Multiple message boxes appear instead of one - vb.net

I am designing a Breakout style game in VB and am having some minor problems with my code.
I am checking for collisions between the ball and the 4 sides of the form. So, as the ball collides with the bottom of the form, the game is meant to display a message box saying "You Lost!" with the Retry and Cancel buttons.
This is what I have coded under my Timer1_Tick event:
'check bottom of screen
If PictureBox_ball.Top >= 403 Then
'403 is the Y-coordinate of a horizontal line I have implemented
MsgBox("You Lost!", MessageBoxButtons.RetryCancel)
End If
However, when I run this code, the game displays multiple message boxes (around 25 of the same ones) instead of displaying one. And it doesn't stop there.
As the ball moves downwards and hits the bottom of the screen, the ball stops moving, displays a bunch of message boxes and then continues to move downwards and out of the screen.
How would I be able to fix this?

This is what I have coded under my Timer1_Tick event:
Stop your timer before you call out your msgBox
WHY ??
Because the the timer is always ticking, and as it ticks, it displays your msgBox.
Just try it, I had the same problem before on my projects.

The above code is in your main loop. Since you don't change any other flag (like : game_over = True or disarm the timer tick), the loop keeps running, the value is still matching the condition, and you get all those MessageBoxes
For example:
If not you_lost
if PictureBox_ball.Top >= 403 Then '403 is the Y-coordinate of a horizontal line I have implemented
MsgBox("You Lost!", MessageBoxButtons.RetryCancel)
you_lost = True
End If
end if

Related

How to prevent form entry errors with radio button appearance and validation in VBA Word

I am creating an electronic checklist for a manufacturing process. Operators will have a series of tasks that they must identify are complete with a Yes/No option. Originally I used check boxes but because we want to validate the form is correctly filled out, I changed them to radio buttons under ActiveX controls. I intend to have the default value of both buttons as False so that the form appears blank when opened, then upon hitting a submit button it validates that all tasks are complete.
Originally I thought I could Group the Y/N's and iterate through opt_yes.value and opt_no.value with the group#, but that doesn't work. So Now I'm not sure how to do it without writing out code for all 19 tasks.
I've started a Function to validate my text entries:
Private Function EverythingFilledIn() As Boolean
EverythingFilledIn = True
With ActiveDocument.FormFields("Time")
If Len(.Result) < 1 Then
Application.OnTime When:=Now + TimeValue("00:00:01"), Name:="GoBackToTime"
MsgBox "What time is it?"
EverythingFilledIn = False
End If
End With
With ActiveDocument.FormFields("Cut")
If Len(.Result) < 1 Then
Application.OnTime When:=Now + TimeValue("00:00:01"), Name:="GoBackToCut"
MsgBox "What is the Cut Number"
EverythingFilledIn = False
End If
End With
And I'm wondering if I can get help on the radio button validations, or an insight to looking at it a different way. I have spent a couple of weeks on forums and learned nuances of radio buttons vs. check boxes, grouping and form validating but somehow none of it has addressed my situation.
1: The radio buttons should all be set to False upon opening template: Done
2. The radio button selected will be highlighted [radio1_Change()]: Done
3. Upon hitting Submit button, validation will alert operator of skipped tasks: ie both button values still False = exit Sub: Need Help Here
Currently the radio buttons are numbered and grouped per task: ie grp_1 has radio1(y) and radio2(n); grp_2 has radio3(y) and radio4(n) etc. I was hoping that this would make it easy to iterate through.

Wait for 1 second before starting code again - VB.NET

I desperately need help with a game I am making. For a bit of context, i am making a memory game and i have the following piece of code that is being troublesome. I have a bunch of labels on the form, 16 to be exact, with 1 randomly generated symbol placed in each. Each symbol appears in the labels twice.
------------------------------Continued----------------------------------------
'MsgBox("hello") 'used to check if the second inccorect press shows up - it does show but instantly changes colour
'''''''''''''''''NEED SOME CODE THAT PAUSES IT HERE'''''''''''''''
labels(0).ForeColor = Color.DarkRed
sender.ForeColor = Color.DarkRed
End If
flips = 1
End If
End If
tmrmemory.Enabled = True ' starts the timer after the user clicks the first label
End Sub
What's supposed to happen is that when the labels clicked don't match, it should show both the clicked labels for a short period before changing them both back to "DarkRed" which is the colour of the form's background.
I have tried using a timer but then i can't use sender.forecolor=color.darkred because it is not declared globally.
I have also tried using the command Threading.Thread.Sleep(500) but it still doesn't show the second incorrect click. I know that the code i have used works because when i use the message box, i can see both symbols and when the two clicks are correct, it stays.
Threading.Thread.Sleep(500) will actually pause your code for half a second. However during this time it won't do anything, not even refresh your controls. To get the effect you want, you need to call the YourControl.Refresh method before calling Threading.Thread.Sleep to force the control to redraw immediately.
On a side note, I would advise you not to call Threading.Thread.Sleep on UI thread. It will give a feeling of program hang. Instead do your work on a separate thread. You can either do all the work yourself right from creating a separate thread to destroying it, or use the BackgroundWorker control which has all the functionality built in.
Here is the link to an article I wrote a long time ago regarding BackgroundWorker that might be useful for you:
http://www.vbforums.com/showthread.php?680130-Correct-way-to-use-the-BackgroundWorker
Declare a variable outside the sub that stores what label should be flipped when the timer ends.
Label click sets
storedLabel = sender
Timer tick sets storedLabel.ForeColor = Color.DarkRed

Mouse click/release psychopy

I am using the .isPressedIn() function see if the mouse click is in a target shape. However, whenever you click on the target shape, it will say the response is incorrect. However, whenever you hold the mouse button down in the target shape, it will say the mouse was clicked on the target. I'm not sure how to fix the mouse button release. I tried using CustomMouse, but I am unable to get that to click inside a shape (unless I am mistaken). Any suggestions would be greatly appreciated.
Thanks!
stimDuration = 5 #stimuli are on the screen for 5 seconds
potential_target = [shape1, shape2, shape3] #shapes that may be a target
target = random.sample(potential_target, 1) #randomly select a target
myMouse = event.Mouse() #define mouse
if clock.getTime() >= stimDuration
ResponsePrompt.draw() #message to indicate to participant to select target
win.flip()
core.wait(2)
if myMouse.isPressedIn(target[0]):
print "correct"
else:
print "incorrect"
The problem is that the line myMouse.isPressedIn(target[0]) checks the state of the mouse exactly when that line is run. Since it is preceeded by a core.wait(2) it does not react to mouse clicks in those two seconds and consequently only collects the mouse response of you still hold it down after two seconds.
I would instead have a tight loop around the myMouse.isPressedIn which runs thousands of times per second. So skipping your first lines:
ResponsePrompt.draw() # message to indicate to participant to select target
win.flip() # show that message
while True: # keep looping. We will break this loop on a mouse press
if myMouse.isPressedIn(target[0]): # check if click is within shape
print "correct"
break # break loop if this condition was met
elif myMouse.getPressed(): # check if there was any mouse press at all, no matter location
print "incorrect"
break # break while loop if this condition was met
In that code, you are using the expression if myMouse.isPressedIn(target[0]), but are only evaluating that expression after some time has elapsed (stimDuration). This means that isPressedIn() will be typically be evaluated well after the actual click happened. At that point, the mouse may no longer be within target[0], or may not longer be being pressed down by the subject. So I think what you are seeing is the correct (expected) behavior.
So to obtain the behavior that you want, you need to do keep track of whether then mouse was pressed in the shape on every frame.
Also, I am not sure how you are using the code you posted. Some looks appropriate for every frame, but some looks like it should be run only once (Begin routine). You might want to review that--things should not be initialized every frame (like target or myMouse).

How do I make a section of code execute if a button is clicked after another button is clicked in visual basic

So basically what the title says. I want to make a program where you click a button, and then another button shows up, and then if you click the next button in a certain amount of time you get a point.
This is what I found in another thread, but this also makes the timer count down before the second button even shows up, even though this code is after the code making the next button show up.
Do While DoWhileBool = True
Select Case DirectCast(Sender, Button).Name
Case "ClickHere2"
If TimeCount > 0 Then
MultCount += 1
End If
Case "ClickHere3"
If TimeCount > 0 Then
MultCount += 1
End If
This is not the full code by any means, but I just wanted to show what I tried that doesn't work for having a button click event in an if statement inside another button click method.
Edit: I ended up figuring it out partially but pretty much all of what I was asking thanks to the help of the answer:
NumButTim.Stop()
If TimerVar <> 0 Then
MultCount += 1
MultCounter.Text = MultCount
MultCounter.Refresh()
End If
NumButTim.Start()
TimerVar = 5
'Do Until TimerVar = 0
' TimerVar = Timer1.ToString
' TimeCounter.Text = Timer1.ToString
' TimeCounter.Refresh()
'Loop
End Sub
The commented section was where I was trying to get a textbox to show the countdown time, but it doesn't work. I'm sure I could figure it out if I wanted to, but I've moved on to other things. Thanks to the person who answered it, he probably led me to the right answer.
Sidenote: I don't use visual basic anymore, but the idea I had that this was a part of was sort of a mix of clicker game num pad typing and letter key typing and the typing would increase a multiplier for a while. Never really finished that idea and I don't even know if what I had made in that game even exists anymore because my external hard drive went kaput before I had transferred all the old files onto my current computer.
From what i understand of your question, this is how i would do it:
Add a timer, and 2 buttons to the form
On form load, you want to set the interval on the timer, so something like this:
Timer1.Interval = 1000 'Set the interval to 1 second
Then when you click on the first button show the second button, so on button1 click:
Button2.show() 'Show the second button
Timer1.Start() 'Start the timer, so they have 1 second from now
And in button 2 click, you want to do your event, add a point etc:
points += 1
Then to make the second button dissapear, (timeout) after a certian amount of time, you change the interval of the timer1. If the button wants to show for 1 second, set the interval to 1000 (milliseconds)
Then in timer1.tick add this code:
timer1.Stop() 'Stop the timer so that its not ran again and again
Button2.Hide() 'Hide the second button
MsgBox("You was too slow!!") 'Tell the user they missed it, or your code..

Display time left when running

I have a form with a few buttons which execute code when pressed like running validations on the database.
Some code can run for a few minutes so is there any way to show the time remaining or a message to display the % of process completed?
Or pop out a message when code evaluation starts and the message should disappear once code running is completed?
What you are probably looking for is a "Progress Bar".
I've used the Microsoft ProgressBar control (you can find it under Insert->ActiveX Control), and it's not that hard to use. Just set the value of it to a percentage (as an integer, not a decimal).
'foo, being the ProgressBar
me.foo = 70 '70%
There is some good info here on another method: http://www.granite.ab.ca/access/progressbar.htm
In order to do this the "normal" way, you'd need to run your validation in another thread and have it report its progress back to the UI thread. However, I don't believe VBA supports any kind of multithreading.
If your validation routines involve a loop, or even just many separate discrete operations, you can try inserting a DoEvents statement in between loop iterations (or operations), and then have your progress display updated periodically (say, in an Application_OnTime event handler).
I usually have a form I name frmProgress or whatever, with a cancel button and a label for displaying a status message. Then embedded in the form code I have a boolean called bCancel, and when you hit the cancel button it simply sets bCancel as true.
Also in this code I have a routine called ShowPercDone( Idx , NumIdc ) where Idx is the step the code is on, and NumIdc is the number of steps the code will take (assuming each step takes the same amount of time). This works well when I'm running through a for loop, but basically any time I want to display a status update I just call the routine in the form with my message, which I should add runs the doevents command for me.
So that's how the status form works. In the macro I run, I start out by just calling frmProgress.show (0) so that it lets you click the cancel button. Then in my loop when I update the status message I then check frmProgress.bCancel and if it's true I exit out of the macro.
Hope that helps.
Finally to be simple i decided to use the method given here
http://oreilly.com/pub/h/3330#code