我想制作一个《太空侵略者》游戏,但如果敌人被击中,我的敌人就不会消失。有人知道如何解决吗?
我已经尝试过for
循环(如您所见),但是它不起作用:
import turtle as tr
wn = tr.Screen()
wn.tracer(0)
bullet = tr.Turtle()
player = tr.Turtle()
enimis = []
y = -250
def shoot():
player.direction = "up"
wn.onkey(shoot,"space")
while True:
if len(enimis) == 0:
for u in range(-210,210,60):
for o in range(100,260,60):
enimi = tr.Turtle()
enimi.setpos(u,o)
enimis.append(enimi)
if player.direction == "up":
bullet.penup()
x = player.xcor()
bullet.setpos(x,y)
bullet.pendown()
for p in range(550):
bullet.setpos(x,y+p)
for k in enimis:
if bullet.distance(k) < 25:
score += 10
if score > highscore:
highscored = True
else:
highscored = False
del k
hit = True
break
else:
hit = False
wn.update()
没有任何错误消息,敌人不会消失。
答案 0 :(得分:0)
我不明白为什么在此错误导致代码完全无法运行时,您为何坚持让死去的敌人消失:
if player.direction == "up":
AttributeError: 'Turtle' object has no attribute 'direction'
您也无法击中敌人,因为您的玩家和敌人无法移动且玩家没有指向敌人。 不可思议的思想太多,代码不足。
要回答您的问题,这是行不通的:
for k in enimis:
if bullet.distance(k) < 25:
# ...
del k
# ...
break
它要么必须是:
for k in enimis:
if bullet.distance(k) < 25:
# ...
enimis.remove(k) # remove by value
# ...
break
或:
for k in range(len(enimis)):
if bullet.distance(enimis[k]) < 25:
# ...
del enimis[k] # remove by index
# ...
break
以下是我对您的代码的完整重写,以使其基本能够发挥作用:玩家可以左右移动;子弹射击,击中敌人,得分并消失;分数显示在屏幕上;等
from turtle import Screen, Turtle
BASELINE = -250
FONT = ('Arial', 18, 'bold')
def left():
player.setx(player.xcor() - 5)
def right():
player.setx(player.xcor() + 5)
def shoot():
global firing
firing = True
firing = False
enemies = []
score = 0
bullet = Turtle('triangle')
bullet.hideturtle()
bullet.speed('fastest')
bullet.shapesize(0.5)
bullet.setheading(90)
bullet.penup()
player = Turtle('turtle')
player.hideturtle()
player.speed('fastest')
player.color('green')
player.setheading(90)
player.penup()
player.sety(BASELINE)
player.showturtle()
marker = Turtle()
marker.hideturtle()
marker.penup()
marker.goto(-300, 300)
marker.write("Score: {}".format(score), align='center', font=FONT)
def play():
global firing, score
if not enemies:
screen.tracer(False)
for x in range(-210, 210, 60):
for y in range(100, 260, 60):
enemy = Turtle('turtle')
enemy.color('red')
enemy.setheading(270)
enemy.penup()
enemy.setpos(x, y)
enemies.append(enemy)
screen.tracer(True)
if firing:
bullet.setx(player.xcor())
bullet.sety(BASELINE)
bullet.showturtle()
for p in range(0, 550, 5):
bullet.sety(BASELINE + p)
for enemy in enemies:
if bullet.distance(enemy) < 20:
score += 10
marker.undo()
marker.write("Score: {}".format(score), align='center', font=FONT)
enemy.clear()
enemy.hideturtle()
enemies.remove(enemy)
break
else: # no break
continue
break
bullet.clear()
bullet.hideturtle()
firing = False
screen.ontimer(play, 100)
screen = Screen()
screen.onkey(shoot, 'space')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
play()
screen.mainloop()
仍然需要:向左,向右和向下移动敌人;使子弹射击和玩家/敌人的移动同时发生;加回highscore
;等