问题描述
我有两种类型的气球,一种蓝色和一种红色(50% 的几率生成红色或绿色气球)。如果它弹出一个绿色气球,玩家将获得 2 分,如果它弹出一个红色气球,将获得 -2 分。 -1 如果绿色气球飞走。 我创建了分数计数,但只有一个气球,这意味着如果我同时弹出红色和绿色气球但我被卡在这里,则分数有效(+2)。 我不知道 random.choice 是否是获得 50% 机会的最佳方式 这是一段代码:
class SpawnTime():
def __init__(self,prevIoUs,time):
self.time_prevIoUs = prevIoUs
self.time= time
class Balloon():
count = 0
def __init__(self):
self.txr = random.choice(BALLOONS_TYPE)
self.width = self.txr.get_width()
self.height = self.txr.get_height()
self.x = random.randint(0,SCREEN_WIDTH-self.width)
self.y = SCREEN_HEIGHT
self.rect = pygame.Rect(self.x,self.y,self.width,self.height)
self.speed = random.randint(MIN_BALLOON_SPEED,MAX_BALLOON_SPEED)
self.active = True
Balloon.count +=1 # add 1 to balloon counter
def update(self):
self.rect.y -= self.speed
if self.rect.bottom <= 0: # off top of screen
self.active= False
def draw(self):
SCREEN.blit(self.txr,self.rect)
class Player():
def __init__(self):
self.x = 0
self.y = 0
self.txr = pygame.image.load('assets/sprites/player.png')
self.width = self.txr.get_width()
self.height = self.txr.get_height()
self.rect = pygame.Rect(self.x,self.height )
self.score = 0
def update(self):
self.x,self.y = pygame.mouse.get_pos()
self.rect.x= self.x
self.rect.y= self.y
def draw(self):
SCREEN.blit(self.txr,self.rect)
def clicked(self):
# check if player has clicked on a balloon
for b in balloons:
if b.rect.collidepoint(self.x,self.y):
self.score +=2
b.active=False
break # exit the for loop
解决方法
不要使用ranfom.choice
,而是使用random.randrange
通过它的索引随机选择一个元素(见random
):
class Balloon():
count = 0
def __init__(self):
self.balloon_type = random.randrange(len(BALLOONS_TYPE))
img = BALLOONS_TYPE[self.balloon_type]
self.width = img.get_width()
self.height = img.get_height()
# [...]
def draw(self):
SCREEN.blit(BALLOONS_TYPE[self.balloon_type],self.rect)
现在您可以根据气球的类型更改分数:
class Player():
# [...]
def clicked(self):
# check if player has clicked on a balloon
for b in balloons:
if b.rect.collidepoint(self.x,self.y):
if b.balloon_type == 0:
self.score += 2
else
self.score -= 2
b.active=False
break # exit the for loop
(我不知道是红色气球还是绿色气球先出现,所以你可能需要交换+=2
和-=2
)