Im getting more and more frustrated on why this is not doing what i want to. I need to have a text file that logs the last 10 buttons the user pressed, i tried in two ways but…
…this code only saves the last button pressed:
String [][] buttonsPressed = { {"Pressed one"}, {"Pressed two"} };
String[] sum;
void setup() {
size(700, 350);
sum = loadStrings("scores.txt");
}
void draw() {
}
void keyPressed() {
if ((key=='1')) {
saveStrings("scores.txt", buttonsPressed[0]);
}
if ((key=='2')) {
saveStrings("scores.txt", buttonsPressed[1]);
}
if ((key == ENTER)) {
printArray(sum);
}
}
…this code saves the buttons pressed but overwrites itself when i run the sketch again (probably has something to do with createWriter):
PrintWriter sum;
void setup() {
size(700, 350);
sum = createWriter("scores.txt");
}
void draw() {
}
void keyPressed() {
if ((key=='1')) {
sum.println("pressed one");
}
if ((key=='2')) {
sum.println("pressed two");
}
if ((key == ENTER)) {
sum.flush();
sum.close();
String[] lines = loadStrings("scores.txt");
for (int i = 0; i <= 9; i++) {
printArray("[" + i + "] " + lines[i]);
}
}
}
Is there a simple way to do this without using libraries ? Please get me in the right direction :)
Break your problem down into smaller steps.
Step 1: At the beginning of your program, read in the existing history file. Store them in some kind of data structure, like an array or an ArrayList.
Step 2: Make the data structure keep track of the last 10 buttons pressed. You'll need to write code that adds the newest button pressed to the end of the data structure, and if the data structure contains more than 10 items, you have to remove the oldest item. Maybe do this in a separate example sketch where you just print the data structure to the console and don't worry about outputting it to a file just yet.
Step 3: Output the data structure to a file. You don't have to worry about appending to the file because your data structure contains the entire history, so you can just overwrite the file with the entire data structure. You'll probably want to do this every time the data structure changes. Again, maybe do this in a separate example program before worrying about where the data is coming from: maybe make a program that outputs an array of random numbers every time the user clicks?
Focus on one small step at a time, and try creating small example programs for each step. Then when you get stuck, you can ask a specific question and provide an MCVE, and we'll go from there. Good luck.
Related
I wrote the code what get Json data and put in listPc. And wrote the loop that add value 'hostName' form listPc to pcBusy List. But my code only add values to second list, If I press GetButton values in pcBusy list duplicates. I need to update the pcBusy List, not only add the same values.
This print if I press button two times:
[S14, S18, S19, S12, S02, V08, S01, O09, S14, S18, S19, S12, S02, V08, S01, O09]
Thanks for help!)
void fetchDataStandart() async {
final urlAuth =
Uri.parse('http://XXX.XX.XXX.XXX/api/usersessions/activeinfo');
final response = await http
.get(urlAuth, headers: <String, String>{'authorization': basicAuth});
if (response.statusCode == 200) {
List listPc = List.from(json.decode(response.body)['result']);
for (int i = 0; i < listPc.length; i++) {
pcBusy.add(listPc[i]['hostName']);
}
print(pcBusy);
} else {
throw Exception('Ошибка получения данных');
}
}
TLDR: add Future<void> as your function return type and consider invoking pcBusy.clear() before overwriting with new data (depends on your logic, though).
With a little more context you'd help me giving you a more complete answer, but here's what I can see from your code:
Your button adds data as many times as you're pressing it. IF you press it two times, you'll get "double" the data, sooner or later. This happens because you use the add method, which just appends data on your list. You can either reset the values with pcBusy.clear() before you add values or do something else if you think that this function shouldn't be overwriting your list. This really depends on your logic;
You're awaiting a Future (via the async keyword), yet your Function doesn't return a Future. This means that - most likely - somewhere else you're awaiting for this function that in reality doesn't need to be awaited. As a consequence this means that when you first press the button, i.e. you fire the future, you can't await for it to happen and your UI doesn't update. The second time, it does update your UI with the previous result and the Future is fired again, letting it update your list with twice the values again as explained in step (1).
Hope this helps. EDIT. Here's some edited code:
// we want this function to be awaited: let it be a Future<void> async function
Future<void> fetchDataStandart() async {
// ... firing an async HTTP request
if (response.statusCode == 200) {
// if everything is OK, decode the JSON
List listPc = List.from(json.decode(response.body)['result']);
// the following will OVERWRITE the list.
pcBusy.clear(); // Or maybe save previous data somewhere else?
for (int i = 0; i < listPc.length; i++) {
pcBusy.add(listPc[i]['hostName']);
}
print(pcBusy);
} else {
throw Exception('Ошибка получения данных');
}
}
To remove duplicates you can convert the list to a set then back to a list again.
pcBusy.toSet().toList();
This is my first year of vex. I am taking on the role of programmer.
I have had this idea for rapid autonomous creation, recording the driver. Instead of the usual array/debugger dump of raw streams of power levels, I had the idea of extracting functions from driver movement.
I wont go into the details, and I can code it myself, but I need some help.
There is one thing I am unable to do simply because of my lack of coding experience.
I want to create a for loop that checks every joystick button one by one.
For example:
struct button
{
bool pressed;
}
for(int i = 0; i>12; i++) //12 is number of buttons on the joystick
{
struct button button<cycle through buttons>;
}
I want there to then be:
struct button button6U;
struct button button6D;
struct button button6R;
etc.
Then, I want this:
for(int i = 0; i>12; i++) // 12 is number of buttons on the joystick
{
if(VexRT[<currentButton>])
{
button<currentButton>.pressed = true;
}
}
I have no idea how to do this, with a wildcard modifing the actual variable name I am writing to.
A couple thoughts:
A for statement would have no idea how to advance the order of joystick buttons. So something I think I might need is:
orderOfButtons
{
VexRT[6U];
VexRT[6D];
VexRT[6R];
// etc.
}
I just cant seem to figure out how to have a variable defining what VexRT[]button I am reading from.
Any help would be appreciated!
Thanks.
Sounds like you want an array:
#define NUMBER_OF_BUTTONS 12
...
struct button VexRT[NUMBER_OF_BUTTONS];
If you want to use symbolic constants to refer to specific buttons in the array, you can use an enumeration:
enum btn_id { BTN_6U, // maps to 0
BTN_6D, // maps to 1
BTN_6R, // maps to 2
...
}
Enumeration constants are represented as integers, and by default they start at 0 and increment by 1. You can initialize them to different values if you want, and multiple enumeration constants can map to the same value. I take advantage of this when I want to identify a "first" and "last" enumeration for looping, like so:
enum btn_id {
BTN_6U,
BTN_FIRST = BTN_6U, // both BTN_FIRST and BTN_6U will map to 0
BTN_6D,
BTN_6R,
...
BTN_whatever,
BTN_LAST
};
Thus, VexRT[BTN_6U] maps to VexRT[0], VexRT[BTN_6D] maps to VexRT[1], etc.
Note that this way, you don't have to loop through all the buttons just to set one:
enum btn_id currentButton = BTN_6D;
...
VexRT[currentButton].pressed = true;
If you do want to loop through the whole set, you can use
for ( enum btn_id i = BTN_FIRST; i < BTN_LAST; i++ )
{
VexRT[i].pressed = false;
}
So, what you want is to sample the user input (at some specified rate), then record it into an array, then play that back at a later time? If you have functions that drive the VEX (I'm not familiar with that), each of which are associated with an input, you can use an array of function pointers to create your output.
#define MAX_ACTION 12
#define MAX_RECORDED 200
// Declare your array of function pointers
int (*action[MAX_ACTION])(void);
// Declare your stored array of recorded actions
int recorded[MAX_RECORDED];
...
// Assign function pointers to associated functions
action[0] = go_forward;
action[1] = turn_right;
...
// Record your actions into some array
while (...)
{
// Record the action
recorded[i++] = get_action();
// Sample delay
}
...
// Playback the actions
for (i=0;i<RECORDED;i++)
{
(*action[recorded[i]])();
// delay here
}
P.S. Your for loop is backward (i<12 not i>12).
I think you are trying to access the events coming from the joystick. You can just loop through the array of values and record them. I think the channels on the joystick are simply accessed like: vexRT[x] where x is 1-12. If you just want to store the latest value from each channel you could do this:
int value[12];
for(i=0; i<12; i++)
{
value[i] = vexRT[i];
}
If you want to store all of the values so that you can map them or play them back or something then you will need a more complex data structure to store them, like a list of the value arrays.
I also have found documentation that says the values are accessed by like vexRT[Chx] where x is 1-12, so you could alternatively create a string and use it to access the joystick channels inside your loop:
string *s = (char *)malloc(5*sizeof(char)); //5 is the max length of the null terminated string
for() . . . {
sprintf(s,"Ch%d", i);
value[i] = vertRT[s];
}
I've been on and off creating a text adventure using a rudimentary engine I made for about a year.
For the story, I have a object array(is that what it's called?) with various story data stuff that I parse through
I've been told that using it the way I am is stupid because it's supposed to be used for other stuff but I only use it because it was easy to learn how to parse the data since I was a beginner
It's getting tedious writing the story and doing stuff for each part (creating the backgrounds and such) since it's so long.
Is there any kind of way I can make it easier for me to write the story?
Here's the object array with a single part set up (with choices)
public static var parts:Object =
{
"0":
{
"text":"Text here",
"choices":
{
"response1":
{
"text":"Response1",
"nextPart":"1"
},
"response2":
{
"text":"Response2",
"nextPart":"2"
}
},
"background": Assets.AssetClass.Background1,
"BGM":"bg1"
},
}
Here's an example of how my engine deals with parts and changing them:
I have a input checker to check when enter is pressed and then do stuff depending on what is on the screen
public function onEnter(button:KeyboardEvent):void
{
if (button.keyCode == 32 && !Won)
{
if (Dead && textFinished && !choosing) // pressing enter while dead and the text is still writing
{
curPart = parts[curPart]["lastPart"] // lastPart will only be stored in parts that have the player die
textFinished = false
Dead = false;
myTextField.text = ""
counter = 0;
sInt = setInterval(addCharackter, textSpeed)
if (stage.getChildByName("cText"))
{
stage.removeChild(continueText)
}
if (parts[curPart].hasOwnProperty("background")) //check if the background needs to change.
{
if (stage.getChildByName("img"))
{
stage.removeChild(background)
}
background = new Background(parts[curPart], 800, 600)
stage.addChildAt(background, 0)
}
}
if (!textFinished && !choosing)// pressing enter when there's no choices on the screen and the text isn't finished and the text is still writing
{
this.myTextField.text = this.parts[this.curPart]["text"];
clearInterval(this.sInt);
this.textFinished = true;
if (parts[curPart].hasOwnProperty("choices"))
{
choosing = true
createOptions(); // function for parsing through the responses bit of that part and displaying them
}
else
{
stage.addChildAt(continueText, 2)
}
if (parts[curPart].hasOwnProperty("lastPart"))
{
Dead = true;
dead()
}
}
else if (textFinished && !choosing && !Dead) // pressing enter if there's no choices on the screen and there's no choices (it'll take you to the next part)
{
trace("Text finished!!")
curPart = parts[curPart]["nextPart"]
myTextField.text = ""
counter = 0;
sInt = setInterval(addCharackter, textSpeed)
textFinished = false;
if (parts[curPart].hasOwnProperty("background"))
{
if (stage.getChildByName("img"))
{
trace("Removed!")
stage.removeChild(background)
}
background = new Background(parts[curPart], 800, 600)
stage.addChildAt(background, 0)
}
if (parts[curPart].hasOwnProperty("BGM")) // does the current part have a new background music?
{
trace("Music!!!!")
sndBGMusic = musicArray[parts[curPart]["BGM"]]
sndBGMusicChannel.stop()
sndBGMusicChannel = sndBGMusic.play(0, 9999999999)
stage.addChildAt(background, 0)
}
stage.removeChild(continueText)
}
}
}
A couple ideas here. These are just things I would do differently than what you have done. I don't guarantee that they are better in any way, but see what you think.
I would have a global variable for _curPart. And I would have a custom class called Part. That class would have properties like _BGM, _bgImage etc. It could have a _choicesArray as a property as well. I'd have other global variables like _hasCandle. Or you can store items in an array and if you need the candle just check if candle is in the array. These global variables will persist from one part to the next.
Then you can access the properties of the part you are in by doing _curPart._bgImage. To me, that looks and feels cleaner.
And to create a new part it could look like (incomplete):
var p15:Part = new Part();
p15._bgImage = image15;
p15._BGM = song10;
//...
The last thing I'd recommend is to try to refactor where you can. For example, where you have //pressing enter if there's no choic... replace all of that code in that bracket with a one or a few function calls (whatever makes the most sense and allows you to reuse code). It just makes it easier to see what's going on, I think. So instead of all these if blocks, just a function like nextPart(); and then that function will have all your if blocks in it. Make sense? Personal preference, but when things are getting complicated, refactoring helps me clear out the cobwebs. Just like you do with dead() and createOptions() but I'd just take it one step further. This won't make your code more efficient, but it might make writing your code more efficient which is paramount in my book (until it's not).
I have a csv file which contains the numbers of buttons. I want to make a function that reads these numbers and set the number of a class that I have made and called FButton.
First I have declared an array of FButtons in my header file.
FButton buttons[10];
Now in the cpp file I have written the following code to set the numbers of the buttons:
QFile f("Buttons.csv");
if (f.open(QIODevice::ReadOnly))
{
int i=0;
QString data;
data = f.readAll();
QStringList vals = data.split(';');
while (!vals.isEmpty())
{
buttons[i].setNumber(vals[0].toInt());
vals.removeAt(0);
i++;
}
f.close();
}
The function setNumber is given by:
void FButton::setNumber(int butNumber)
{
number=butNumber;
}
It is possible for me to build the code, but when i try to run it an error occurs:
GUI.exe is no longer working.
Can somebody tell me what is wrong with my code?
Wouldn't you have more values in your CSV than the size of buttons array (or whatever collection it is) ? Or having uninitialized objects in buttons ?
I was working on a test project that I will later incorporate into a much larger work that is a simple quiz game. I made an array with my questions:
var questions1:Array=["nitrogen dioxide","sulfur hexafluoride",..."]
and in a second layer I made a button that cycles through the questions randomly.
import flash.events.MouseEvent;
var qno=0;var rnd1;
function change_question(){
rnd1=Math.ceil(Math.random()*questions1.length)-1;
q.text=questions1[rnd1];
if(questions1[rnd1]=="X"){change_question();}
questions1[rnd1]="X";
}
change_question();
next_b.addEventListener(MouseEvent.CLICK, ButtonAction1);
function ButtonAction1(eventObject:MouseEvent){
qno++;change_question();
}
This part works great, because I was following a tutorial. Text appears in a dynamic text box I created as it should. This tutorial taught to change the value of the array to X with every choice and to ignore choose a different question every time it encountered an X
After it cycles through all the questions I basically get an infinite loop in my output section of flash because it can't find any more non-X values. I was hoping someone had information on how to press a button an change the array back to its default settings so that a teacher (because that is who it is for) has a way of resetting the file when they have reached the end of the quiz.
Thanks everyone!
As per my understanding you wanted to randomize your questions and after showing all the entire questions you wanted to reset your questions.
As per your code you get a random question and updating the same array by pushing value 'X'. Rather than doing this what you need to do is to preserve the array only randomize its position. So that you can use the same value once you cover your all questions
I have added code here.
import flash.events.MouseEvent;
var qno=0;var rnd1;
var questions1:Array=["nitrogen dioxide","sulfur hexafluoride","carbon dioxide","carbon monooxide"];
var nAttmeptedCount = 0;
var shuffledLetters:Array;
function change_question()
{
if(qno == questions1.length)
{
qno = 0;
resetQuestion()
}
else
{
q.text = questions1[shuffledLetters[qno]];
qno++;
}
}
function resetQuestion()
{
shuffledLetters = new Array(questions1.length);
for(var i=0;i<shuffledLetters.length;i++)
{
shuffledLetters[i] = i;
}
shuffledLetters.sort(randomize);
}
function randomize ( a : *, b : * ) : int {
return ( Math.random() > .5 ) ? 1 : -1;
}
resetQuestion()
change_question();
next_b.addEventListener(MouseEvent.CLICK, ButtonAction1);
function ButtonAction1(eventObject:MouseEvent){
change_question();
}
In above solution after showing all questions I have reset the questions automatically. you can modify code as per your requirement. If you want to do the reset questions you can put you code qno = 0;resetQuestion() on button click.
hope above solution work for you.