【发布时间】:2020-11-15 11:02:54
【问题描述】:
作为我的第一个海龟项目,我开始编写“蛇”游戏,但不是蛇,而是海龟吃随机协调的食物。
我在吃食物时遇到了问题。我的意思是,必须有一个if 语句来检查蛇(即乌龟)和食物(也是乌龟)是否在相同的 XY 坐标中。如果是这样,首先,将乌龟的尺寸提高,然后隐藏食物,为其获取另一个随机坐标,然后将其显示在屏幕上。
这是我的代码:
from turtle import *
from random import *
def go():
# the main walking function for the turtle
turtle.forward(2)
def rotate():
# to rotate the turtle 90 degrees to the left
turtle.left(90)
def getfood():
# get random coordinates for the food
x = randint(-280, 280)
y = randint(-280, 280)
# set the food to the random position
food.hideturtle()
food.up()
food.goto(x, y)
food.showturtle()
turtle = Turtle()
screen = Screen()
screensize(600, 600)
food = Turtle()
food.shape('circle')
turtle.shape('turtle')
turtle.shapesize(3)
turtleSize = 3
getfood()
while True:
turtle.up()
go()
# check if the turtle has eaten the food.
if food.xcor == turtle.xcor and food.ycor() == turtle.ycor():
turtleSize += 1
turtle.shapesize(turtleSize)
getfood()
# let the player rotate pressing the "a" key
screen.listen()
screen.onkeypress(rotate, 'a')
问题就在那里,在if 语句中,它检查乌龟是否吃过食物。执行甚至没有进入它。一定是因为那些xcor() 和ycor() 方法,但我不知道应该改用什么。你能帮我吗? :)
【问题讨论】:
标签: python turtle-graphics snakemake