Exemple #1
0
class ConsoleGame:
    def __init__(self, player1: Player, player2: Player) -> None:
        self.player1 = player1
        self.player2 = player2
        self.fighter = Fighter(player1, player2)

    def run(self):
        game_over = False
        while not game_over:
            to_move = self.fighter.get_attacker()
            defender = self.fighter.get_defender()
            print_player_info(to_move)
            print_player_info(defender)
            print("Введите 'potion' или 'skill' в зависимости от того, что вы хотите использовать.")
            while True:
                move_type = input()
                if move_type == "potion":
                    print("Введите номер зелья.")
                    move = input()
                    if move == "back":
                        continue
                    number = int(move)
                    potions = [i for i in to_move.inventory.items if type(i) is Potion]
                    self.fighter.step(UsePotion(potions[number]))
                    print("Выбранное зелье: {}".format(potions[number]))
                    break
                if move_type == "skill":

                    print("Выбранный скил: {}".format(to_move.active_skills[number].name))
                    is_finished, damage = self.fighter.step(UseActiveSkill(to_move.active_skills[number]))
                    print("Нанесенный урон: {}".format(damage))
                    break
Exemple #2
0
    def __init__(self):
        """Inits game and create game resources"""
        # * inits background setting for pygame
        pygame.init()

        # * creates Surface display window, for drawing game
        # instance of Settings
        self.settings = Settings()

        # *  ASSIGNS MAIN DISPLAY SURFACE
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        # *  CREATE FULLSCREEN
        # self.screen = pygame.display.set_mode(
        #     (0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Tetris Dump Universe")

        # * FIGHTER INSTANCE
        # Fighter requires one instance of TDU game so we pass self for the current intance of the TDU game class
        self.fighter = Fighter(self)

        # * BULLETS INSTANCES
        self.bullets = pygame.sprite.Group()

        # * ALIEN GROUP INSTANCE
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
Exemple #3
0
 def add_fighter(self, unit, team_id, summon = False):
     ''' Добавляет файтера в битву.
         unit - может быть User или Mob. "Источник" для файтера.
         int team_id - номер команды.
         Возвращает файтера.
     '''
     if isinstance(unit, user.User):
         res = Fighter.from_user(self, unit, team_id)
         self.p[team_id].append(res)
         unit.enter_fight(self, team_id)
         return res
     elif isinstance(unit, mob.Mob):
         if summon:
             res = Fighter.summon(self, unit, team_id)
         else:
             res = Fighter.from_mob(self, unit, team_id)
         haveSameMobs = False
         for f in self.p[team_id]:
             if f._type in ["mob", "summon"] and f.mob_id == unit.id:
                 haveSameMobs = True
                 if f.name == unit.name:
                     f.name = self.get_unique_mob_name(f)
         if haveSameMobs:
             res.name = self.get_unique_mob_name(res)
         self.p[team_id].append(res)
         return res
     else:
         raise Exception("not implemented")
Exemple #4
0
    def __init__(self):
        pygame.mixer.pre_init(frequency=22050, size=-16, channels=8, buffer=256)
        pygame.init()
        pygame.display.set_caption("Injection")
        pygame.mixer.init()
        self.clock = pygame.time.Clock()
        self.surface = pygame.display.set_mode((1024, 768), pygame.DOUBLEBUF)
        self.viewport = Viewport(self)
        self.world = World(self, "gfx/world01.json")
        self.fighter1 = Fighter(self, 'g', startpos=(100, 0))
        self.fighter2 = Fighter(self, 'r', startpos=(850, 0))
        self.fighter2.rect.left = 800
        self.pointsbar1 = PointsBar(self.fighter1, pygame.Rect(22, 17, 323, 27), color=1)
        self.pointsbar2 = PointsBar(self.fighter2, pygame.Rect(683, 17, 323, 27), color=2)
        self.injectionsbar1 = InjectionsBar(self.fighter1, pygame.Rect(33, 50, 300, 27))
        self.injectionsbar2 = InjectionsBar(self.fighter2, pygame.Rect(695, 50, 300, 27))
        self.roundcounter = RoundCounter(self, pygame.Rect(427, 0, 167, 50))
        self.ai = FightingAi(self, self.fighter2)
        self.menu = Menu(self)
        self.ignore_keys = False
        self.multiplayer = 0

        self.fireballs = []
        pygame.mixer.music.load("snd/music.wav")
        pygame.mixer.music.set_volume(.35)
        #pygame.mixer.music.set_volume(0)
        pygame.mixer.music.play()
        self.f = self.fighter1
Exemple #5
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Zombie Appocalypse')

    play_button = Button(ai_settings, screen, "Play Game")

    fighter = Fighter(ai_settings, screen)
    bullets = Group()
    zombies = Group()

    gf.create_fighter(ai_settings, screen, fighter, zombies)

    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, fighter, zombies, bullets)
        if stats.game_active:
            fighter.update()
            bullets.update()
            gf.update_bullets(ai_settings, screen, stats, sb, fighter, zombies, bullets)
            gf.update_zombies(ai_settings, stats, screen, fighter, zombies, bullets)

        gf.update_screen(ai_settings, screen, stats, sb, fighter, zombies, bullets, play_button)
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    # 设置窗口标题
    pygame.display.set_caption("Enemy Invasion")

    # 创建Play按钮
    play_button = Button(ai_settings, screen, "Play")

    # 创建一个用于存储游戏统计信息的实例,并创建记分牌
    stats = GameStats(ai_settings)
    scoreboard = Scoreboard(ai_settings, screen, stats)

    # 创建一艘新的战斗机、一个子弹编组和一个敌机编组
    fighter = Fighter(ai_settings, screen)
    bullets = Group()
    enemies = Group()

    # 创建敌机舰队
    gf.create_fleet(ai_settings, screen, fighter, enemies)

    # 开始游戏的主循环
    while True:
        # 监听键盘和鼠标事件
        gf.check_events(ai_settings, screen, stats, scoreboard, play_button, fighter, enemies, bullets)

        if stats.game_active:
            fighter.update()
            gf.update_bullets(ai_settings, screen, stats, scoreboard, fighter, enemies, bullets)
            gf.update_enemies(ai_settings, screen, stats, scoreboard, fighter, enemies, bullets)

        gf.update_screen(ai_settings, screen, stats, scoreboard, fighter, enemies, bullets, play_button)
def run_game():
    # initialize game and create a screen object
    pygame.init()
    f_settings = Setting()
    screen = pygame.display.set_mode((f_settings.screen_width, f_settings.screen_height))
    pygame.display.set_caption("Alien Attack!")
    # Make a fighter, a group of bullets and a group of aliens
    fighter = Fighter(f_settings, screen)
    aliens = Group()
    bullets = Group()

    # Create play button
    play_button = Button(f_settings, screen, "Play")

    # Create an instance to store game stats
    stats = GamesStats(f_settings)

    # Create the fleet of aliens
    gf.create_fleet(f_settings, screen, aliens, fighter)

    # Create scoreboard
    sb = Scoreboard(f_settings, screen, stats, fighter)

    # Start the main loop for the game.
    while True:
        gf.check_events(f_settings, screen, aliens, fighter, bullets, play_button, stats, sb)
        if stats.game_active:
            fighter.position()
            gf.update_bullets(f_settings, screen, stats, fighter, bullets, aliens, sb)
            gf.update_aliens(f_settings, screen, aliens, fighter, bullets, stats, sb)
        gf.screen_update(f_settings, screen, fighter, bullets, aliens, stats, play_button, sb)
Exemple #8
0
 def __init__(self, name):
     Fighter.__init__(self,
                      Weapon.preset('Rusty Sword'),
                      health=50,
                      name=name,
                      ac=8)
     self.inventory = Inventory([self.__weapon__])
     self.needed = BASE_XP_NEEDED
Exemple #9
0
def run_game():
    #获取游戏参数
    game_settings = Settings()

    #初始化游戏
    pygame.init()
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("飞机大战")

    #初始化游戏控制
    gs = GameStats(game_settings, screen)

    #定义玩家
    player = Fighter(game_settings, screen, gs.img_role)

    #存储敌机
    enemies1 = pygame.sprite.Group()
    enemies_down = pygame.sprite.Group()

    #存储补给
    supplies = pygame.sprite.Group()

    #定义时钟
    clock = pygame.time.Clock()

    while True:
        # 控制游戏帧数,表示每秒循环60次
        clock.tick(60)

        if gs.bStarted and not gs.bPaused and not gs.bOver and not gs.bWin:
            #发射子弹
            player.shoot(gs)

            #生成敌机
            Enemy.discover(game_settings, gs, enemies1)

            #生成补给
            Supply.discover(game_settings, gs, supplies)

            #更新敌机并检测碰撞
            cf.update_enemies(screen, enemies1, enemies_down, player,
                              gs.sound_gameover)

            #更新子弹并检测碰撞
            cf.update_bullets(game_settings, player, enemies1, enemies_down,
                              supplies)

            #更新补给并检测碰撞
            cf.update_supplies(game_settings, gs, player, enemies1,
                               enemies_down, supplies)

        #更新画面
        cf.update_screen(game_settings, gs, screen, player, enemies1,
                         enemies_down, supplies)

        #鼠标和键盘事件处理
        cf.check_events(gs, player)
Exemple #10
0
    def create(self):
        name = input("Name: ")
        hp = int(input("hp: "))
        attack = int(input("Attack Damage: "))
        defense = int(input("Defense: "))

        fighter = Fighter(name, hp, attack, defense)
        fighter.save()
        return fighter
Exemple #11
0
    def __init__(self, screen, clock):

        self.screen = screen
        self.clock = clock
        self.width, self.height = self.screen.get_size()

        self.world = World(self.width, self.height)
        self.knight = Fighter('Knight', 30, 10, 3, 0)
        self.bandits = self.create_bandits(2)
Exemple #12
0
    def test_one(self):
        hero = Fighter("Hero", 8)
        hero.set_attack(5)
        hero.set_armor(5)

        boss = Fighter("Boss", 12)
        boss.set_attack(7)
        boss.set_armor(2)

        battle = Battle(hero, boss)
        battle.start()
        expected = hero
        actual = battle.get_winner()
        self.assertEqual(expected, actual)
Exemple #13
0
def initGame():
    global gamepad, clock, fighter, bullet, boss ,shot, explosion
    # 게임이 진행될 게임 화면, 게임의 초당 프레임(FPS), 비행기 변수 선언, 적 선언
    global enemys, items
    pygame.init()
    gamepad = pygame.display.set_mode((pad_width, pad_height))  # 게임화면의 가로세로크기를 설정
    pygame.display.set_caption('Shooting Game')  # 게임화면의 제목 지정

    fighter = Fighter()
    for i in range(10):
        enemys.append(Enemy())

    items.append( HP_UP())
    items.append( POWER_UP())
    items.append( SCORE_UP())
    items.append( SUPER_POWER_UP())



    bullet = Bullet()
    boss = Boss()
    shot = pygame.image.load('image/shot.png')
    explosion = pygame.image.load('image/explosion.png')


    clock = pygame.time.Clock()  # 초당 프레임수를 설정할 수 있는 Clock객체 생성
Exemple #14
0
    def receive(self, message, emitter=None, data=None):
        if message == TitleScene.Events.DONE:
            current_scene = MenuScene()
            current_scene.render()
            current_scene.loop()
        elif message == MenuScene.Events.CREATE_CHARACTER:
            current_scene = CreateFighterScene()
            current_scene.render()
            current_scene.loop()
        elif message == CreateFighterScene.Events.CREATE:
            Director.characters.append(data)

        elif message == CreateFighterScene.Events.DONE:
            current_scene = MenuScene()
            current_scene.render()
            current_scene.loop()

        elif message == MenuScene.Events.LIST_CHARACTER:
            self.characters = Fighter.all()
            current_scene = ShowCharactersScene(self.characters)
            current_scene.render()
            current_scene.show_fighters()

        elif message == MenuScene.Events.SELECT_CHARACTER:
            # TODO:
            print('PENDING: make select character scene')
        elif message == MenuScene.Events.REMOVE_CHARACTER:
            # TODO:
            print('PENDING: make remove character scene')
def thresher(x, y):
    fighter_component = Fighter(current_hp=26,
                                max_hp=26,
                                damage_dice=2,
                                damage_sides=6,
                                armour=3,
                                strength=20,
                                dexterity=12,
                                vitality=12,
                                intellect=5,
                                perception=8,
                                xp=275,
                                dodges=True)
    ai_component = AimlessWanderer()
    monster = Entity(
        x,
        y,
        'T',
        libtcod.dark_azure,
        'Thresher',
        'A colossal ogre-like hominid covered in patches of matted hair and littered with scars. This '
        'creature tirelessly searches it\'s surroundings for new objects to smash together with a '
        'joyous, childlike expression.',
        blocks=True,
        fighter=fighter_component,
        render_order=RenderOrder.ACTOR,
        ai=ai_component,
        regenerates=True,
        faction='Scavengers',
        errasticity=75)
    return monster
def moire_beast(x, y):
    fighter_component = Fighter(current_hp=14,
                                max_hp=14,
                                damage_dice=3,
                                damage_sides=2,
                                armour=1,
                                strength=10,
                                dexterity=16,
                                vitality=12,
                                intellect=10,
                                perception=10,
                                xp=200,
                                dodges=True)
    ai_component = Aggressive()
    monster = Entity(
        x,
        y,
        'M',
        libtcod.light_grey,
        'Moire Beast',
        'The hide of this squat quadruped is an affront to the senses; dense and intricate greyscale '
        'patterns constantly shift epileptically upon the beast\'s surface like a surrealist '
        'interpretation of a zebra. The gleam of it\'s fluorescent yellow, feline irises serve as the only '
        'ubiquitous reference point on this beast\'s wildly fluctuating, migraine-inducing form.',
        blocks=True,
        render_order=RenderOrder.ACTOR,
        fighter=fighter_component,
        ai=ai_component,
        regenerates=True,
        faction='Beasts')
    return monster
def whip_vine(x, y):
    fighter_component = Fighter(current_hp=4,
                                max_hp=4,
                                damage_dice=1,
                                damage_sides=2,
                                armour=1,
                                strength=14,
                                dexterity=6,
                                vitality=10,
                                intellect=0,
                                perception=0,
                                xp=25,
                                dodges=False)
    ai_component = Stationary()
    monster = Entity(
        x,
        y,
        'V',
        libtcod.light_grey,
        'Whip Vine',
        'What at first appears to be no more than a dead, waist-height bush in actuality '
        'represents a highly specialized carnivorous plant that flays the skin off any creature '
        'that wanders into its path.',
        blocks=True,
        render_order=RenderOrder.PLANT,
        fighter=fighter_component,
        ai=ai_component,
        faction='Plants')
    return monster
def sludge_fiend(x, y):
    fighter_component = Fighter(current_hp=6,
                                max_hp=6,
                                damage_dice=1,
                                damage_sides=5,
                                armour=0,
                                strength=16,
                                dexterity=8,
                                vitality=10,
                                intellect=6,
                                perception=8,
                                xp=50,
                                dodges=True)
    ai_component = AimlessWanderer()
    monster = Entity(
        x,
        y,
        'f',
        libtcod.red,
        'Sludge Fiend',
        'The irony of attempting to retain one\'s humanity whilst simultaneously seeking to consume '
        'all mutagenic material in one\'s path seems to be lost on this poor unfortunate. Tattered clothing '
        'drips off this mutant\'s twisted form like a bullet-shredded cape; obsidian spikes protrude '
        'in clusters from its emaciated and discoloured torso.',
        blocks=True,
        render_order=RenderOrder.ACTOR,
        fighter=fighter_component,
        ai=ai_component,
        regenerates=True,
        faction='Scavengers',
        errasticity=50)
    return monster
Exemple #19
0
 def setEnemy(self, enum, x, y):
     if (enum == 0):
         return Drone(x, y)
     elif (enum == 1):
         return Fighter(x, y)
     elif (enum == 2):
         return Diver(x, y)
Exemple #20
0
    def create_bandits(self, amount):

        arr = []

        for i in range(amount):
            arr.append(Fighter("Bandit", 20, 6, 1, i))

        return arr
async def restart_fight(ctx, name: str):
    global turnCounter
    turnCounter = 0
    enemy_dict['mook1'].setStats('mook1', 2, 0, 0, 0, 10, 10, 0)
    enemy_dict['mook2'].setStats('mook2', 2, 3, 0, 0, 10, 5, 0)
    enemy_dict['boss'] = Fighter('boss', 4, 3, 4, 5, 12, 15, 3)
    protag.setStats(name, 5, 3, 3, 5, 11, 20, 3)

    enemy_dict['mook1'].setCombat(1)
    enemy_dict['mook2'].setCombat(1)
    enemy_dict['boss'].setCombat(0)
    await ctx.send('Combat has restarted. Your enemies are mook1 and mook2. To attack, input command punch, magic, or mana blast (has chargetime)')
Exemple #22
0
    def __init__(self, Character1, Character2, arena, roundTime=90, name1="Player1", name2="Player2"):
        ###character 1 and 2 are strings pointing to the assets with the character. will be delivered by the character-selection screen.
        ### till we have the selection screen, hardcode or default them.

        self.arena = loader.loadModel(arena)
        self.arena.reparentTo(render)
        self.arena.setScale(4)
        self.arena.find("**/ground").setCollideMask(BitMask32.bit(1))
        self.arena.find("**/ground").hide()
        self.arena.find("**/out").setCollideMask(BitMask32.bit(1))
        self.arena.find("**/out").hide()
        
        self.player1 = Fighter(Character1, self.roundEnd, 0,  name=name1 )
        self.player2 = Fighter(Character2, self.roundEnd, 1, name=name2 )
        
        self.player1.setOpponent(self.player2)
        self.player2.setOpponent(self.player1)
        self.matchCam =MatchCamera(self.player1.getNP(),self.player2.getNP(),base.camera )
        self.roundTime=roundTime
        self.timer = Timer(self.roundEnd)
        self.messages = AnimatedText()
        self.winner = AnimatedText(pos = (0.0,0.0))
        self.roundStart()
Exemple #23
0
class Game:
    def __init__(self):
        pygame.mixer.pre_init(frequency=22050, size=-16, channels=8, buffer=256)
        pygame.init()
        pygame.display.set_caption("Injection")
        pygame.mixer.init()
        self.clock = pygame.time.Clock()
        self.surface = pygame.display.set_mode((1024, 768), pygame.DOUBLEBUF)
        self.viewport = Viewport(self)
        self.world = World(self, "gfx/world01.json")
        self.fighter1 = Fighter(self, 'g', startpos=(100, 0))
        self.fighter2 = Fighter(self, 'r', startpos=(850, 0))
        self.fighter2.rect.left = 800
        self.pointsbar1 = PointsBar(self.fighter1, pygame.Rect(22, 17, 323, 27), color=1)
        self.pointsbar2 = PointsBar(self.fighter2, pygame.Rect(683, 17, 323, 27), color=2)
        self.injectionsbar1 = InjectionsBar(self.fighter1, pygame.Rect(33, 50, 300, 27))
        self.injectionsbar2 = InjectionsBar(self.fighter2, pygame.Rect(695, 50, 300, 27))
        self.roundcounter = RoundCounter(self, pygame.Rect(427, 0, 167, 50))
        self.ai = FightingAi(self, self.fighter2)
        self.menu = Menu(self)
        self.ignore_keys = False
        self.multiplayer = 0

        self.fireballs = []
        pygame.mixer.music.load("snd/music.wav")
        pygame.mixer.music.set_volume(.35)
        #pygame.mixer.music.set_volume(0)
        pygame.mixer.music.play()
        self.f = self.fighter1
    def ev_quit(self, e):
        pass

    def ev_keydown(self, e):
        if self.ignore_keys:
            return

        # Fighter 2
        if self.multiplayer:
            if e.key == pygame.K_RIGHT:
                self.fighter2.right()
            elif e.key == pygame.K_LEFT:
                self.fighter2.left()
            elif e.key == pygame.K_DOWN:
                self.fighter2.block()
            elif e.key == pygame.K_SLASH:
                self.fighter2.jump()
            elif e.key == pygame.K_PERIOD:
                self.fighter2.punch()
            elif e.key == pygame.K_COMMA:
                self.fighter2.kick()
            elif e.key == pygame.K_UP:
                if self.fighter2.current_injection < len(self.fighter2.injections) - 1:
                    self.fighter2.switch_to_injection(self.fighter2.current_injection + 1)

        # Fighter 1
        if e.key == pygame.K_d:
            self.fighter1.right()
        elif e.key == pygame.K_a:
            self.fighter1.left()
        elif e.key == pygame.K_s:
            self.fighter1.block()
        elif e.key == pygame.K_j:
            self.fighter1.jump()
        elif e.key == pygame.K_h:
            self.fighter1.punch()
        elif e.key == pygame.K_g:
            self.fighter1.kick()
        elif e.key == pygame.K_w:
            if self.fighter1.current_injection < len(self.fighter1.injections) - 1:
                self.fighter1.switch_to_injection(self.fighter1.current_injection + 1)

        elif e.key == pygame.K_ESCAPE:
            self.menu.current_menu = 0
            self.menu.active = 1
            self.roundcounter.round = -1
            self.fighter1.wins = 0
            self.fighter2.wins = 0
 
    def ev_keyup(self, e):
        if self.ignore_keys:
            return

        # Fighter 2
        if self.multiplayer:
            if e.key == pygame.K_LEFT:
                self.fighter2.stop_left()
            elif e.key == pygame.K_RIGHT:
                self.fighter2.stop_right()

        # Fighter 1
        if e.key == pygame.K_a:
            self.fighter1.stop_left()
        elif e.key == pygame.K_d:
            self.fighter1.stop_right()


    def opponent(self, caller):
        opp = self.fighter2
        if opp == caller:
            opp = self.fighter1
        return opp

    def hit_opponent(self, caller, damage, hit_boxes=None, kind='physical'):
        opp = self.opponent(caller)
        opp_hb = opp.hit_boxes()
        direction = 1
        if caller.looking_right:
            direction = -1
        if hit_boxes == None:
            hit_boxes = caller.hit_boxes()
        if any([x.collidelist(opp_hb) != -1 for x in hit_boxes]):
            opp.take_damage(damage, direction, kind=kind)
            return True
        return False

    def game_over(self):
        if self.fighter1.wins > self.fighter2.wins:
            gameover_image = pygame.image.load("gfx/player1won.png")
        else:
            gameover_image = pygame.image.load("gfx/player2won.png")

        self.surface.blit(gameover_image, (330, 140))
        self.roundcounter.render(self.surface)
        pygame.display.flip()
        while True:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    if e.key == pygame.K_RETURN:
                        self.roundcounter.round = -1
                        self.fighter1.wins = 0
                        self.fighter2.wins = 0
                        self.fighter1.reset()
                        self.fighter2.reset()
                        self.menu.activate()
                        return

    def next_round(self):
        if self.roundcounter.round < len(self.roundcounter.rounds) - 1:
            if self.fighter1.wins == 2 or self.fighter2.wins == 2:
                self.game_over()
                return
            self.fighter1.reset()
            self.fighter2.reset()
            self.ai.reset()
            for inj in self.injectionsbar1.injections[1:]:
                inj.disabled = False
                inj.activate = False
            for inj in self.injectionsbar2.injections[1:]:
                inj.disabled = False
                inj.activate = False
            self.pointsbar1.health = self.fighter1.health
            self.pointsbar2.health = self.fighter2.health
            self.viewport.offset = 0
            self.roundcounter.next_round()
        else:
            self.game_over()

    def check_state(self):
        if self.fighter1.health <= 0:
            self.fighter2.wins += 1
            self.next_round()
        if self.fighter2.health <= 0:
            self.fighter1.wins += 1
            self.next_round()
        

    def main_loop(self):
        while True:
            if self.menu.active:
                self.fighter1.reset()
                self.fighter2.reset()
                self.menu.loop()

            self.clock.tick(30)
            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    self.ev_quit(e)
                elif e.type == pygame.KEYDOWN:
                    self.ev_keydown(e)
                elif e.type == pygame.KEYUP:
                    self.ev_keyup(e)

            self.fighter1.update()
            self.fighter2.update()
            self.surface.fill((0, 0, 0))
            self.world.render(self.surface)
            self.fighter1.render(self.surface)
            self.fighter2.render(self.surface)
            self.pointsbar1.render(self.surface)
            self.pointsbar2.render(self.surface)
            self.injectionsbar1.render(self.surface)
            self.injectionsbar2.render(self.surface)
            self.roundcounter.render(self.surface)
            if not self.ignore_keys and not self.multiplayer:
                self.ai.update()

            for f in self.fireballs:
                f.update()
                f.render(self.surface)

            pygame.display.flip()
Exemple #24
0
class Match():
    def __init__(self, Character1, Character2, arena, roundTime=90, name1="Player1", name2="Player2"):
        ###character 1 and 2 are strings pointing to the assets with the character. will be delivered by the character-selection screen.
        ### till we have the selection screen, hardcode or default them.

        self.arena = loader.loadModel(arena)
        self.arena.reparentTo(render)
        self.arena.setScale(4)
        self.arena.find("**/ground").setCollideMask(BitMask32.bit(1))
        self.arena.find("**/ground").hide()
        self.arena.find("**/out").setCollideMask(BitMask32.bit(1))
        self.arena.find("**/out").hide()
        
        self.player1 = Fighter(Character1, self.roundEnd, 0,  name=name1 )
        self.player2 = Fighter(Character2, self.roundEnd, 1, name=name2 )
        
        self.player1.setOpponent(self.player2)
        self.player2.setOpponent(self.player1)
        self.matchCam =MatchCamera(self.player1.getNP(),self.player2.getNP(),base.camera )
        self.roundTime=roundTime
        self.timer = Timer(self.roundEnd)
        self.messages = AnimatedText()
        self.winner = AnimatedText(pos = (0.0,0.0))
        self.roundStart()
    
    def roundStart(self,task=None):
        self.player1.prepareFighter()
        self.player2.prepareFighter()
        self.timer.setTime(self.roundTime)
        self.timer.start()
        self.messages.splay("Fight!")
        self.roundEnded = False
                
    def roundEnd(self,task=None):
        #TODO: hook in GUI to display apporpriate messages for KO and Draw , player wins , match end etc
        if self.roundEnded:
            return
        else:
            self.roundEnded = True
        self.timer.stop()
        #double ko would require a variable like roundOver.
        #short delay to allow double ko. 
        if self.player1.getHealth()<=0 and self.player2.getHealth() <=0:
            #double knockout.
            self.player1.fighterWin()
            self.player2.fighterWin()
            self.messages.splay("Double K.O.")
            
        elif self.player2.getHealth() > 0 > self.player1.getHealth():
            self.player2.fighterWin()
            self.messages.splay("K.O.")
            #player2 wins by ko
            
        elif self.player2.getHealth() < 0 < self.player1.getHealth():
            self.player1.fighterWin()
            self.messages.splay("K.O.")
            #player1 wins by ko
            
        elif self.player2.getHealth() > self.player1.getHealth() :
            self.player2.fighterWin() 
            self.messages.splay("K.O.")
            #put both an a state where they cant attack each other!!
            
        elif self.player2.getHealth() < self.player1.getHealth() :   
            self.player1.fighterWin() 
            self.messages.splay("K.O.")
            #put both an a state where they cant attack each other!!
             
        else:
            self.player1.fighterWin()
            self.player2.fighterWin() 
            #both players with the same health??? W T F ??
            #put in non-attack-state 
            
        
        
        print self.player1.getWins(),self.player2.getWins()
        if self.player1.getWins() >=3 and self.player2.getWins() >=3:
            #match ended in a draw
            self.winner.splay("Draw!")
            self.endMatch()
            return
        elif self.player1.getWins() >=3:
            #player1 wins
            self.winner.splay("Player 1 wins!")
            self.endMatch()
            return
        elif self.player2.getWins() >=3:
            #player2 wins
            self.winner.splay("Player 2 wins!")
            self.endMatch()
            return
        else:
            pass
        
        taskMgr.doMethodLater(3,self.roundStart,"startRound")
            
        #update the round-wins gui. display guistuff, play win animation on chars, do whatever you like..
        #reset the char healt,reset the positions and fsm states, then let the fun go on.
        #eventually clear the round-end variable.
        #if one player has 3 wins. end match
 
    def endMatch(self):
        self.winner.splay("Match ended!")
        print "match ends!"