我正在尝试使用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()
我不尝试任何颜色检测,因为我不知道从哪里开始。
答案 0 :(得分:1)
我建议您不基于颜色进行碰撞检测。您有可能跌倒乌龟的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()
方法即可进行碰撞检测。