My friend gave me this Arduino code:
int button;
void setup(){
pinMode(12, INPUT);
}
void loop(){
for(button; button == HIGH; button == digitalRead(12)) { //This line
//Do something here
}
}
The line commented with "this line" is unclear to me.
I've always seen a for loop like:
for (init; condition; increment)
Also used in different ways, like:
for(int i=0; i<n; i++){}
for(;;){}
And so on, but I've never seen something like the code I got from my friend.
It does compile on the Arduino IDE, so what is the meaning of this specific for loop?
In other words, what kind of loop is it, and how does it work?
This loop:
for(button; button == HIGH; button == digitalRead(12))
is equivalent to:
button; // does nothing - should probably be `button = HIGH;` ?
while (button == HIGH) // break out of loop when button != HIGH
{
//do something here
button == digitalRead(12); // comparison - should probably be assignment ?
}
Note: I suspect the whole loop is buggy and should probably read:
for (button = HIGH; button == HIGH; button = digitalRead(12))
// do something here
Firstly, let's interpret this literally. Converts to while loop as:
button; // does nothing
while(button == HIGH) { // clear
// do stuff
button == digitalRead(12); // same as digitalRead(12);
}
This code really should be setting off a lot of IDE or compiler warnings. Anyway my answer is correct, that's what it literally converts to. Note that button == digitalRead(12) is valid but does nothing with the result of the comparison.
Most likely the code is buggy. One hypothesis is the == should be =.
Related
I'm trying to write a program in which the end screen of the game only shows up after the last animation finishes. I'm using a counter that's implemented after each object is removed (which is only after it finishes its animation), and when that counter gets to zero, it should show the end screen. Unfortunately, from what I can tell, the counter statement isn't registering at all. I've inserted a print statement that isn't functioning.
var star;
var score;
var counter;
function setup() {
createCanvas(600,400);
score = 0;
counter = 20;
for (var s = 0; s < 20; s++) {
star = createSprite(random(width), random(height));
star.addAnimation("idle", idleAnim);
star.addAnimation("explode", explAnim);
star.changeAnimation("idle");
star.onMousePressed = function() {
this.changeAnimation("explode");
this.animation.looping = false;
score +=1
if (this.getAnimationLabel() == "explode" && this.animation.getFrame() == this.animation.getLastFrame()) {
this.remove();
counter -= 1;
print(counter);
}
}
}
}
function draw() {
if (score == 20 && counter == 0) {
background(255,222,51)
textSize(90);
fill(0)
text("YOU WIN!",95,225)
} else {
drawSprites();
}
}
You need to take a step back and debug your program. For example, are you sure the star.onMousePressed() function is firing? Are you sure the if statement is working the way you expected? Are you sure the player.dir() function is being called?
It sounds like your if statement is not being entered. can you find out the value of everything on that line? Which thing has a different value from what you expected?
Use console.log() statements, or use the JavaScript debugger, to answer all of the above. Figure out exactly which line of code is behaving differently from what you expected, and then isolate that problem in a MCVE. Good luck.
Trying to make simon says game as my semester project, problem is I cant add a delay between the colors when they change,
i.e i want to add a delay so that when one box color changes, then after about 3~4 seconds the next box color changes, but the problem is when I put the Sleep() in my for loop, the system pauses for the amount given as a whole, then displays all the colors changed at the same time not one by one....
Any help, here is the function that i call when the game's start button is clicked. How to fix it ?
void flash()
{
srand(time(NULL));
int x;
for (int i = 5; i > 0;i--)
{
x = rand() % 4;
if (x == 0)
{
button1->BackColor = System::Drawing::Color::Blue;
}
else if (x == 1)
{
button2->BackColor = System::Drawing::Color::Blue;
}
else if (x == 2)
{
button3->BackColor = System::Drawing::Color::Blue;
}
else if (x == 3)
{
button4->BackColor = System::Drawing::Color::Blue;
}
Sleep(500);
}
}
P.s I have tried to put the sleep in the if statements but that doesn't work either, Any help please ?
As your code is single-treaded and you are updating the colors of the buttons in a loop, there is (currently) no chance for the application's standard drawing routines to kick in, until the loop is finished. If you do want a redraw while being in the loop, you have to manually issue it by (e.g.):
button1->Invalidate();
button1->Update();
Please be aware that, if you stay in the loop for too long, windows does recognize that your application is not responding to windows messages and renders it "unresponsive" (window fading to half white). To circumvent this, you can use the Timer class from System::Windows::Forms to implement the delay behaviour.
In the code block below I am trying to move a rectangle once for every key-press but the rectangle moves as long as I hold down a key.
ALLEGRO_EVENT ev;
while(!done)
{
al_wait_for_event(event_queue, &ev);
if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_UP:
pos_y -= 10;
break;
case ALLEGRO_KEY_DOWN:
pos_y += 10;
break;
case ALLEGRO_KEY_RIGHT:
pos_x += 10;
break;
case ALLEGRO_KEY_LEFT:
pos_x -= 10;
break;
}
}
else if(ev.type == ALLEGRO_EVENT_KEY_UP)
{
if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
done = true;
}
al_draw_filled_rectangle(pos_x, pos_y, pos_x + 30, pos_y + 30, al_map_rgb(255,0,255));
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
}
Also I noticed that al_wait_for_event is not waiting for a new event in case of holding down a key but is in fact making the event of type ALLEGRO_EVENT_KEY_CHAR . Although this should not pose any problem , I wanted to know a bit more about it.
Also, the above code is taken from a tutorial. It worked fine over there.
To make sure your app doesn't apply the key press more than once per Key_Down event define a Boolean initialized to false. Place everything in your Key_Down events in an If statement triggering only if Boolean == false and in its block immediately set Boolean = true followed by the things you want the event to do only once per event.
Then, in the corresponding Key_Up event set
Boolean = false and you should be golden.
I haven't tested this, but it should work, and it serves towards compating your app to any client computer, no matter if they have funky key press settings on their device.
I'm working on a legacy app that is not just spaghetti, but turns to egg shells when broken (Humpty Dumpty syndrome), where figuring out what is going on as the code meanders around like a drunken sailor in Old Manila is like trying to find a poodle in a smokestack.
As an example, here is a method that I must grok; this is just the first part of it:
private void InitializeBackgroundThread( LoginStatuses loginStatus, string DialogCap )
{
try
{
double pause = 1;
int wait = 250;
ProgressChangedFlag = false;
ProgressChangedIndex = 0;
pc = new PendingCommands( pause, wait );
PendingCommands.ProcessCommands = true;
if (!((loginStatus == LoginStatuses.LoginVendors) || (loginStatus == LoginStatuses.LoginInventory)))
PendingCommands.Processing = false;
PendingCommands.Timeout = false;
Util.StopCancelRequested = false;
if( timeOut != "" )
pc.timeOut = timeOut;
if (!((loginStatus == LoginStatuses.LoginVendors) || (loginStatus == LoginStatuses.LoginInventory)))
{
InitializeBackgroundThread_CCRLoginTerminate (true);
InitializeBackgroundThread_CCRTimerExceeded (true);
InitializeBackgroundThread_CCROnline (true);
}
if (loginStatus == LoginStatuses.LoginVendors)
{
InitializeBackgroundThread_CCRCommandConfirmedGetsites (false);
InitializeBackgroundThread_CCRCommandConfirmed (false);
InitializeBackgroundThread_CCRCommandConfirmedSitesetup (true);
}
else if (loginStatus == LoginStatuses.LoginSitesData)
{
InitializeBackgroundThread_CCRCommandConfirmed (false);
InitializeBackgroundThread_CCRCommandConfirmedSitesetup (false);
InitializeBackgroundThread_CCRCommandConfirmedGetsites (true);
}
else
{
InitializeBackgroundThread_CCRCommandConfirmedSitesetup (false);
InitializeBackgroundThread_CCRCommandConfirmedGetsites (false);
InitializeBackgroundThread_CCRCommandConfirmed (true);
}
InitializeBackgroundThread_CCRProgress (true);
InitializeBackgroundThread_CCRProgressChanged (true);
InitializeBackgroundThread_CCRProgressComm (true);
Now I can "deskcheck" it by going through it with a notepad, asking myself, "Okay, what will happen - which variables will be assigned which values, and which methods will be called - if loginStatus is "AllQuiet"? What if loginStatus is "SNAFU"? Etc. etc. ad nauseum.
Wouldn't it be great if a tool could eat this spaghetti right up and spit out a report such as:
*With a loginStatus of "AllQuiet"
PendingCommands.Processing is set to true.
InitializeBackgroundThread_CCRProgressChanged is called.
...
With a loginStatus of "SNAFU"
(etc.)*
This would be a "killer" debugging/sanity check tool. I know there are code coverage tools, but are there any that are this sophisticated?
This isn't code coverage, which simply tracks what code gets executed if you run a specific test.
What you want is something like a cross between program slicing ("show me everything downstream/upstream from some code point" aka 'a slice' http://en.wikipedia.org/wiki/Program_slicing),
and partial evaluation ("show me what this code looks like if I assume some value is a specific constant" http://en.wikipedia.org/wiki/Partial_evaluation). And you want it to display the result superimposed on top of your actual code (e.g. boldface the selected part) to see your focus.
Yes, that would be wickedly nice tool.
No, I don't know of any. There are program slicers for C and C++ (See http://www.grammatech.com/research/technologies/codesurfer). I don't think they have the partial evaluation part, but I think they do have some other options to minimize the size the slice being inspected.
The most egregiously redundant code construct I often see involves using the code sequence
if (condition)
return true;
else
return false;
instead of simply writing
return (condition);
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
if (foo == true)
{
do stuff
}
I keep telling the developer that does that that it should be
if ((foo == true) == true)
{
do stuff
}
but he hasn't gotten the hint yet.
if (condition == true)
{
...
}
instead of
if (condition)
{
...
}
Edit:
or even worse and turning around the conditional test:
if (condition == false)
{
...
}
which is easily read as
if (condition) then ...
Using comments instead of source control:
-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.
-Adding comments like "RWF Change" instead of just making the change and letting source control assign the blame.
Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:
return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);
:-)
Redundant code is not in itself an error. But if you're really trying to save every character
return (condition);
is redundant too. You can write:
return condition;
Declaring separately from assignment in languages other than C:
int foo;
foo = GetFoo();
Returning uselessly at the end:
// stuff
return;
}
I once had a guy who repeatedly did this:
bool a;
bool b;
...
if (a == true)
b = true;
else
b = false;
void myfunction() {
if(condition) {
// Do some stuff
if(othercond) {
// Do more stuff
}
}
}
instead of
void myfunction() {
if(!condition)
return;
// Do some stuff
if(!othercond)
return;
// Do more stuff
}
Using .tostring on a string
Putting an exit statement as first statement in a function to disable the execution of that function, instead of one of the following options:
Completely removing the function
Commenting the function body
Keeping the function but deleting all the code
Using the exit as first statement makes it very hard to spot, you can easily read over it.
Fear of null (this also can lead to serious problems):
if (name != null)
person.Name = name;
Redundant if's (not using else):
if (!IsPostback)
{
// do something
}
if (IsPostback)
{
// do something else
}
Redundant checks (Split never returns null):
string[] words = sentence.Split(' ');
if (words != null)
More on checks (the second check is redundant if you are going to loop)
if (myArray != null && myArray.Length > 0)
foreach (string s in myArray)
And my favorite for ASP.NET: Scattered DataBinds all over the code in order to make the page render.
Copy paste redundancy:
if (x > 0)
{
// a lot of code to calculate z
y = x + z;
}
else
{
// a lot of code to calculate z
y = x - z;
}
instead of
if (x > 0)
y = x + CalcZ(x);
else
y = x - CalcZ(x);
or even better (or more obfuscated)
y = x + (x > 0 ? 1 : -1) * CalcZ(x)
Allocating elements on the heap instead of the stack.
{
char buff = malloc(1024);
/* ... */
free(buff);
}
instead of
{
char buff[1024];
/* ... */
}
or
{
struct foo *x = (struct foo *)malloc(sizeof(struct foo));
x->a = ...;
bar(x);
free(x);
}
instead of
{
struct foo x;
x.a = ...;
bar(&x);
}
The most common redundant code construct I see is code that is never called from anywhere in the program.
The other is design patterns used where there is no point in using them. For example, writing "new BobFactory().createBob()" everywhere, instead of just writing "new Bob()".
Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.
I often run into the following:
function foo() {
if ( something ) {
return;
} else {
do_something();
}
}
But it doesn't help telling them that the else is useless here. It has to be either
function foo() {
if ( something ) {
return;
}
do_something();
}
or - depending on the length of checks that are done before do_something():
function foo() {
if ( !something ) {
do_something();
}
}
From nightmarish code reviews.....
char s[100];
followed by
memset(s,0,100);
followed by
s[strlen(s)] = 0;
with lots of nasty
if (strcmp(s, "1") == 0)
littered about the code.
Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower.
Redundant .ToString() invocations:
const int foo = 5;
Console.WriteLine("Number of Items: " + foo.ToString());
Unnecessary string formatting:
const int foo = 5;
Console.WriteLine("Number of Items: {0}", foo);