本人初学,欲用Python中的turtle写一个简单的贪吃蛇游戏,结合网络上的教程,写至蛇改变运动方向,但是不知为何,蛇无法按预期改变运动方向,按“w”为向左上而非向上,按“s”为向左下而非向下,按“d”为向左而非向右。究其原因,为x和aim_x一直为-10而无法改变。具体代码错误原因和改正方法上网搜索许久未果,故来此咨询。
代码如下:
import turtle
def square(x, y, size, color_name):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(color_name)
turtle.begin_fill()
for i in range(4):
turtle.forward(size)
turtle.left(90)
turtle.end_fill()
from random import randrange
snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]]
apple_x = randrange(-205,206)
apple_y = randrange(-205,206)
aim_x,aim_y = -10,0
def change(x,y):
global aim_a,aim_y
aim_x = x
aim_y = y
def gameLoop():
global apple_x,apple_y
turtle.clear()
snake.insert(0,[snake[0][0]+aim_x,snake[0][1]+aim_y])
snake.pop()
for i in range(len(snake)):
square(snake[i][0],snake[i][1],10,"black")
square(apple_x,apple_y,10,"red")
turtle.ontimer(gameLoop,300)
turtle.update()
turtle.setup(420,420)
turtle.hideturtle()
turtle.tracer(False)
turtle.listen()
turtle.onkey(lambda:change(0, 10), "w")
turtle.onkey(lambda:change(-10, 0), "a")
turtle.onkey(lambda:change(0, -10), "s")
turtle.onkey(lambda:change(10, 0), "d")
gameLoop()
turtle.done()
多谢各位指点与帮助!鄙人不胜感激!
【以下回答由 GPT 生成】
问题的根本原因在于方向的改变逻辑不正确,这导致方向改变时蛇的移动方向并不是按照预期的方向进行。在代码中,按下按键后并没有直接改变运动方向的aim_x和aim_y的值,而是在gameLoop函数中将aim_x和aim_y添加到蛇头的坐标上,实际上这种方式并不能改变蛇的运动方向。
为了解决这个问题,我们可以对代码进行一些修改。下面是修改后的代码和解决方案:
import turtle
def square(x, y, size, color_name):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(color_name)
turtle.begin_fill()
for i in range(4):
turtle.forward(size)
turtle.left(90)
turtle.end_fill()
from random import randrange
snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]]
apple_x = randrange(-205,206)
apple_y = randrange(-205,206)
aim_x,aim_y = 0, 10 # 初始方向向上
def change(x,y):
global aim_x, aim_y
aim_x = x
aim_y = y
def gameLoop():
global apple_x, apple_y
turtle.clear()
new_head = [snake[0][0]+aim_x,snake[0][1]+aim_y] # 计算新的蛇头位置
snake.insert(0, new_head)
snake.pop()
for i in range(len(snake)):
square(snake[i][0],snake[i][1],10,"black")
square(apple_x,apple_y,10,"red")
turtle.ontimer(gameLoop,300)
turtle.update()
turtle.setup(420,420)
turtle.hideturtle()
turtle.tracer(False)
turtle.listen()
turtle.onkey(lambda:change(0, 10), "w")
turtle.onkey(lambda:change(-10, 0), "a")
turtle.onkey(lambda:change(0, -10), "s")
turtle.onkey(lambda:change(10, 0), "d")
gameLoop()
turtle.done()
修改后,我们在gameLoop函数中计算新的蛇头位置时直接使用aim_x和aim_y来改变,并将新的蛇头位置插入到蛇列表的第一个位置,然后移除蛇列表的最后一个位置,即实现了贪吃蛇的运动。这样就可以根据按键的不同来改变蛇的运动方向了。
请通过复制上面的代码并运行来查看修正后的效果。
【相关推荐】