Adding a delay in my code, not working. C++ - windows

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.

Related

Unity c# having trouble getting it too detect when a key is not pressed

if (Input.GetKeyDown("z") == true)
{
moveSpeed = 10;
}
else if (Input.GetKeyDown("z") == false)
{
moveSpeed = 5;
}
that is the code.
When it runs it seems to detect that z is pressed and than set moveSpeed to 10. But than it fails to detect that z is not pressed and resets moveSpeed back to 5.
I have tried a few variations of this code, all seem to have the same result.
you must use Input.GetKeyUp("z")

p5.play counter not working

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.

Allegro 5 detects long key press as several key presses

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.

What kind of 'for' loop is this?

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 =.

Joystick won't work using SDL

I'm building a simple game in SDL. I've been through countless tutorials and I've clearly missed something as it still ignoring my Joystick completely
In my constructor
SDL_JoystickEventState(SDL_ENABLE);
joystick = SDL_JoystickOpen(0);
In my update I'm calling a test to check I have actually initialized the joystick
if (SDL_NumJoysticks() <= 0)
{
done = true;
}
Here is my player update as well
void World::playerMovement()
{
SDL_Event event;
while (SDL_PollEvent (&event))
{
switch (event.type)
{
case SDL_QUIT:
done = true;
break;
case SDL_JOYAXISMOTION:
if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) )
{
test = true;
}
break;
}
}
}
Test is simply a bool which once true will mean my enemies start spawning. I also run a check in main
if (SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0)
{
fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
done = true;
}
When I run the game it loads as normal but no matter how much I move the joystick it won't set test to true.
I also tried using the following in the while poll event loop instead.
if (event.type == SDL_JOYAXISMOTION)
{
if(SDL_JoystickGetAxis(joystick, 1) > 0)
{
test = true;
}
}
Any idea's what I have missed?
I think emartel has the best answer to make sure SDL_joystick is working.
When does World::playerMovement() happen? The overall flow of your program is hard to determine from these snippets.
I'm happy to share with you my code for handling joysticks, which keeps track of: multiple joysticks, axes scaled [-1,1] with deadzone removed, and buttons held down.
http://www.raptor007.com/code/RaptorEngine_Joystick.zip
And here's a snippet of how that would be utilized as part of your main loop:
// FIXME: SDL needs to be initialized before we get here.
JoystickManager Joy;
Joy.Initialize();
double deadzone = 0.02;
// Main loop.
bool done = false;
while( ! done )
{
// Keep the list of joysticks up-to-date.
Joy.FindJoysticks();
// Handle all user input.
SDL_Event event;
while( SDL_PollEvent( &event ) )
{
// Let the JoystickManager track events relevant to it.
Joy.TrackEvent( &event );
// FIXME: Handle single-press events here (next target, etc).
// Don't handle button-held-down events like firing (see below).
if( event.type == SDL_QUIT )
done = true;
}
// Read joystick 0 analog axes.
double roll = Joy.Axis( 0, 0, deadzone );
double pitch = Joy.Axis( 0, 1, deadzone );
double yaw = Joy.Axis( 0, 3, deadzone );
double throttle = Joy.AxisScaled( 0, 2, 1., 0., 0., deadzone );
// Read joystick 0 buttons held down.
bool firing = Joy.ButtonDown( 0, 0 );
// FIXME: Update game objects and draw graphics.
}
I found a weird behaviour in SDL2:
If no events are put into the queue, try adding the following before the SDL_Init call:
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,"1");
Are you sure joystick points to a valid joystick?
You state that you're getting it in your Constructor... does that contructor happen to be called before you initialize SDL with SDL_INIT_JOYSTICK? This could happen if your player is a global variable.
Make sure that in order you:
Init the Joystick subsystem, either by adding it to your SDL_Init with | SDL_INIT_JOYSTICK or by calling SDL_InitSubSystem(SDL_INIT_JOYSTICK);
Check SDL_NumJoysticks() > 0
Get joystick 0: joystick = SDL_JoystickOpen(0);
Enable events: SDL_JoystickEventState(SDL_ENABLE);
Process your events with SDL_PollEvent
At the end of your program, close your joystick: SDL_JoystickClose(joystick);
Also, make sure the joystick is properly detected in Windows and reports its inputs properly.
Looks like your SDL isn't init proper.
replace
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)
with
SDL_Init(SDL_INIT_EVERYTHING)
Is this SDL 1.2 or 2.0? In my case, on 2.0 SDL_PollEvent(&event) didn't actually put any data in the event struct. After that call, I had to use SDL_JoystickGetAxis(joystick_id, axis) and friends to get data.
So in your case, try to move the SDL_JoystickGetAxis call out of the if-test on event-type.
If you call SDL_NumJoysticks to get the number of controllers connected, then call SDL_JoystickOpen which returns a joystick identifier before your game loop then you will receive the SDL_JOYAXISMOTION events.
e.g.
int num_joy;
num_joy = SDL_NumJoysticks();
printf("%d joysticks found\n", num_joy);
for(int i = 0; i < num_joy; i++)
{
SDL_Joystick *joystick = SDL_JoystickOpen(i);
printf("Joystick name: %s\n", SDL_JoystickName(joystick));
}
SDL_Event event;
bool quit = false;
// Game loop
while(!quit)
{
// event loop
while(SDL_PollEvent(&event))
{
if (event.type == SDL_JOYAXISMOTION)
{
printf("Joystick______EVENT!\n");
}
// etc.....
See https://wiki.libsdl.org/SDL_JoystickName
I do not know how this can help you, but I do know that pygame supports joystick. And pygame is the python port of the SDL library. If everything fails, I guess you can always write that particular piece of code in python.

Resources