Ejemplo n.º 1
0
    def startNewGame(self):
        """ Start a new game """
        for i in range(0, Settings.GAME_PLAYERS):
            self.addTeam('team '+str(i+1), Settings.GAME_SNAILS, i)
        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)

        self.gamemode = GameModes.GAME_PLACING_SNAILS
Ejemplo n.º 2
0
class TestTimer(unittest.TestCase):
    """
    A test class for the Timer module.
    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.teams= []
        self.team1 = Team("team1")
        self.team2 = Team("team2")
        pygame.init()
        self.team1.addSnails(2)
        self.team2.addSnails(3)

        self.teams.append(self.team1)
        self.teams.append(self.team2)

        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)

#    def testInitialized(self):
#        """
#        Test if init goes good
#        """
#        self.assertEqual(self.turnManager.teams, self.teams)
#        self.assertEqual(self.turnManager.teams[0], self.team1)
#        self.assertEqual(self.turnManager.teams[1], self.team2)
#
#        self.assertEqual(self.turnManager.status, TurnStatus.BREAK)
#        self.assertEqual(self.turnManager.startTime, Settings.TIMER_STARTTIME)
#        self.assertEqual(self.turnManager.size, Settings.TIMER_SIZE)
#        self.assertEqual(self.turnManager.position, Settings.TIMER_POSITION)
#        self.assertEqual(self.turnManager.font_size, Settings.TIMER_FONT_SIZE)

    def testSingleton(self):
        """
        Test if the singleton works
        """
        turnmanager2 = TurnManager()
        self.assertEqual(id(self.turnManager), id(turnmanager2))
Ejemplo n.º 3
0
class TestWeapon(unittest.TestCase):
    """
    A test class for the Weapon module.
    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """        
        self.turnManager = TurnManager()
        self.teams = []
        
        self.team = Team("Akatsuki")
        self.team.addSnails(1)
        self.teams.append(self.team)
        
        self.turnManager.setTeams(self.teams)
        
        self.snail = None
        for snail in self.team.sprites():
            self.snail = snail
        
        self.weapon = Weapon("Canon", 20)
        self.weapon.ammo = 5
        
        
    def testInitialized(self):
        """
        Test if init goes good
        """
        self.assertEqual(self.weapon.name, "Canon")
        self.assertEqual(self.weapon.power, 20)
        self.assertEqual(self.weapon.ammo, 5)
        
    def testShoot(self):
        self.weapon.shoot()
        self.assertEqual(self.weapon.ammo, 4)
Ejemplo n.º 4
0
    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.teams= []
        self.team1 = Team("team1")
        self.team2 = Team("team2")
        pygame.init()
        self.team1.addSnails(2)
        self.team2.addSnails(3)

        self.teams.append(self.team1)
        self.teams.append(self.team2)

        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)
Ejemplo n.º 5
0
 def setUp(self):
     """
     set up data used in the tests.
     setUp is called before each test function execution.
     """        
     self.turnManager = TurnManager()
     self.teams = []
     
     self.team = Team("Akatsuki")
     self.team.addSnails(1)
     self.teams.append(self.team)
     
     self.turnManager.setTeams(self.teams)
     
     self.snail = None
     for snail in self.team.sprites():
         self.snail = snail
     
     self.weapon = Weapon("Canon", 20)
     self.weapon.ammo = 5
Ejemplo n.º 6
0
 def __init__(self, players):
     self.players = players
     self.relate_opponents(self.players)
     self.turns = TurnManager()
     self.winner = None
Ejemplo n.º 7
0
class Match:
    def __init__(self, players):
        self.players = players
        self.relate_opponents(self.players)
        self.turns = TurnManager()
        self.winner = None

    def start(self, verbose=False):
        for i in range(MAX_TURNS):
            try:
                current_state = self.turns.new_turn(self.players)
                self.display_message(verbose, current_state, 'pre_action')
                actions = self.request_actions(current_state, verbose)
                if verbose:
                    self.action_message(actions, current_state)
                new_state = self.turns.next_state(actions)
                self.update_players(new_state)

            except DeadPlayerException as person:
                final_state = self.turns.current_turn().state_after
                self.display_message(verbose, final_state, 'pre_action')
                # print(f'{person} died.')
                self.winner = self.get_opponent_of(person)
                # print(self.winner,
                #       "wins!\n\n-- Game Over --")
                break
        # self.evaluate_match_in_respect_to(self.get_winner())
        # self.end_by_turn_limit()
        # for player in self.players:
        #     if player.name == self.winner:
        #         for line in self.turns.dump_like_vector(player):
        #             print(line)

    def request_actions(self, state, verbose):
        def request(player, bonus=False):
            fail_safe = 0
            if bonus and verbose:
                print(f"{player.name} have superior \
reflexes and can take a bonus action.")
            while True and fail_safe < 1000:
                try:
                    if isinstance(player, AiPlayer):
                        action_number = player.take_action(
                            self.turn_vector(player))
                    else:
                        action_number = player.take_action()
                    assert (0 < action_number < 7)
                    break
                except (AssertionError, ValueError) as e:
                    fail_safe += 1
                    print("Action has to be an integer between 1 and 6.")
                    print(e)
                    if fail_safe >= 1000:
                        action_number = randint(1, 7)
            return action_number

        number_of_bonus_actions = state['bonus actions']
        actions = [[request(player) for player in self.players]]
        for _ in range(number_of_bonus_actions):
            actions.append([request(self.players[0], bonus=True), 0])
        return actions

    def update_players(self, state):
        for i, player in enumerate(self.players):
            attributes = state['players'][i]
            player.health = attributes['health']
            player.reflex = attributes['reflex']

    def display_message(self, verbose, state, kind):
        if verbose:
            message_callbacks = {
                'pre_action': self.pre_action_message,
                'action': self.action_message,
            }
            print(message_callbacks[kind](state))

    def pre_action_message(self, state):
        message = ['-- Turn {} --'.format(state['turn'])]
        message.extend([
            "{name1}, w({slash1}sl/{thrust1}th):\
 {hp1}hp, {rx1}rx.".format(name1=player['name'],
                           slash1=player['weapon']['slash'],
                           thrust1=player['weapon']['thrust'],
                           hp1=player['health'],
                           rx1=player['reflex']) for player in state['players']
        ])
        message.append('{}\n'.format(self.advantage_message(state)))
        return '\n'.join(message)

    def advantage_message(self, state):
        advantage = state['advantage']
        if advantage['who']:
            return f"{advantage['who']} has {advantage['kind']} advantage."
        else:
            return "No one has advantage."

    def action_message(self, actions, state):
        ACTION_NAMES = [
            'no action', 'offensive movement', 'defensive movement',
            'slash attack', 'thrust attack', 'slash defense', 'thrust defense'
        ]
        for pair in actions:
            for i, action in enumerate(pair):
                print(f"{state['players'][i]['name']} performs",
                      ACTION_NAMES[action])
            print('\n')

    def get_opponent_of(self, player_name):
        try:
            for i, player in enumerate(self.players):
                if player.name is str(player_name):
                    return player.opponent.name
        except (AttributeError, TypeError):
            raise AssertionError('Input variables should be strings')

    def relate_opponents(self, players):
        for i in range(-1, len(players) - 1):
            players[i].opponent = players[i + 1]

    def get_winner(self):
        for player in self.players:
            if player.name == self.winner:
                return player
        return None

    def end_by_turn_limit(self):
        sorted_players = sorted(self.players,
                                key=lambda player: player.health,
                                reverse=True)
        self.winner = sorted_players[0].name

    def turn_vector(self, player):
        big_log = self.turns.dump_like_vector(player)
        vectors, action = zip(*big_log)
        return vectors[-1]

    def evaluate_match_in_respect_to(self, player):
        last_state = self.turns.turn_collection[-1].state_after
        duration_factor = 19 - last_state['turn']
        for individual in last_state['players']:
            if individual['name'] == player.name:
                damage_taken = (individual['health'] / player.starting_health)
        return duration_factor * damage_taken
Ejemplo n.º 8
0
class TestTimer(unittest.TestCase):
    """
    A test class for the Timer module.
    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        pygame.init()
        self.teams= []
        self.team1 = Team("team1")
        self.team2 = Team("team2")

        self.team1.addSnails(3)
        self.team2.addSnails(3)

        self.teams.append(self.team1)
        self.teams.append(self.team2)

        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)

    def testInitialized(self):
        """
        Test if init goes good
        """
        self.assertEqual(self.turnManager.teams, self.teams)
        self.assertEqual(self.turnManager.teams[0], self.team1)
        self.assertEqual(self.turnManager.teams[1], self.team2)

        self.assertEqual(self.turnManager.status, TurnStatus.BREAK)
        self.assertEqual(self.turnManager.startTime, Settings.TIMER_STARTTIME)
        self.assertEqual(self.turnManager.size, Settings.TIMER_SIZE)
        self.assertEqual(self.turnManager.position, Settings.TIMER_POSITION)
        self.assertEqual(self.turnManager.font_size, Settings.TIMER_FONT_SIZE)

    def testSingleton(self):
        """
        Test if the singleton works
        """
        turnmanager2 = TurnManager()
        self.assertEqual(id(self.turnManager), id(turnmanager2))
        self.assertEqual(self.turnManager._instance, turnmanager2._instance)

    def testTimer(self):
        """
        Test if the turnManager's status switches from CurrentTurn to Break when counter is 0
        """
        self.assertEqual(self.turnManager.status, TurnStatus.BREAK)
        #print self.turnManager.started
        self.turnManager.startTimer()

        time.sleep(Settings.TIMER_BREAKTIME + 2)

        self.assertEqual(self.turnManager.status, TurnStatus.CURRENTTURN)

        time.sleep(Settings.TIMER_STARTTIME + 2)
        self.assertEqual(self.turnManager.status, TurnStatus.BREAK)
        self.turnManager.stopTimer()

    def testCurrentTurn(self):
        """
        Test if the turnManager's status switches from Break to CurrentTurn when counter is 0
        """
        self.assertEqual(self.turnManager.status, TurnStatus.BREAK)
        #print self.turnManager.started
        self.turnManager.startTimer()

        time.sleep(Settings.TIMER_BREAKTIME + 1)

        self.assertEqual(self.turnManager.status, TurnStatus.CURRENTTURN)
        self.turnManager.stopTimer()
    
    def testChangeTurn(self):
        self.assertEqual(self.team1.hasTurn, True)
        self.turnManager.changeTurn()
        self.assertEqual(self.team1.hasTurn, False)
        self.assertEqual(self.team2.hasTurn, True)
        se


    def testChangeTurnTeam(self):
        """
        Test if the next time get's the turn
        """
        self.turnManager.startTimer()
        self.assertEqual(self.turnManager.teams[0].hasTurn, True)

        time.sleep(Settings.TIMER_BREAKTIME + Settings.TIMER_STARTTIME + 5)

        self.assertEqual(self.turnManager.teams[0].hasTurn, False)
        self.assertEqual(self.turnManager.teams[1].hasTurn, True)
        self.turnManager.stopTimer()


    def testChangeTurnSnail(self):
        """
        Test if the next snail get's the turn
        """
        a = 1

    def testFirstTurnTeam(self):
        """
        Test if the first team in the team list got the turn when the turnManager starts
        """
        self.turnManager.startTimer()
        time.sleep(2)
        self.assertEqual(self.turnManager.teams[0].hasTurn, True)
        self.assertEqual(self.turnManager.teams[1].hasTurn, False)
        self.turnManager.stopTimer()


    def testFirstTurnSnail(self):
        """
        Test if the first snail of the team who got the turn has the turn
        """
        # the first snail who gets the turn is the first snail of team 1
        firstSnailID = self.turnManager.teams[0].currentSnailTurn
        # the 2nd snail who gets the turn is the first snail of team 2
        secondSnailID = self.turnManager.teams[1].currentSnailTurn

        self.turnManager.startTimer()
        self.assertEqual(self.turnManager.teams[0].hasTurn, True)
        self.assertEqual(self.turnManager.teams[0].currentSnailTurn, firstSnailID)

#        time.sleep(Settings.TIMER_BREAKTIME + Settings.TIMER_STARTTIME + 5)
#
#        self.assertEqual(self.turnManager.teams[0].hasTurn, False)
#        self.assertEqual(self.turnManager.teams[1].hasTurn, True)
#        self.assertEqual(self.turnManager.teams[1].currentSnailTurn, secondSnailID)

        self.turnManager.stopTimer()
Ejemplo n.º 9
0
class Game(Scene):
    """
    This is the game class, this is the most important scene, and keeps track of the whole game
    """
    def __init__(self):
        """ Initializes the game scene """
        self.mainmenu = None
        self.winscreen = None
        self.initEvents()
        self.initTerrain()
        self.initTeams()

        self.createGameObjects()

        self.startNewGame()

    def initEvents(self):
        """ Initializes the eventreader """
        SceneManager().registerEventReader(self.do_action)

    def do_action(self, event):
        """
        Check the events, and do something when needed
        @param event: The event
        """
        
        # check events
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                for snail in TurnManager().currentTeam.orderedSnailList:
                    if snail.hasTurn:
                        snail.shoot()
            if event.key == pygame.K_ESCAPE:
                SceneManager().setScene(self.mainmenu)
    def clean(self):
        """ Clean everything up, so that application doesn't crash """
        self.turnManager.stopTimer()
        SceneManager().unregisterEventReader(self.do_action)

    def initTeams(self):
        """ Initializes the team """
        self.teams = []
        self.teamsAlive = 0

    def initTerrain(self):
        """ Initializes the terrain """
        self.terrain = Terrain()

    def createGameObjects(self):
        """ Create the terrain """
        self.terrain.create(15)

    def addTeam(self, name, numberOfSnails, gravity_direction):
        """
        Add a team to the game
        @param name: The name of the team
        @param numberOfSnails: The amount of snails the team has
        @param gravity_direction: The gravity direction of the team
        """
        team = Team(name)
        team.setGravity(gravity_direction)
        team.addSnails(numberOfSnails)
        team.setTeamImage((gravity_direction+1))
        self.teams.append(team)
        
    def startNewGame(self):
        """ Start a new game """
        for i in range(0, Settings.GAME_PLAYERS):
            self.addTeam('team '+str(i+1), Settings.GAME_SNAILS, i)
        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)

        self.gamemode = GameModes.GAME_PLACING_SNAILS

    def stopGame(self):
        """ Stop the game """
        self.turnManager.timer.cancel()
        teamColors = {1:'green', 2:'red', 3:'yellow', 4:'blue'}
        livingTeamColor = str(teamColors[self.teams[0].colorIndex])
        SceneManager().setScene(WinScreen(self.mainmenu, livingTeamColor))
        #SceneManager().scene = self.mainmenu

    def update(self, input):
        """
        Update the game
        @param input: The input class
        """
        self.terrain.update()
        self.updateTeams(input)

        self.updateGameMode()

    def updateTeams(self, input):
        """
        Update every team
        @param input: The input class
        """
        self.teamsAlive = 0
        for team in self.teams:
            team.update(input, self.terrain)
            self.teamsAlive += 1

    def updateGameMode(self):
        """ Update the gamemodes """
        if self.gamemode == GameModes.GAME_PLACING_SNAILS:
            for team in self.teams:
                for snail in team.sprites():
                    if snail.isPlaced == False:
                        return
            self.turnManager.startTimer()
            self.gamemode = GameModes.GAME_PLAYING
        if self.gamemode == GameModes.GAME_PLAYING:
            if self.teamsAlive <= 1:
                self.stopGame()

    def draw(self, surface):
        """
        Draw the game on a surface
        @param surface: The surface the game should be drawed on
        """
        self.terrain.draw(surface)
        for team in self.teams:
            team.draw(surface)

        #self.bullets.draw(surface)
        if self.gamemode == GameModes.GAME_PLAYING:
            self.turnManager.draw(surface)