简体   繁体   English

Python-我无法弄清的蛇游戏错误

[英]Python - A bug with my snake game that I can't figure out

Note - this game is made using pygame 注意-此游戏是使用pygame制作的

I have made this snake game and everything is working perfectly except one thing. 我做了这个蛇游戏,除了一件事之外,其他所有东西都运转良好。 Sometimes, when the snake eats the apple the apple doesn't re-spawn. 有时,当蛇吃掉苹果时,苹果不会重生。 I think that this might happen when the apple spawns inside the snake but I wrote some code to check if the apple would spawn in the snake and if so choose a different position. 我认为苹果在蛇内产卵时可能会发生这种情况,但我编写了一些代码来检查苹果是否会在蛇中产卵,如果是,请选择其他位置。 Maybe I did it wrong?! 也许我做错了吗?

The bug is in your food.py source code file, in the get_food_position() function. 该错误位于您的food.py源代码文件中的get_food_position()函数中。 Specifically the following line is causing your bug: 具体来说,以下几行会引起您的错误:

self.apple_pos = (random.randint(self.WIDTH-self.WIDTH, self.WIDTH), random.randint(self.HEIGHT-self.HEIGHT, self.HEIGHT))

When you observe the apple not re-spawning, that is because you are setting the tuple self.apple_pos to be outside your viewable area. 当您观察到苹果没有重新产生时,这是因为您将元组self.apple_pos设置为在可见区域之外。 You have to remember that the apple has height and width, so it cannot be drawn at the very extremes of your viewable area. 您必须记住,苹果有高度和宽度,因此无法在可见区域的最极端绘制它。 You can prove this to yourself by forcibly setting self.apple_pos = (1280,720) , and then setting it again to (1260,700) . 您可以通过强制设置self.apple_pos = (1280,720) ,然后再次将其设置为(1260,700)来向自己证明这一点。

The following correction to your code solves the problem: 对您的代码进行以下更正可以解决此问题:

self.apple_pos = (random.randint(0, self.WIDTH-20), random.randint(0, self.HEIGHT-20))

I chose the magic number 20 because your apple seems to have area 20x20 pixels. 我选择了魔术数字20,因为您的苹果似乎有20x20像素的面积。

You'll note that drawing the apple at (0,0) does not have this problem because the apple is placed by its own (0,0) coordinate, which is its upper left corner. 您会注意到,在(0,0)处绘制苹果不会出现此问题,因为苹果是通过其自己的(0,0)坐标(即其左上角)放置的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM