我在pygame中做了一个pokemon攻略,我做了一个方法来测试玩家是否在高草丛中。但是,我不知道应该在哪里调用这个方法。我试过在玩家移动方法中,在游戏循环方法中,还有更新方法中。当我这样做的时候,它是在你搬出草丛后才检查的,也就是说你第一次搬进草丛的时候,它不会工作,而当你第一次搬出草丛的时候,它就会工作(不该工作的时候)。
in_grass(self)
方法。
def in_grass(self):
for g in self.game.grass:
if pygame.sprite.collide_rect(self, g):
print(random.randint(1, 10000))
if random.randint(1, 180) <= 25:
self.battle()
玩家 move(self)
方法。
def move(self, x_change, y_change):
if x_change > 0:
self.dir = 'RIGHT'
if x_change < 0:
self.dir = 'LEFT'
if y_change > 0:
self.dir = 'DOWN'
if y_change < 0:
self.dir = 'UP'
if not self.collide(x_change, y_change):
self.x += x_change
self.y += y_change
image_list = None
if self.dir == 'UP':
image_list = self.image_up
elif self.dir == 'LEFT':
image_list = self.image_left
elif self.dir == 'RIGHT':
image_list = self.image_right
elif self.dir == 'DOWN':
image_list = self.image_down
if image_list:
if self.walkcount >= len(image_list):
self.walkcount = 0
self.image = image_list[self.walkcount]
self.walkcount += 1
self.image.set_colorkey(BLACK)
主循环
def events(self):
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:
self.player.move(0, -1)
if event.key == pygame.K_a:
self.player.move(-1, 0)
if event.key == pygame.K_s:
self.player.move(0, 1)
if event.key == pygame.K_d:
self.player.move(1, 0)
if event.type == pygame.KEYUP:
self.player.image = self.player.default_images[self.player.dir]
self.player.image.set_colorkey(BLACK)
我终于成功了!我不能给自己打赏,所以我想它就放在那里吧。
所以这里有一些思考。
小小的免责声明,我绝不是一个游戏开发者,也不是一个很有经验的开发者。
在一个较大的游戏中,你可能要好好把握一下哪里发生了什么。现在假设我们有一个充满实体的游戏(把实体想象成你在屏幕上看到的对游戏有某种影响的东西)。我们想在游戏的每一帧中更新所有这些实体。
实体可能会被渲染,移动,碰撞检查,受玩家输入影响,动画或任何你的游戏需要的功能。
entities = []
然后我们可以做这样的事情,我们在gameloop中循环查看每个敌人,然后执行他们的行为函数,我们把所有的实体传递到check_collision函数中,使这个代码更容易理解。
版本1
entities = []
def game_loop:
while(true):
for entity in entities:
entity.gather_input()
entity.move()
entity.check_collision(entities)
entity.animate()
entity.render()
现在来看看这个。
第二版
entities = []
def game_loop:
while(true):
for entity in entities:
entity.gather_input()
for entity in entities:
entity.move()
for entity in entities:
entity.check_collision(entities)
for entity in entities:
entity.animate()
for entity in entities:
entity.render()
我们执行实体的顺序,它们的行为已经改变了。我们现在有了分组行为,我们可以说我们已经定义了gameloop的更新阶段。我们现在知道所有实体的运动都是在我们检查它们的所有碰撞之前更新的。
而在版本1中,我们先对1个实体做所有的逻辑,然后再做下一个。使用版本1,我们可能会在一帧中丢失相关数据,因为有一个实体可能会移动并检查碰撞,而实际上应该等到所有实体都移动后再检查。
希望这能引发更多的研究,进入游戏设计架构的兔子洞。
在玩家的游戏中创建一个布尔值 __init__
方法调用 self.checked = False
. 然后,在 in_grass
方法,在最后,设置 self.checked = True
. 其中 update
方法。if not self.checked: self.in_grass
最后,在 move
方法,在开始时,设置 self.checked = False
我终于把它弄好了,耶!