Error message inside a loop - Pong game - loops

I am making a game similar to pong in small basic. What I want to do is when the ball hits the wall the game ends and shows an error message.
What I did was use a while loop as such below:
While (hits right wall) or (hits left wall) or (hits top wall) or (hits bottom wall) = "True"
GraphicsWindow.ShowMessage("you lost", "game over")
Endwhile
What that actually does is keep repeating the error message and I have to quit the program. How can I get it to just show the message once when the conditions for it hitting either wall is true?

Use break once the condition is met and once you show the error message.

This is a job for a flag!
Before your loop you set a flag to true. Your loop is based on just that flag. Then for each exit condition that you need you have a separate if statement that handles that logic. When that condition is met, you set the flag to false.
This keeps the code simple, and the logic easy to follow.
Example:
gameOn = "true"
While gameOn = "true"
'Code to control your game
If (hitsLeftWall) Then
gameOn = "false"
ElseIf (hitsRightWall) then
gameOn = "false"
ElseIf (hitsLTopWall) then
gameOn = "false"
ElseIf (hitsBottomWall) then
gameOn = "false"
EndIf
EndWhile

Related

Execute if else condition parallelly over list of strings

I'm new in python and facing an issue in getting the right output. I have a list of strings as :
list_string=[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
All I want output as:
Output expected: [['The course starts next Sunday'], ["I don't wash the dishes"], 'When does the train usually leave']
What I've done is something:
import re
subtring='!DOC'
output=[]
for i in string:
if subtring in i:
text=re.findall("<p>(.*?)</t>",i, re.DOTALL)
output.append(text)
elif subtring in i:
text=re.findall("<d>(.*?)</span>",i, re.DOTALL)
output.append(text)
else:
output.append(i)
print (output)
[['The course starts next Sunday'], ["class='default'<d>I don't wash the dishes</span>"], 'When does the train usually leave']
Can anyone suggest the right way to do it?
It appears as though the second rule trumps the first so if there is a match on the second rule, use it otherwise try the first rule falling back to returning what you were given.
A solution that is close to what you have now might be:
import re
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output=[]
for line in list_string:
retval = re.findall("<d>(.*?)</span>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
retval = re.findall("<p>(.*?)</t>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
output.append(line)
print (output)
Though if it was me, I would probably use a little function with a comprehension:
import re
def pick_out_text(text):
retval = re.findall("<d>(.*?)</span>", text, re.DOTALL)
if retval: return retval[0]
retval = re.findall("<p>(.*?)</t>", text, re.DOTALL)
if retval: return retval[0]
return text
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output = [pick_out_text(line) for line in list_string]
print(output)

How to solve Ruby Wizardry "Staying in the loop" example program?

The book Ruby Wizardry Chapter 4 includes the following sample program
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where ya headin', friend?"
destination = gets.chomp
if stops.include? destination
puts "I know how to get to #{destination}! Here's the station list:"
stops.each do |stop|
puts stop
break if stop == destination
end
else
puts "Sorry, we don't stop at that station. Maybe another time!"
we_wanna_ride = false
end
end
It then goes on to pose a few additional challenges:
"What if a passenger is going the other way on the train (for instance, from Mal Abochny to East Bumpspark)? How could you update your program to work in both directions? Even trickier, what if the train route is a big circle (meaning if a passenger goes from East Bumpspark to Mal Abochny, the next stop after Mal Abochny should be East Bumpspark again)? How could you update your program to print out the right list of train stops if a passenger wants to go all the way around the circle?"
Does anybody have any ideas how to proceed here ? I'm a beginning programmer so any help would be greatly appreciated. Here's my progress so far. I figured I would get a departure from the user and then use to.i to get the input into an integer. I could then use the integer value to compare to the index position in the array. If the rider wants to go in the opposite direction I could use something like stops.each.reverse to print out the array items in reverse order.
we_wanna_ride = true
stops = ["East Bumpspark(1)", "Endertromb Avenue(2)", "New Mixico(3)", "Mal Abochny(4)"]
puts "#{stops}"
while we_wanna_ride
print "Select a destination number"
destination = gets.chomp.to_i
print "Select a departure number"
departure = gets.chomp.to_i
if departure <= destination
stops.each do |stop|
puts stop
break if stop == destination
end
else puts "Sorry"
we_wanna_ride = false
end
end
Here is how I solved this challenge. It works but is rather lengthy. More advanced ruby coders may be able to provide a shorter solution:
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where do you wish to depart from?: "
depart = gets.chomp.split.map(&:capitalize).join(' ')
depart_index = stops.index(depart)
# puts depart_index
print "Where ya headin' friend?: "
destination = gets.chomp.split.map(&:capitalize).join(' ')
destination_index = stops.index(destination)
# puts destination_index
index_diff1 = depart_index - destination_index
index_diff2 = destination_index - depart_index
if stops.include? destination && depart
puts "\nI know how to get to #{destination}! Here's the station list:"
if destination_index > depart_index && index_diff2 < 3
stops[depart_index..-1].each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index > depart_index && index_diff2 >= 3
dubstops = stops.concat(stops)
dubstops[0..depart_index+4].reverse_each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index < depart_index && index_diff1 < 3
stops[0..depart_index].reverse_each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index < depart_index && index_diff1 >= 3
dubstops = stops.concat(stops)
dubstops[depart_index..-1].each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
end
else
puts "Sorry, we don't service that station. Maybe another time!"
we_wanna_ride = false
end
end

How do I check if an object collides with every object in an array?(Picture boxes)

High school student here and I'm pretty rusty on my code. Okay, I have to have an image scroll along, and if it hits an object(in this case both are picture boxes), it resets.
The problem is when it gets to the If statement below, it won't work saying " 'bounds' is not a member of 'system.array' "
If PtbIcon.Bounds.IntersectsWith(objects.Bounds) Then
The error is the Objects.bounds
If PtbIcon.Bounds.IntersectsWith(objects.Bounds) Then
t = t + 1
PtbIcon.Location = New Point(29, 236)
'resets when you die, sets the score
End If
lblScore.Text = "Your Score Equals" & t
End
Why doesn't this work? Why? Is there a simpler way of checking all of this, such as calling a function which checks the bounds individually?
Use Linq.
Dim t As Integer = 0
PtbIcon.All(Function(pb As PictureBox) As Boolean
' Checking goes here with pb
' Return True if you want to go through all of them
End Function)
lblScore.Text = "Your Score Equals" & t

Retry loop until condition met

I am trying to navigate my mouse on object but I want to create a condition that will check if "surowiec" is still on the screen, if not I want to skip loop and go to another one. After it finish the second one get back to first and repeat.
[error] script [ Documents ] stopped with error in line 12 [error] FindFailed ( can not find surowiec.png in R[0,0 1920x1080]#S(0) )
w_lewo = Location(345,400)
w_prawo = Location(1570,400)
w_gore = Location(345,400)
w_dol = Location(345,400)
surowiec = "surowiec.png"
while surowiec:
if surowiec == surowiec:
exists("surowiec.png")
if exists != None:
click("surowiec.png")
wait(3)
exists("surowiec.png")
elif exists == None:
surowiec = None
click(w_prawo)
wait(8)
surowiec = surowiec
How about a small example:
while True:
if exists(surowiec):
print('A')
click(surowiec)
else:
print('B')
break
A while loop that is True will always run, until it it meets a break to exit the loop. Also have a look at the functions that are available in Sikuli, it can somethimes be hard to find them, that they are available. So here are a few nice ones:
Link: Link 1 and Pushing keys and Regions
The commands that I found myself very usefull are is exists and if not exists, and find that will allow to locate an image on the screen. Then you don't have to find an image over and over again if it stays on the same location. image1 = find(surowiec)

How to clear the screen and how to run the code after the levelOne loop

Full code and files: https://www.dropbox.com/sh/gqke6hfooz7mbnr/Qm8NMlyNqc
Can't seem to find the an solution to this dilemma. Basicly I press space to go to the next loop (levelTwo) and it just stops, nothing new appears on the screen even though I have code to do that. I'd really appreciate the help.
Part of the code with probably the dilemma but not sure:
if len(rabbits) == 0:
rabbitCounter = 0
windowSurface.blit (textLevelOne, (100, 104))
levelOne = False
windowSurface.fill((0,0,0))
#Ritar fönstret
pygame.display.update()
mainClock.tick(60)
#LEVEL TWO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
startSoundLevelTwo = True
while levelOne == False:
levelTwo = True
if startSoundLevelTwo == True:
rabbitSound.play()
foxSound.play()
pygame.mixer.music.play()
startSoundLevelTwo = False
pigSpawn = True
boarSpawn = True
Level 2 lacks the pygame.display.update() call.
Personally, I like to structure pygame code with one main loop, like this:
level = 1
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Process event, update game state:
if level == 1:
# Update level 1 state
elif level == 2:
# Update level 1 state
# Clear screen:
windowSurface.fill((0,0,0))
# Draw current state to screen:
if level == 1:
# Play level 2 music
# Draw level 1 state to screen
elif level == 2:
# Play level 2 music
# Draw level 2 state to screen
...
# Update screen and control FPS
pygame.display.update()
mainClock.tick(60)
You can use functions for each level, so you keep the main loop simple.

Resources