gpt4 book ai didi

python - 如何在 Pygame 中每次重置游戏时初始化新对象

转载 作者:行者123 更新时间:2023-12-01 07:43:18 25 4
gpt4 key购买 nike

每次用户按 c 键时,我都会尝试重新创建新对象,以便我可以从起点再次加载游戏。但我找不到办法这样做。

这是我迄今为止尝试过的:

def initializeGame(theGame):

while run:
theGame.clock.tick(FPS)

# This function consists code for Events
theGame.events()
# This function consists code from enemy hit events
theGame.hit_or_not()
# This function consists code for bullet hit events
theGame.bulletHit_or_not()
# This function consists code for player movements
theGame.movements()
# This function consists code for drawing the sprites over the screen
theGame.redrawGameWindow()

def startGame(run):
first_game = Game()

while run:
initializeGame(first_game)

keys = pygame.key.get_pressed()

if keys[pygame.K_ESCAPE]:
run = False

if keys[pygame.K_c]:
new_game = Game()
initializeGame(new_game)

startGame(True)

我想做的就是当我按“c”键时,游戏必须从起点重新启动,为此我必须重新创建新的“Game()”类对象并初始化游戏

游戏类代码 - https://pastebin.com/abAiey34

最佳答案

避免游戏循环中出现游戏循环,这意味着从 initializeGame 中删除循环。
initializeGame 名称具有误导性,请将其命名为 runGame:

def runGame(theGame):

# This function consists code for Events
theGame.events()
# This function consists code from enemy hit events
theGame.hit_or_not()
# This function consists code for bullet hit events
theGame.bulletHit_or_not()
# This function consists code for player movements
theGame.movements()
# This function consists code for drawing the sprites over the screen
theGame.redrawGameWindow()

因此,拥有一个游戏就足够了,它只是“重置”创建一个新的游戏对象。
在唯一的游戏循环中,必须调用 runGame:

def startGame(run):

game = Game()
while run:
theGame.clock.tick(FPS)

# run the game
runGame(game)

# get keys
keys = pygame.key.get_pressed()

# handle keys
if keys[pygame.K_ESCAPE]:
run = False
if keys[pygame.K_c]:
game = Game()

startGame(True)

注意,startGame() 已经有一个循环,因此没有必要在任何函数中进行进一步的游戏循环。 runGame() 完成游戏框架中完成的所有操作。 runGame()startGame() 的游戏循环中不断调用。
如果必须开始一个新游戏,创建一个新的 Game 对象就足够了。

<小时/>

注意,pygame.key.get_pressed() 返回的状态被评估,当 pygame.eventspygame.event.get() 处理或pygame.event.pump() .
在事件循环后调用 pygame.key.get_pressed()。

我更喜欢稍微不同的设计。获取主循环中的事件 (pygame.event.get()) 并将它们传递给 runGame() 并进一步传递给 Game.events():

class Game:

# [...]

def events(self, eventlist):

for event in eventlist:
# handle events
# [...]

def runGame(theGame, eventlist):

# This function consists code for Events
theGame.events(eventlist)

# [...]

def startGame(run):

game = Game()
while run:
theGame.clock.tick(FPS)

# run the game
eventlist = pygame.event.get()
runGame(game, eventlist)

# get keys
keys = pygame.key.get_pressed()

# handle keys
if keys[pygame.K_ESCAPE]:
run = False
if keys[pygame.K_c]:
game = Game()

关于python - 如何在 Pygame 中每次重置游戏时初始化新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56578253/

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