Whenever I was trying to make a snake game , this is still incomplete, whenever my snake collides with boundary it goes to the next screen a prints
you suck try again
but if I double click anywhere on the pygame window it crashes sometimes.
Tthe number of left clicks are more than just 2 but in the end it still crashes after clicking a while.
What must I do to fix this as this issue is not there for the initial screen where I play with the snake.
The code I used is given below:
import pygame
import random
pygame.init()
font = pygame.font.Font(None,25)
def mess(msg,color):
screen_text = font.render(msg, True , color)
display.blit(screen_text , [(w/2) - 50 , h/2] )
score = 0
w = 800
h = 600
display = pygame.display.set_mode((w,h))
pygame.display.update()
red = (255,0,0)
white = (255,255,255)
black = (0,0,0)
yellow = (255,255,0)
bye = False
xpos = w/2
ypos = h/2
xch = 0
ych = 0
b = 10
while True:
wa = random.randrange (10,700)
ha = random.randrange (10,500)
if wa%10 == 0 and ha%10 == 0:
break
time = pygame.time.Clock()
FPS = 10
up = False
side = False
lenth = 10
while not bye:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w and up == False:
ych = -b
xch = 0
up = True
side = False
if event.key == pygame.K_s and up == False:
ych = +b
xch = 0
up = True
side = False
if event.key ==pygame.K_d and side == False:
xch = +b
ych = 0
side = True
up = False
if event.key == pygame.K_a and side == False:
xch = -b
ych = 0
side = True
up = False
if xpos == wa and ypos == ha:
lenth = lenth + 10
while True:
wa = random.randrange (10,700)
ha = random.randrange (10,500)
if wa%10 ==0 and ha%10 == 0:
break
score = score + 10
if xpos == w - 10 or xpos == 0 or ypos == h - 10 or ypos == 0:
xch = 0
ych = 0
display.fill(black)
mess("You suck Try again!",red)
pygame.display.update()
break
xpos = xpos + xch
ypos = ypos + ych
time.tick(FPS)
display.fill(white)
display.fill(red , rect=[xpos,ypos,10,10])#snake
display.fill(yellow ,rect=[xpos + 0.41 , ypos +10 ,10 , lenth])#bady
display.fill(black, rect=[wa,ha,10,10]) #food
pygame.display.update()
答案 0 :(得分:0)
我不知道这是否能完全解决您的问题。但是像这样的while循环没有睡眠会导致你的程序占用你所有的CPU能力,这可能会导致你的程序崩溃。解决此问题的方法是更改此代码...
while True:
wa = random.randrange (10,700)
ha = random.randrange (10,500)
if wa%10 ==0 and ha%10 == 0:
break
对此...
wa = random.randrange(1,70)*10
ha = random.randrange(1,50)*10
这会将while循环全部移除,并且在10到700之间,以及10和500之间仍然可以将数字除以10。
答案 1 :(得分:0)
当你的蛇离开屏幕时,会执行以下if语句:
if xpos == w - 10 or xpos == 0 or ypos == h - 10 or ypos == 0:
xch = 0
ych = 0
display.fill(black)
mess("You suck Try again!",red)
pygame.display.update()
break
因此,在向显示屏绘制一些文字并致电pygame.display.update()
后,您拨打break
,结束while
循环。
所以你的游戏不会崩溃,它只会结束。