import turtle
import time
import random
camara = turtle.Screen()
camara.title('bienvenido al juego de la serpiente.')
camara.setup(width=600, height=600)
camara.bgcolor("blue")
score = 0
total_score = 0
#texto
text = turtle.Turtle()
text.penup()
text.hideturtle()
text.color('red')
text.speed(0)
text.setpos(0, 250)
text.write(f'actual score {score} total score {total_score}', move=False, align='center', font=('candara', 24, 'bold'))
#cabeza
head = turtle.Turtle()
head.speed(1.4)
head.direction = 'stop'
head.shape('square')
head.shapesize(stretch_wid=1.1, stretch_len=1.1, outline=None)
head.color('red')
head.penup()
head.setpos(0, 0)
def arriba():
while head.direction != 'down':
head.direction = 'up'
y = head.ycor()
head.sety(y + 20)
def abajo():
while head.direction != 'up':
head.direction = 'down'
y = head.ycor()
head.sety(y - 20)
def izquierda():
while head.direction != 'right':
head.direction = 'left'
x = head.xcor()
head.setx(x - 20)
def derecha():
while head.direction != 'left':
head.direction = 'right'
x = head.xcor()
head.setx(x + 20)
camara.listen()
camara.onkeypress(arriba, 'w')
camara.onkeypress(izquierda, 'a')
camara.onkeypress(abajo, 's')
camara.onkeypress(derecha, 'd')
#food
food = turtle.Turtle()
food.penup()
food.shape('square')
food.speed(0)
x1 = random.randint(-270, 270)
y1 = random.randint(-270, 270)
food.setpos(x1, y1)
if food.distance(head) < 20:
food.penup()
food.shape('square')
food.speed(0)
x1 = random.randint(-270, 270)
y1 = random.randint(-270, 270)
food.setpos(x1, y1)
camara.mainloop()
大家好,我正在试着做一个《蛇的游戏》,我做了一个算法,当蛇接触到食物时,食物消失,然后再次出现在 map 上的随机位置,但不知何故,它似乎不起作用,因为当蛇接触食物时,食物仍然保持在相同的位置,所以在那之后,我做了这个算法(添加一个While True):
food = turtle.Turtle()
while True:
food.penup()
food.shape('square')
food.speed(0)
x1 = random.randint(-270, 270)
y1 = random.randint(-270, 270)
food.setpos(x1, y1)
为了弄清楚食物是否随机地看起来足够好,确实是这样,但当我开始移动蛇头时,循环停止运行,(蛇继续移动),食物保持不变.我是说... 当我执行这些代码行时:
def arriba():
while head.direction != 'down':
head.direction = 'up'
y = head.ycor()
head.sety(y + 20)
def abajo():
while head.direction != 'up':
head.direction = 'down'
y = head.ycor()
head.sety(y - 20)
def izquierda():
while head.direction != 'right':
head.direction = 'left'
x = head.xcor()
head.setx(x - 20)
def derecha():
while head.direction != 'left':
head.direction = 'right'
x = head.xcor()
head.setx(x + 20)
camara.listen()
camara.onkeypress(arriba, 'w')
camara.onkeypress(izquierda, 'a')
camara.onkeypress(abajo, 's')
camara.onkeypress(derecha, 'd')
可以这么说,代码的其余部分停止运行. 那么这里的问题是什么呢?我应该怎么做才能让食物在每次蛇接触食物时都随机出现?谢谢.