微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pygame 气球流行游戏:气球等级和得分

如何解决Pygame 气球流行游戏:气球等级和得分

我有两种类型的气球,一种蓝色和一种红色(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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。