gpt4 book ai didi

python - 使用 Python 和 Pygame 进行贪吃蛇

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:36 24 4
gpt4 key购买 nike

我目前正在为我的编码类(class)做一个蛇项目。我能够让蛇移动,每个 body 部位都跟随前面的 body 部位。然而,我很难尝试改变蛇的方向。这是当前的示例代码。

snakeHeadX = 400
snakeHeadY = 400

a = [[snakeHeadX,snakeHeadY],[snakeHeadX - 20,snakeHeadY], [snakeHeadX-20-20,snakeHeadY]]

for i in range(len(a) -1, -1, -1):
if i == 0:
continue

[a[i][0], a[i][1]] = [a[i-1][0], a[i-1][1]]
if i == 0:
continue
a[0][0] = a[0][0] + 20

a[0][0] = a[0][0] + 20 是在 X 上移动蛇头位置加上 20 的任何想法。改变方向,例如说 a[0][1] = a[0][1] + 20,这会将蛇的头部在 Y 轴上向上移动 20?

最佳答案

您可以创建变量“方向”,它可以存储您头部移动方向的值(即“向上”、“向下”、“向左”或“向右”),并基于此您可以移动蛇但是,蛇的每个“ block ”都会同时改变方向。

这是您需要执行的操作:

    snake_start_x = 400
snake_start_y = 400
snake_block_size = 20

snake = [] #please, use names that make sense, not a
for i in range(3): #a bit more elegant than what you did to create snake
snake.append([snake_start_x-i*snake_block_size, snake_start_y])

def move_head(direction):
global snake #if you would pass snake as an argument it would create another instance. Here where're working directly on snake

if direction == "up": #change y by -20
snake[0][1] -= snake_block_size

elif direction == "down": #change y by 20
snake[0][1] += snake_block_size

elif direction == "left": #change x by -20
snake[0][0] -= snake_block_size

elif direction == "right": #change x by 20
snake[0][0] += snake_block_size

def move_tail(): #
global snake
for i in range(len(snake)-1, 0, -1): #looping backwards without including head
snake[i][0] = snake[i-1][0]
snake[i][1] = snake[i-1][1]

然后你需要在循环中调用它

    d = "up" # you can change it on key-press for example
while True: #your main loop
move_tail() #first snake moves tail up to it's head
move_head(d) #then head "bounces" in the right direction

#draw it then or whatever...

我认为有更好的方法可以做到这一点(也许让蛇成为一个对象?),但我想出了这个相对简单的方法。

编辑:您可以在 move_head 函数中添加碰撞检测,或者在移动完成后调用另一个函数来检查碰撞检测。这是一个例子:

    def is_in_wall(WIDTH, HEIGHT):
global snake
if snake[0][0] < 0: # too far left
return True
elif snake[0][0]+snake_block_size > WIDTH: # too far right
return True
elif snake[0][1] < 0: # too far up
return True
elif snake[0][1]+snake_block_size > HEIGHT: # too far down
return True
else:
return False

在你的循环中:

    if is_in_wall(WIDTH, HEIGHT): #WIDTH and HEIGHT are dimensions of your window 
#die or stop the game bacause snake has crossed the border

关于python - 使用 Python 和 Pygame 进行贪吃蛇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59556360/

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