生成随机坐标直到正确

时间:2019-12-14 12:10:34

标签: python python-2.7

所以基本上我是用Python创建Snake(游戏)的。我猜你们都知道它是如何工作的,一条蛇,一个苹果-蛇吃着苹果,变得越来越大。

除了一个问题外,我的代码都运行良好,因为苹果的放置位置是随机的,所以有时它会出现在蛇上,变得像被吃掉一样不可见。

    def add_apple(self):
    # Place an apple in a random location on screen
    self.apple = (self.ui.random(WIDTH), self.ui.random(HEIGHT))
    a, b = self.apple
    self.ui.place(a, b, self.ui.FOOD)

我的蛇是清单:

    self.snake.append((self.x, self.y))
    self.ui.place(self.x, self.y, self.ui.SNAKE)

    # If apple is eaten, add another
    if self.apple == (self.x, self.y):
        self.add_apple()
    # For movement
    else:
        x, y = self.snake.pop(0)
        self.ui.place(x, y, self.ui.EMPTY)

所以我的问题是如何做到这一点,以便如果苹果的随机位置确实在蛇上,请再试一次。我尝试在add_apple中使用while循环,但是GUI由于某种原因(没有错误代码)将停止响应

谢谢。

1 个答案:

答案 0 :(得分:1)

我们将创建一个新的苹果店,直到找到不是蛇的地方

更改

def add_apple(self):
    # Place an apple in a random location on screen
    self.apple = (self.ui.random(WIDTH), self.ui.random(HEIGHT))
    a, b = self.apple
    self.ui.place(a, b, self.ui.FOOD)

对此:

def add_apple(self):
    # Place an apple in a random location on screen
    self.apple = (self.ui.random(WIDTH), self.ui.random(HEIGHT))
    while self.apple in self.snake:
        self.apple = (self.ui.random(WIDTH), self.ui.random(HEIGHT))
    a, b = self.apple
    self.ui.place(a, b, self.ui.FOOD)

如果您想使其更快,可以按照以下步骤操作:

from random import choice
def add_apple(self):
    # Place an apple in a random location on screen
    x_snakes = [i[0] for i in self.snake] # all snake x posisions
    y_snakes = [i[1] for i in self.snake] # all sanke y posisions
    x_not_snake = [i for i in range(WIDTH) if i not in x_snake] # all the posision that the snake is not in the x cordinate
    y_not_snake = [i for i in range(HEIGHT) if i not in y_snake] # same for y
    self.apple = (choice(x_not_snake), choice(y_not_snake)) # randomly get one
    a, b = self.apple
    self.ui.place(a, b, self.ui.FOOD)

这对于最终游戏状态会更好,因为它将确保每次random通话都会找到一个随机位置