嗨,我是python的新手,也是堆叠交换的新手。我正在尝试使用乌龟创建一个太空入侵者游戏,但是我遇到了一个问题,即我的枪无法射击直到所有外星人都完成了入侵。我想我遇到了这个问题,因为入侵功能和射击功能没有同时运行,或者因为乌龟不允许一次移动多只乌龟。
我试图使用线程并行运行这两个函数,但它没有解决问题,在入侵完成之前枪无法开火。任何帮助将不胜感激! (我对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()
答案 0 :(得分:1)
Thread(target = invasion())
应为Thread(target = invasion)
?否则,您将立即调用该函数,而不是传递要由Thread调用的函数。