gpt4 book ai didi

python - 双击屏幕时 pygame 崩溃

转载 作者:行者123 更新时间:2023-12-01 16:28:31 25 4
gpt4 key购买 nike

每当我尝试制作蛇游戏时,这仍然是不完整的,每当我的蛇与边界碰撞时,它就会转到下一个打印屏幕

you suck try again

但是如果我双击 pygame 窗口上的任意位置,它有时会崩溃。

左键点击次数不止2次,但最后还是点了一会儿就崩溃了。

我必须做什么来解决这个问题,因为我玩蛇的初始屏幕不存在这个问题。

我使用的代码如下:

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()

最佳答案

我不知道这是否能完全解决您的问题。但是,像这样的 while 循环中没有 sleep 可能会导致您的程序占用所有 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 整除的数字。

关于python - 双击屏幕时 pygame 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31139777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com