gpt4 book ai didi

python - 当我打开Pygame时,它总是崩溃

转载 作者:行者123 更新时间:2023-12-03 17:49:02 24 4
gpt4 key购买 nike

我有这个躲避外星人的游戏,但是它不起作用。我可以打开前面的开始屏幕,但是当我按下Enter键时,它崩溃并冻结。我尝试从python.exe而不是仅从IDLE运行它,但在那种情况下,它会弹出然后立即关闭。在我尝试运行它的最初几次,会弹出一些错误,但现在没有错误表明可能是错误的。它只是停止响应。我在这里做错了什么?

import pygame, random, sys
from pygame.locals import *


def startGame():
if event.type == K_ENTER:
if event.key == K_ESCAPE:
sys.exit()
return

def playerCollision():
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False

pygame.init()

screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')

font = pygame.font.SysFont(None, 55)

playerImage = pygame.image.load('')
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('')

drawText('Dodge the Aliens!', font, screen, (750 / 3), (750 / 3))
drawText('Press ENTER to start.', font, screen, (750 / 3) - 45, (750 / 3) + 65)
pygame.display.update()

topScore = 0
while True:
aliens = []
score = 0
playerRect.topleft = (750 /2, 750 - 50)
alienAdd = 0
while True:
score += 1
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: x -=3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_ESCAPE]: sys.exit()
alienAdd += 1

if alienAdd == addedaliens:
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a)
screen.fill(0,0,0)
drawText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.update()


if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break

clock.tick(60)

drawText('Game Over!', font, screen, (750 / 3), ( 750 / 3))
drawText('Press ENTER To Play Again.', font, screen, ( 750 / 3) - 80, (750 / 3) + 50)
pygame.display.update()
startGame()

这是我的一些修改后的新代码
导入pygame,随机,sys
从pygame.locals导入*
alienimg = pygame.image.load('C:\ Python27 \ alien.png')
playerimg = pygame.image.load('C:\ Python27 \ spaceship.png')
def playerCollision(): # a function for when the player hits an alien
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False

def screenText(text, font, screen, x, y): #text display function
textobj = font.render(text, 1, (255, 255, 255))
textrect = textobj.get_rect()
textrect.topleft = (x,y)
screen.blit(textobj, textrect)

def main(): #this is the main function that starts the game

pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()

pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont("monospace", 55)


pressed = pygame.key.get_pressed()

aliens = []
score = 0
alienAdd = 0
addedaliens = 0

while True: #our while loop that actually runs the game



for event in pygame.event.get(): #key controls
if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit()
elif event.type == KEYDOWN and event.key == pygame.K_LEFT:
playerRect.x -= 3

elif event.type == KEYDOWN and event.key == pygame.K_RIGHT:
playerRect.x += 3


playerImage = pygame.image.load('C:\\Python27\\spaceship.png').convert() # the player images
playerRect = playerImage.get_rect()
playerRect.topleft = (750 /2, 750 - 50)
alienImage = pygame.image.load('C:\\Python27\\alien.png').convert() #alien images

alienAdd += 1

pygame.display.update()

if alienAdd == addedaliens: # randomly adding aliens of different sizes and speeds
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a) #removes the aliens when they get to the bottom of the screen

screen.blit(screen, (0,0))
screenText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.flip()


if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break


clock.tick(60)

screenText('Game Over!', font, screen, (750 / 6), ( 750 / 6))
screenText('Press ENTER To Play Again.', font, screen, ( 750 / 6) - 80, (750 / 6) + 50)
pygame.display.update()

main()

最佳答案

我仍然看到您的代码有几个问题,并且我认为您一开始就要立即做太多事情。尝试使其尽可能简单。尝试创建显示并绘制一些图像:

import pygame

pygame.init()

display = pygame.display.set_mode((750, 750))
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
display.blit(img, (0, 0))
pygame.display.flip()

当然,您必须调整img路径。运行此命令,您可能会看到一个明确的错误(您应该在另一个线程中发布该错误),或者在屏幕上看到您的img。但是程序没有响应,因为没有事件处理,也没有主循环。

为了避免这种情况,您可以引入一个主循环,例如:
import sys
import pygame

pygame.init()

RESOLUTION = (750, 750)
FPS = 60

display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")

while True: # <--- game loop

# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)

这将导致一个程序反复显示相同的img,并且可以使用鼠标正确退出该程序。但是它仍然像一个脚本,如果有人导入了它,它将立即执行,这不是我们想要的。因此,让我们对其进行修复,并将其全部包装在一个主要函数中,如下所示:
import sys
import pygame

#defining some constants
RESOLUTION = (750, 750)
FPS = 60

def main(): # <--- program starts here

# setting things up
pygame.init()
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")

while True: # <--- game loop

# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)

if __name__ == "__main__":
main()

'if name ==“ main ”:'可确保程序在导入时不执行。

我希望这有帮助。请记住:不要一次尝试太多。一步一步地采取小步骤,并尝试保持对程序的控制。如果需要,您甚至可以在每行代码后放置一条print语句,以准确告知您程序的工作方式和顺序。

关于python - 当我打开Pygame时,它总是崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493997/

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