Reputation: 327
After I run my pygame code it runs till the horizontel box is in the screen but after that it stops and when we try to cross it it shows the error Python not responding. This is my code:
import pygame
import sys
import random
from time import sleep
pygame.init()
pygame.display.init()
root = pygame.display.set_mode((600, 500))
pygame.display.set_caption('Game attempt')
clock = pygame.time.Clock()
body_horizontel = pygame.image.load(r"snake\body_horizontal.png")
# variables
x_coordinate = random.randint(0, 40)
y_coordinate = random.randint(0, 40)
bg = pygame.image.load(r"bg.jpg")
apple = pygame.image.load(r"apple.png")
body_horizontel_location_x = 260
body_horizontel_location_y = 230
root.blit(bg, (0, 0))
root.blit(apple, (x_coordinate * 15, y_coordinate * 12.5))
while True:
pygame.event.pump()
root.blit(body_horizontel, (body_horizontel_location_x, body_horizontel_location_y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
run = 0
while run < 4:
if body_horizontel_location_y >= 40:
root.blit(bg, (0, 0))
root.blit(apple, (x_coordinate * 15, y_coordinate * 12.5))
body_horizontel_location_y -= 40
root.blit(body_horizontel, (body_horizontel_location_x, body_horizontel_location_y))
sleep(0.01)
pygame.display.update()
run += 1
root.blit(apple, (x_coordinate * 15, y_coordinate * 12.5))
pygame.display.update()
root.blit(bg, (0, 0))
clock.tick(100)
I have the if clause so that if box doesn't go above the screen and that causes problem as when I try to make it go above the screen by clicking up arrow button the screen crashes. I have even tried changing the sleep with pygame.time.delay() or clock.tick() but none of them worked.
Upvotes: 1
Views: 111
Reputation: 570
Hi in your while loop it continues to run until run is greater than or equal to 4. The run variable only gets added one if your if statement is true so if it is false your program will stay in that while loop forever because run will never be greater than 4
Use this as your if statement instead
if body_horizontel_location_y >= 40:
root.blit(bg, (0, 0))
root.blit(apple, (x_coordinate * 15, y_coordinate * 12.5))
body_horizontel_location_y -= 40
root.blit(body_horizontel, (body_horizontel_location_x, body_horizontel_location_y))
sleep(0.01)
pygame.display.update()
run += 1
As you can see I took the run += 1 out of the if statement
Upvotes: 1