我正在用Python创建一个简单的游戏,使用海龟包。
我的目标是让一些气球在屏幕上从右到左运行,然后当其中一个被点击以使它消失。
我做错的是,当我点击一个气球,他们都消失了!
这是我的密码
1-主要
from turtle import Screen
from balloon import Balloon
import time
screen = Screen()
screen.title('Balloons Nightmare')
screen.setup(width=600, height=600)
screen.bgpic(picname='sky-clouds.gif')
screen.tracer(0)
balloons_manager = Balloon()
current_x = 0
current_y = 0
screen.listen()
screen.onclick(fun=balloons_manager.explode_balloon, btn=1)
game_is_on = True
while game_is_on:
time.sleep(0.1)
screen.update()
balloons_manager.create_balloon()
balloons_manager.move_balloon()
screen.exitonclick()2-气球模块
import random
from turtle import Turtle
COLORS = ["red", "yellow", "green", "blue", "black"]
MOVEMENT_SPEED = 2
class Balloon:
def __init__(self):
self.all_balloons = []
self.balloon_speed = MOVEMENT_SPEED
self.x = 0
self.y = 0
self.hidden = None
def create_balloon(self):
random_choice = random.randint(1, 9)
if random_choice == 1:
new_balloon = Turtle("circle")
new_balloon.penup()
new_balloon.turtlesize(stretch_wid=2, stretch_len=0.75)
new_balloon.color(random.choice(COLORS))
random_y_cor = random.randint(-50, 280)
new_balloon.goto(320, random_y_cor)
self.hidden = new_balloon.isvisible()
self.all_balloons.append(new_balloon)
def move_balloon(self):
for balloon in self.all_balloons:
balloon.backward(self.balloon_speed)
def explode_balloon(self, x, y):
for balloon in range(len(self.all_balloons)):
print(self.all_balloons[balloon].position())
self.all_balloons[balloon].hideturtle()
# for balloon in self.all_balloons:
# balloon.hideturtle()我尝试了这么多的改变,但是没有任何帮助,例如我尝试到目前为止得到气球的x,y坐标,所以只要点击就可以隐藏有这些坐标的那个,但是对我没有用,或者我做错了什么。
如有任何提示将不胜感激。
谢谢
发布于 2022-09-22 18:15:59
下面是由单击处理程序触发的代码:
def explode_balloon(self, x, y):
for balloon in range(len(self.all_balloons)):
print(self.all_balloons[balloon].position())
self.all_balloons[balloon].hideturtle()这会在所有气球上盘旋,并无条件地隐藏它们。
您可能希望在其中使用if只有条件地触发隐藏行为。将单击的x和y坐标与循环中的当前气球进行比较。只有当距离小于一定数量(例如气球半径)时,才隐藏气球。
另一种方法是使用turtle.onclick添加一个处理程序函数,该函数将在单击海龟时触发。
相关信息:
发布于 2022-09-22 18:28:05
我通过在create_balloon函数中添加一个内部函数来解决这个问题
def create_balloon(self):
random_choice = random.randint(1, 9)
if random_choice == 1:
new_balloon = Turtle("circle")
new_balloon.penup()
new_balloon.turtlesize(stretch_wid=2, stretch_len=0.75)
new_balloon.color(random.choice(COLORS))
random_y_cor = random.randint(-50, 280)
new_balloon.goto(320, random_y_cor)
def hide_the_balloon(x, y):
return new_balloon.hideturtle()
new_balloon.onclick(hide_the_balloon)
self.all_balloons.append(new_balloon)https://stackoverflow.com/questions/73818999
复制相似问题