私の最初のカメプロジェクトとして、私は「ヘビ」ゲームのコーディングを始めましたが、ヘビの代わりに、ランダムに調整された食べ物を食べるカメです。
食べ物を食べるときに問題に直面しました。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()
方法のせいであるに違いありませんが、代わりに何を使うべきかわかりません。手伝ってくれませんか?:)
あなたができることは、カメと食物の両方の衝突境界を半径の形で定義し、2つの半径の合計が1つのカメから別のカメまでの距離よりも大きいかどうかを確認することです。次のコードが機能するはずです。
turtle.radius = 10
food.radius = 5
while True:
turtle.up()
go()
# check if the turtle has eaten the food.
if (turtle.radius+food.radius)>=food.distance(turtle):
turtleSize += 1
turtle.shapesize(turtleSize)
getfood()
# let the player rotate pressing the "a" key
screen.listen()
screen.onkeypress(rotate, 'a')
ps:必要に応じて半径値を設定できます。2つのランダムな値を使用しました。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加