【发布时间】:2017-12-03 03:58:12
【问题描述】:
您好,我是 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()
【问题讨论】:
-
见Create more than two turtles and moving them - 它使用
ontimer()和"small steps"来移动许多海龟。 -
顺便说一句:
onclick()(类似于onscreenclick和Thread(target=...))需要没有()(也称为callback)的函数名,但你在onclick(shoot())中使用(),所以你获取result = shoot() ; onclick(result)。但是shoot()返回None,所以你得到onclick(None)。顺便说一句:onclick/onscreenclick 运行带有两个参数的函数x,y所以你需要def shoot(x, y): -
顺便说一句:你忘了
turtle.mainloop()- 也许它会在没有mainloo()的IDLE或其他基于tkinter的工具的情况下运行mainloop()(turtle是基于tkinter也一样)但在IDLE之外它将不起作用。 -
感谢您的帮助@furas!我进行了您建议的更改,但是入侵无法与射击功能同时发生的问题仍然存在……在此问题之上,我注意到了一个新问题,其中射击功能由于某种原因无限递归的。我究竟做错了什么?非常感谢您的帮助和耐心。
-
@furas homex = turtle.xcor() homey = turtle.ycor() x = homex y = homey def shoot(x,y): turtle.color('red') turtle.showturtle( ) turtle.pu() turtle.onscreenclick(turtle.goto) turtle.goto(homex, homey) turtle.onclick(shoot(x,y)) defingression(): x = 0 while x name == 'main': Thread(target =ingress()).start() Thread(target = shoot(x,y)).start () turtle.mainloop()
标签: python multithreading python-3.x parallel-processing turtle-graphics