【问题标题】:Make it so that turtle can't cross turtle-drawn lines使乌龟不能越过乌龟绘制的线
【发布时间】:2019-05-21 16:03:13
【问题描述】:

我正在尝试使用 Python 2.7.15 中的海龟制作一款类似于 Atari 2600 的冒险游戏。我可以让乌龟不能越过乌龟画的线吗?

当我的乌龟检测到某种颜色时,我需要它做某些事情,比如当它碰到蓝色时不能穿过绿色或打开门。如果你能帮助我弄清楚如何在乌龟接触乌龟后让收藏品(钥匙)跟随乌龟,则可以加分。这是我的代码:

from turtle import *
import turtle as t

color = raw_input("Enter an avatar color in the form of a hex code (Black won't show because the background is black): ")
c = Turtle()
loop = 0

def bdr():
    c.color(color)
    c.up()
    c.goto(0,-185)
    c.seth(90)
    t.ht()
    t.bgcolor("#000000")
    t.color("#00ff00")
    t.speed(0)
    t.up()
    t.rt(90)
    t.fd(200)
    t.rt(90)
    t.fd(200)
    t.rt(180)
    t.down()
    for box in range (4):
        t.fd(400)
        t.lt(90)
    t.up()
    t.fd(200)

def k1():
    c.seth(90)
    c.fd(5)

def k2():
    c.seth(180)
    c.fd(5)

def k3():
    c.seth(0)
    c.fd(5)

def k4():
    c.seth(270)
    c.fd(5)

bdr()

onkey(k1, "Up")
onkey(k2, "Left")
onkey(k3, "Right")
onkey(k4, "Down")

listen()
mainloop()

我没有尝试过任何颜色检测,因为我不知道从哪里开始。

【问题讨论】:

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


    【解决方案1】:

    我建议您不要基于颜色进行碰撞检测。如果你下拉到 turtle 的 tkinter 基础,这是可能的,但由于你的海龟在一个盒子内移动,所以测试坐标要简单得多:

    from turtle import Screen, Turtle, mainloop
    
    SIZE = 400
    DISTANCE = 5
    CURSOR_SIZE = 20
    
    def draw_border():
    
        border = Turtle(visible=False)
        border.color("green")
        border.speed('fastest')
    
        border.penup()
        border.goto(-SIZE/2, -SIZE/2)
        border.pendown()
    
        for _ in range(4):
            border.forward(SIZE)
            border.lt(90)
    
    def k1():
        player.setheading(90)
    
        if player.ycor() + DISTANCE < SIZE/2:
            player.forward(DISTANCE)
    
    def k2():
        player.setheading(180)
    
        if player.xcor() - DISTANCE > -SIZE/2:
            player.forward(DISTANCE)
    
    def k3():
        player.setheading(0)
    
        if player.xcor() + DISTANCE < SIZE/2:
            player.forward(DISTANCE)
    
    def k4():
        player.setheading(270)
    
        if player.ycor() - DISTANCE > -SIZE/2:
            player.forward(DISTANCE)
    
    color = raw_input("Enter avatar color as a hex code (black won't show): ")
    
    screen = Screen()
    screen.bgcolor("black")
    
    player = Turtle(visible=False)
    player.speed('fastest')
    player.color(color)
    player.up()
    player.sety(CURSOR_SIZE/2 - SIZE/2)
    player.setheading(90)
    player.showturtle()
    
    draw_border()
    
    screen.onkey(k1, "Up")
    screen.onkey(k2, "Left")
    screen.onkey(k3, "Right")
    screen.onkey(k4, "Down")
    
    screen.listen()
    mainloop()
    

    至于门和钥匙,如果您也将它们设为海龟,您可以简单地使用海龟的.distance() 方法进行碰撞检测。

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2017-08-09
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      相关资源
      最近更新 更多