python - 使用线程和/或多处理同时移动多个 turtle

标签 python multithreading python-3.x parallel-processing turtle-graphics

嗨,我是 python 新手,也是堆栈交换新手。我正在尝试使用 turtle 创建一个太空入侵者游戏,但我遇到了一个问题,在所有外星人完成入侵之前我的枪无法射击。我认为我遇到这个问题是因为入侵功能和射击功能没有同时运行,或者因为 turtle 不允许同时移动超过一只 turtle 。

我尝试使用线程并行运行这两个函数,但它没有解决问题,直到入侵完成后枪才能开火。任何帮助将不胜感激! (我对 python 很陌生,所以我对代码的困惑表示歉意)

import turtle
import random
import threading
from threading import Thread

screen = turtle.Screen()
screen.setup(400, 500)
screen.bgpic("/Users/benmartinez/Desktop/Space_Invaders_BG.gif")

turtle.right(90)
turtle.pu()
turtle.forward(200)
turtle.pd()
turtle.right(90)
turtle.forward(200)
turtle.right(90)
turtle.forward(500)
turtle.right(90)
turtle.forward(400)
turtle.right(90)
turtle.forward(500)
turtle.right(90)
turtle.forward(200)

turtle.right(180)
turtle.forward(20)

turtle.left(90)

turtle.circle(20, 180)

turtle.left(90)
turtle.forward(20)
turtle.left(90)

homex = turtle.xcor()
homey = turtle.ycor()

def shoot():
    turtle.color('red')
    turtle.showturtle()
    turtle.pu()
    turtle.onscreenclick(turtle.goto)
    turtle.goto(homex, homey)
    turtle.onclick(shoot())

def invaders():
    invader_initial_position = random.randint(-200, 200)
    i = turtle.Turtle()
    i.shape('triangle')
    i.color('green')
    i.pu()
    i.hideturtle()
    i.goto(invader_initial_position, 300)
    i.showturtle()
    i.right(90)
    i.speed(1)
    i.forward(500)

def invasion():
    x = 0
    while x < 10:
        invaders()
        x += 1

#if __name__ == '__main__':
Thread(target = invasion()).start()
Thread(target = shoot()).start()

最佳答案

Thread(target = Invasion()) 应该是 Thread(target = Invasion) 吗?否则,您将立即调用该函数,而不是传递要由线程调用的函数。

关于python - 使用线程和/或多处理同时移动多个 turtle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615105/

相关文章:

python - 如何修改字典输出

python pandas dataframe线程安全吗?

Python在特定区间选择随机数

python 调用类方法而不初始化类

c++ - 我应该使用单例设计模式还是其他方式实现线程安全队列?

django - 'ManyToManyDescriptor'对象在django 2中没有属性'all'

php - 在 PHP CLI 中使用并行线程运行大循环

multithreading - 硬件线程与软线程?

python - MacPorts 说当运行 "python --version"时我仍然有 Python 2.7

python - 不使用 Itertools 组合两个列表