python - Python Turtle 碰撞循环
问题描述
我正在尝试构建一个简单的游戏。用户控制海龟。当它接触圆圈时,圆圈会重新定位,玩家将获得一分。该程序只运行一次这一位,请参见代码中的注释。我如何使程序始终运行它?我认为 mainloop() 做到了这一点。
def move_t2():
t2.ht()
rc_list = [-300, -250, -200, -150, -100, -50, 0, 50, 100, 150, 200, 250, 300]
r1 = random.choice(rc_list)
r2 = random.choice(rc_list)
t2.setpos(r1, r2)
t2.st()
def more_points():
t3_points.clear()
new_points=points + 1
if new_points >=0:
t3_points.write("Points "+str(new_points),font=10)
# The program only run this part one time. I want it to loop.
if t.distance(t2) < 50:
move_t2()
more_points()
def mr():
if t.xcor()<301:
t.setheading(0)
t.fd(50)
else:
t.setheading(180)
def ml():
if t.xcor() > -301:
t.setheading(180)
t.fd(50)
else:
t.setheading(0)
def mu():
if t.ycor() < 301:
t.setheading(90)
t.fd(50)
else:
t.setheading(270)
def md():
if t.ycor() > -301:
t.setheading(270)
t.fd(50)
else:
t.setheading(90)
ts.onkey(mr,"Right")
ts.onkey(ml,"Left")
ts.onkey(mu,"Up")
ts.onkey(md,"Down")
ts.listen()
ts.mainloop()
解决方案
该程序只运行一次这一位,请参见代码中的注释。我如何使程序始终运行它?我认为 mainloop() 做到了这一点。
有问题的代码位位于顶层,仅设置为运行一次。将mainloop()
控制权移交给事件处理程序,以便键盘键等可以触发事件。需要发生的是碰撞检查代码需要成为一个函数并添加到每个键盘事件处理程序中:
from turtle import Screen, Turtle
from random import choice
POSITION_LIST = [-300, -250, -200, -150, -100, -50, 0, 50, 100, 150, 200, 250, 300]
FONT = ('Arial', 18, 'normal')
def move_turtle(t):
t.hideturtle()
r1 = choice(POSITION_LIST)
r2 = choice(POSITION_LIST)
t.setpos(r1, r2)
t.showturtle()
points = 0
def more_points():
global points
points += 1
pen.clear()
pen.write("Points: {}".format(points), align='center', font=FONT)
def mr():
if t1.xcor() < 301:
t1.setheading(0)
t1.fd(25)
else:
t1.setheading(180)
check_collision()
def ml():
if t1.xcor() > -301:
t1.setheading(180)
t1.fd(25)
else:
t1.setheading(0)
check_collision()
def mu():
if t1.ycor() < 301:
t1.setheading(90)
t1.fd(25)
else:
t1.setheading(270)
check_collision()
def md():
if t1.ycor() > -301:
t1.setheading(270)
t1.fd(25)
else:
t1.setheading(90)
check_collision()
def check_collision():
if t1.distance(t2) < 20:
move_turtle(t2)
more_points()
screen = Screen()
screen.setup(700, 700)
t1 = Turtle()
t1.shape('turtle')
t1.penup()
move_turtle(t1)
t2 = Turtle()
t2.shape('circle')
t2.penup()
move_turtle(t2)
pen = Turtle()
pen.hideturtle()
pen.penup()
pen.sety(-325)
pen.write("Points: {}".format(points), align='center', font=FONT)
screen.onkey(mr, "Right")
screen.onkey(ml, "Left")
screen.onkey(mu, "Up")
screen.onkey(md, "Down")
screen.listen()
screen.mainloop()
推荐阅读
- javascript - 进行两次数据库调用并在一个 ejs 页面中呈现由结果填充的两个不同数组的内容
- google-chrome-extension - 如何同时拥有 Chrome 扩展的用户和开发者组
- python - 如何在 Python 上用不同大小的数组列表填充矩阵?
- multithreading - 每个线程都有它的主要功能吗?
- sql - 从其他报告中调用报告
- jenkins - 在 Groovy jenkins 管道脚本中按值对地图进行排序
- kql - 如何将 KQL 结果打印到 ASCII 表
- java - Setter 返回 this vs builder
- kubernetes - 使用 CNI 设置网络
- python - 将上传进度从 S3 Boto3 发送到 Angular 前端