【问题标题】:How to find a turtle collision [duplicate]如何找到海龟碰撞[重复]
【发布时间】:2019-05-03 20:30:43
【问题描述】:

我正在尝试用 python 中的海龟制作蛇游戏。 我想要做的是当蛇进入圈子时,蛇会变长。

我也在尝试每次使用随机模块让圆圈进入不同的位置,我不希望蛇离开屏幕。

from turtle import Turtle, Screen
import random

wn = Screen()
wn.bgcolor('lightblue')

snake = Turtle()
snake.shape("square")
snake.shapesize(1, 1, 1)

snake.color('red')
snake.penup()

speed = 3


circle = Turtle()
circle.shape("circle")
circle.shapesize(0.8, 0.8, 0.8)
circle.color('blue')

def travel():
    snake.forward(speed)
    wn.ontimer(travel, 10)
#controls for using arrows with keyboard
wn.onkey(lambda: snake.setheading(90), 'Up')
wn.onkey(lambda: snake.setheading(180), 'Left')
wn.onkey(lambda: snake.setheading(0), 'Right')
wn.onkey(lambda: snake.setheading(270), 'Down')

wn.listen()

travel()

wn.mainloop()

【问题讨论】:

    标签: python python-3.x turtle-graphics


    【解决方案1】:

    Turtle 不包含任何内置方法来检测两个Turtle 对象之间的碰撞。你可以做的是根据snakecircle的位置差定义一个碰撞函数。使用 Turtles 内置的 distance 函数,这是一项非常简单的任务。半径,在这种情况下为 20,可以调整精度

    import turtle
    
    def isCollision(t1, t2):
        return t1.distance(t2) < 20
    

    要将circle Turtle 发送到随机位置,您可以使用gotorandit 函数让它移动到随机的xy 坐标

    import turtle
    from random import randint
    
    circle.goto(randint(0,100),randint(0,100))
    

    参考文献:

    Detecting collision in Python turtle game

    How to send turtle to random position?

    【讨论】:

    • 但它以圆圈为界。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多