首页 > 解决方案 > 龟屏监听允许多线程?

问题描述

我正在用 PyTurtle 编写一个类似于 Asteroids 的简单游戏。目前,我有一艘船(乌龟),它可以射箭(也是乌龟)来尝试击中目标(乌龟)。我决定将shoot()函数绑定到空格键。

在 repl.it 中进行测试时,我突然意识到,当我向 Space 发送垃圾邮件时,会出现意外的箭头行为。尽管每次调用都shoot()应该按顺序运行一个 for 循环 100 次,但不知何故,所有的箭弹都同时移动。我希望看到每个箭头一个接一个地依次移动,但这些箭头却是平行移动的。

为什么会这样?它与screen.listen()允许多线程或其他什么有关吗?还是 Turtle 只是多线程的?

import turtle
import random

# Create the basic turtle and screen objects
turt = turtle.Turtle()
screen = turtle.Screen()

# Set colors and speed
turt.color('cyan')
turt.speed(100)
screen.bgcolor('black')

# Create target turtle and move it to a random location
target = turtle.Turtle()
target.color('red')
target.shape('circle')
target.speed(100)
target.penup()
target.goto(random.randint(-200, 200), random.randint(-200, 200))

# Initialize target hit count
count = 0

# Function to turn turtle left
def left():
  turt.left(5)

# Function to turn turtle right
def right():
  turt.right(5)

# Function to shoot arrow towards the direction of the turtle
def shoot():
  # Call 'global count' to change the variable from inside the function
  global count
  arrow = turtle.Turtle()
  arrow.speed(100)
  arrow.color('yellow')
  arrow.setheading(turt.heading())
  arrow.penup()
  # Move forward until the turtle is not visable on the canvas
  for i in range(100):
    arrow.forward(5)
    # Check if the arrow collides with the target
    if abs(arrow.xcor() - target.xcor()) < 10 and abs(arrow.ycor() - target.ycor()) < 10:
      # If the arrow collides with the target, reposition the target
      target.goto(random.randint(-200, 200), random.randint(-200, 200))
      count = count + 1
      print(count)

# Connect functions to keyboard keys
screen.onkey(left, 'left')
screen.onkey(right, 'right')
screen.onkey(shoot, 'space')

# Begin listening to keyboard inputs
screen.listen()

标签: pythonturtle-graphicspython-turtle

解决方案


推荐阅读