weird error causes no responding - python

envface1=pygame.image.load(p1)
envface2=pygame.image.load(p2)
envface1=pygame.transform.scale(envface1,(768,400))
envface2=pygame.transform.scale(envface2,(768,400))
start = timeit.default_timer()
window.blit(txt[0],(0,0))
window.blit(envface1,(0,400))
window.blit(envface2,(800,400))
pygame.display.flip()
display=False
while not display:
#delete the print will make it no responding
print
keys=pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
display=True
print "1"
if keys[pygame.K_RIGHT]:
display=True
print "2"
end=timeit.default_timer()
print end-start
pygame.quit()
For this part of code, I am trying to make something that user can choose the picture they like and print the result out. But in the while loop, when I delete the line with "print" only and run it, the program will down and make it no responding. Why would this happen?

As Cyber explained, you have a while loop that runs while display is false. However, since you don't modify display at all inside the loop, you've effectively created an infinite loop.
Your observation that the program will not respond is caused by the fact that nothing happens in the infinite loop unless a key is pressed.

Related

Breaking Loops as soon as their condition breaks in Python

I would like to know how to break a loop as soon as its condition breaks.Its a little difficult to explain I will attach some code that will explain it well.I think I have to use things like break and continue but I am not sure where in my code should I place or maybe I need to do something else.your help would be greatly appreciated.
while 1:
if image1 appears on screen:
# do some task(it includes multiple if statements in it too)
else:
#do task 1
#do task 2
#do task 3
I want as soon as image1 appears on screen else loop should exit even if it's incomplete.like if image1 appears when else loop is doing task 2 it should exit without completing it and move to the if loop.
with my current code if image1 appears on screen the else loop only exits when all 3 tasks are done.
I want to exit the else loop not the if loop and
by exit or break I mean shift from else loop to if loop
You can use a return, like this:
if image1 appears on screen:
#do some task**
return
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
UPD
I suggest this code is a part of some function.
Otherwise you will have to put it inside some function since return can be called from inside a function only.
It is also a good practice to define and use functions.
If image1 appears on screen, the else part will not execute (that's how if-else functionality works).
You can just add "break" in the end of the if (before the else)
if image1 appears on screen:
do some task**
break
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
Use break where you want to stop the loop -
if image1 appears on screen:
#do some task**
break
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
You can also check this
Use a break in if condition
#loop
if image1 appears on screen:
do some task**
break # this will break the loop at running iteration
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
#loop

How do I pause code in an if function in pygame?

How do you make the code stop for a moment before checking for something else? (I'm new to code)
if BonusTime==True and Drop==True:
if event.type == pygame.MOUSEBUTTONDOWN:
window.blit(Fired,(mouseX-12,mouseY-12))
Cankill=True
#I want it to delay here
Cankill=False
There is a cross hair that follows the mouse and when I click it, it fires. The problem is, you can just hold the mouse down and leave the cross hair in one place. Whenever an enemy walks into the cross hair, they die. I need it so even when you hold it will only fire once. I plan to make it delay the if statement, to set "Cankill" to true and then wait a second, after waiting, it should set "Cankill" to false. I've already looked through a lot of other people's questions similar to this and haven't found something I can understand. So if you could please help me find out how to delay it in the way I need.
"Pausing" is not what you want - if you do that, your game will just freeze, and nothing will move (since you are usign the OS mouse pointer, maybe it could move).
Anyway, the function to "pause" inside a game is pygame.time.wait(1000) - the number is in miliseconds.
Waht you actually need is to mark down the time the click was made, continue with the game, and when 1 second has passed, reset the variable back to the other state.
Something along:
last_trigger = 0
while True:
# game updating code goes here (getting events, and such)
...
if Cankill and pygame.time.get_ticks() - last_trigger > 1000:
Cankill = False
if event.type == pygame.MOUSEBUTTONDOWN:
window.blit(Fired,(mouseX-12,mouseY-12))
Cankill=True
last_trigger = pygame.time.get_ticks()
The "get_ticks" call returns the number of miliseconds that passed since pygame was initialized - and is usefull for this time of timers.

Let an image appear with key stroke and stay [pygame]

I'm currently working on a school project and I'm stuck with this problem.
The problem is in this line of code:
if pressed[pygame.K_SPACE]:
a = 1
while a == 1:
gameDisplay.blit(bulletIMG, (x,y))
I know what that problem is, the loop will go on forever.
Is there a way to break out of this loop? or should I try a different approach.
If I understand you correctly, you want to have the user press a button and an image displays permanently:
display_image = False
while game_running:
if pressed[pygame.K_SPACE]:
display_image = True
if display_image:
gameDisplay.blit(bulletIMG, (x,y))
now the image will always be displayed because the flag will always be true once the user hits the space bar (the key is bringing the flag outside the game loop).

Terminating from a while true loop (Calico IDE)

I'm using the Graphics and Myro packages in the Calico IDE, can anyone figure a way for me to hit the 'q' key and have the program terminate? Currently when I hit the 'q' key I have to click the mouse on my window to terminate.
def main():
win = Window(800,500)
bg = Picture("http://www.libremap.org/data/boundary/united_states/contig_us_utm_zone_14_600px.png")
bg.draw(win)
while True:
char = win.getKeyPressed()
if char == 'q':
win.close()
break
x, y = win.getMouse()
MPO = Rectangle(Point(x,y), Point(x+10,y+10))
MPO.fill = Color("white")
MPO.draw(win)
I've never heard of Calico before, but from 5 seconds looking at the docs, I see this:
getMouse() - waits until user clicks and returns (x, y) of location in window
So, I'm willing to bet this is why you have to click on your window before hitting the Q key has any effect—because you're program is stuck waiting inside the getMouse() call, just as the docs say it should be.
Even if the docs didn't explain this, you could probably figure it out pretty quickly by adding some printing/logging and/or running in a debugger, to see where it's bogged down when it's not responding to your keypresses.
For example, the quick&dirty way to do this:
while True:
print 'Before getKeyPressed'
char = win.getKeyPressed()
print 'After getKeyPressed, got', char
if char == 'q':
print 'About to close because of q'
win.close()
print 'Closed'
break
print 'Before getMouse'
x, y = win.getMouse()
print 'After getMouse, got', x, y
… and so on.
Of course in real life, you don't want to add a print statement for every single line of code. (And, when you do want that, you want a smarter way of instrumenting than manually writing all those lines.) But you can add a few to narrow it down to the general area, then zoom in and add a few more within that area, and so on, until you find the culprit.
Meanwhile, if you change your code to use getMouseNow() instead of getMouse(), that will solve the problem, but only by busy-looping and redrawing the window over and over as fast as possible, whether or not you've done anything.
What you really need here—as for any GUI app—is an event loop. I can see that there are functions called onMouseDown and onKeyPress, which looks like exactly what you need here.

How to create a "play again" option with Pygame

I am new to programming with Python. I have been working through a tutorial book that I found, and got the game up and running, but then decided I wanted to have a "Play Again?" option at the end. I can get the game to quit out with a press of the "n" key, but cannot work out how to get the game to restart.
Here is the code I think is giving the trouble:
#player reaches treasure
if player_rectangle.colliderect(treasure_rectangle):
#display text
screen.blit(text,(screen_width/2-195,screen_height/2-25))
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_n:
exit()
elif event.key==pygame.K_y:
pygame.display.update()
I know something needs to go after the elif event, and I have tried all that I can think of. I tried to define the whole program, and call it but that stopped the whole thing running. I have looked around internet sites, but just cannot seem to come up with a answer.
Can some one help out in easy terms how to get the game to restart to the starting position when the y key is pressed? I know it has something to do with a loop, I just cannot place my finger on what.
Many thanks.
It's not entirely clear how your code is organized, so I'll be very general. Usually games are implemented with a "main loop" that handles all of the action. In "pseudo"-python:
def main_loop():
while True:
handle_next_action()
draw_screen()
if game_is_over():
break
Before you start the loop, you usually do some setup to get the game state how you want it:
def main():
setup()
main_loop()
shut_down()
Given those parts, you can reset the game by having the main loop code call setup again (it may need to be specifically designed to be runable more than once):
def main_loop():
while True:
handle_events()
draw_screen()
if game_is_over():
if play_again(): # new code here!
setup()
else:
break
You might want to split the setup code into two parts, one which only needs to be run when the program begins (to read configuration files and set up things like the window system), and a second that gets repeated for each new game (setting up the game's state).
To restart a game you normally need to reset all variables to their initial value (e.g. number of lives, score, initial position, ...).
The best way is to put all initialisations inside a procedure:
def init():
global score,lives # use these global variables
score=0
lives=3
init() # call init() to define and reset all values
while 1: # main loop
...
elif event.key==pygame.K_y:
init() # restart the game

Categories

Resources