gpt4 book ai didi

python - Python 中的循环

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:35 25 4
gpt4 key购买 nike

我正在尝试让 pygame 中的 Sprite throw 手榴弹。我希望它向前移动一点,然后停止。我的问题是让手榴弹顺利前进。以下代码的作用是让它立即移动到兴趣点,而不是平滑移动。

[手榴弹类]

#Grenade Class
class Explosive(pygame.sprite.Sprite):
def __init__(self, location):
pygame.sprite.Sprite.__init__(self)
self.pos = location
self.image = Nade
self.rect = self.image.get_rect()
self.rect.right = self.image.get_rect().right
self.rect.left = self.image.get_rect().left
self.rect.top = self.image.get_rect().top
self.rect.bottom = self.image.get_rect().bottom
self.rect.center = location
def move(self):
if Player.direction == 0:
self.rect.centery = self.rect.centery - 5
if Player.direction == 180:
self.rect.centery = self.rect.centery + 5
if Player.direction == 90:
self.rect.centerx = self.rect.centerx + 5
if Player.direction == 270:
self.rect.centerx = self.rect.centerx - 5

[扔手榴弹(在主循环中)]

if event.key == pygame.K_e and grenadeNum > 0:
Grenade = Explosive([Player.rect.centerx, Player.rect.centery])
for i in range(1, 10)
Grenade.move()

最佳答案

虽然您确实需要更新显示,但还有第二个问题。现在,你根本没有告诉它等待,所以它会立即完成所有十个 Action 。这将同样突然,因此您可能需要导入时间并在其中的某个位置添加 time.sleep() 。因为在一个独立的“for”循环中移动手榴弹,如果你还有其他事情发生,这将会停止。如果你有一个 while 循环来管理一切,请对手榴弹调用“更新”函数,它们将有计数器来知道它们是否应该在本轮中移动。如果其他 Sprite 需要做某事,您也可以调用它们的方法。最后,为了加快程序速度,您只能更新 Sprite 移动的部分的屏幕。当您将所有这些放在一起时,它是这样的:

import time

grenades = pygame.sprite.RenderUpdates() #initializes a pygame group for sprites

class Explosive(pygame.sprite.Sprite):
def __init__(self, location):
pygame.sprite.Sprite.__init__(self)
self.pos = location
self.image = Nade
self.rect = self.image.get_rect()
self.rect.right = self.image.get_rect().right
self.rect.left = self.image.get_rect().left
self.rect.top = self.image.get_rect().top
self.rect.bottom = self.image.get_rect().bottom
self.rect.center = location
self.move_counter = 10 #adds a counter for how many rounds left of moving the grenade has
def update(self):
if self.move_counter > 0: #checks that self still has turns left to move
<insert screen variable name>.fill(<insert background color>,self.rect) #erases self in old location
if Player.direction == 0:
self.rect.centery = self.rect.centery - 5
if Player.direction == 180:
self.rect.centery = self.rect.centery + 5
if Player.direction == 90:
self.rect.centerx = self.rect.centerx + 5
if Player.direction == 270:
self.rect.centerx = self.rect.centerx - 5
pygame.display.update(self.draw((screen))) #draws self in new location
self.move_counter -= 1 #subtracts one from the counter to mark that another turn of moving has passed by

while True:
grenades.update()
#anything else you want to do in real time here
time.sleep(0.1)

关于python - Python 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573890/

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