コード例 #1
0
ファイル: life_game.py プロジェクト: Anyue-andy/MOOC_LifeGame
class LifeGame(object):
    """
    Game of life.

    This class controls a game cycle triggered by timer.

    Attributes:
        game_map: GameMap instance.
    """

    def __init__(self, map_rows=10, map_cols=10, life_init_possibility=0.5):
        self.game_map = GameMap(map_rows, map_cols)
        self.game_map.reset(life_init_possibility)

    def print_map(self):
        """Clear the console, then print the map"""
        os.system('cls' if os.name == 'nt' else 'clear')
        self.game_map.print_map()

    def game_cycle(self):
        nc_map = self.game_map.get_neighbor_count_map()
        for row in range(self.game_map.rows):
            for col in range(self.game_map.cols):
                nc = nc_map[row][col]
                if nc < 2 or nc > 3:
                    self.game_map.set(row, col, 0)
                elif nc == 3:
                    self.game_map.set(row, col, 1)
        self.print_map()
コード例 #2
0
ファイル: life_game.py プロジェクト: vunited/MOOC_LifeGame
class LifeGame(object):
    """
    Game of life.

    This class controls a game cycle triggered by timer.

    Attributes:
        game_map: GameMap instance.
    """
    def __init__(self, map_rows=10, map_cols=10, life_init_possibility=0.5):
        self.game_map = GameMap(map_rows, map_cols)
        self.game_map.reset(life_init_possibility)

    def print_map(self):
        """Clear the console, then print the map"""
        os.system('cls' if os.name == 'nt' else 'clear')
        self.game_map.print_map()

    def game_cycle(self):
        nc_map = self.game_map.get_neighbor_count_map()
        for row in range(self.game_map.rows):
            for col in range(self.game_map.cols):
                nc = nc_map[row][col]
                if nc < 2 or nc > 3:
                    self.game_map.set(row, col, 0)
                elif nc == 3:
                    self.game_map.set(row, col, 1)
        self.print_map()
コード例 #3
0
class TestGameMap(TestCase):
    def setUp(self):
        self.gmap = GameMap(4, 3)

    def test_rows(self):
        self.assertEqual(4, self.gmap.rows, "invalid rows")

    def test_cols(self):
        self.assertEqual(3, self.gmap.cols, "invalid cols")

    @patch('random.random',
           new=Mock(side_effect=chain(cycle([0.3, 0.6, 0.9]))))
    def test_reset(self):
        self.gmap.reset()
        for i in range(4):
            self.assertEqual(1, self.gmap.get(i, 0))
            for j in range(1, 3):
                self.assertEqual(0, self.gmap.get(i, j))

    def test_get_set(self):
        self.assertEqual(0, self.gmap.get(0, 0), "invalid value")
        self.gmap.set(0, 0, 1)
        self.assertEqual(1, self.gmap.get(0, 0), "invalid value")

    def test_get_neighbor_count(self):
        expected_value = [[8] * 3] * 4
        self.gmap.cells = [[1] * 3] * 4
        for i in range(4):
            for j in range(3):
                self.assertEqual(expected_value[i][j],
                                 self.gmap.get_neighbor_count(i, j),
                                 '%d,%d' % (i, j))

    @patch('game_map.GameMap.get_neighbor_count', new=Mock(return_value=8))
    def test_get_neighbor_count_map(self):
        expected_value = [[8] * 3] * 4
        self.assertEqual(expected_value, self.gmap.get_neighbor_count_map())

    def test_set_map(self):
        self.assertRaises(TypeError, self.gmap.set_map, {1, 2, 3})
        self.assertRaises(AssertionError, self.gmap.set_map, [[1] * 3] * 3)
        self.assertRaises(TypeError, self.gmap.set_map, [['1'] * 3] * 4)
        self.assertRaises(AssertionError, self.gmap.set_map, [[10] * 3] * 4)

        expected_value = [[1] * 3] * 4
        self.gmap.set_map(expected_value)
        self.assertEqual(expected_value, self.gmap.cells)

    def test_print_map(self):
        self.gmap.cells = [[1, 0, 1], [0, 1, 1], [1, 1, 1], [0, 0, 0]]
        with patch('builtins.print') as mock:
            self.gmap.print_map()
            mock.assert_has_calls(
                [call('1 0 1'),
                 call('0 1 1'),
                 call('1 1 1'),
                 call('0 0 0')])
コード例 #4
0
ファイル: life_game.py プロジェクト: yihong-peng/gamelife
class LifeGame(object):

    def __init__(self, map_rows=10, map_cols=10, life_init_possibility=0.5):
        self.game_map = GameMap(map_rows, map_cols)
        self.game_map.reset(life_init_possibility)

    def print_map(self):
        os.system('cls' if os.name == 'nt' else 'clear')
        self.game_map.print_map()

    def game_cycle(self):
        nc_map = self.game_map.get_neighbor_count_map()
        for row in range(self.game_map.rows):
            for col in range(self.game_map.cols):
                nc = nc_map[row][col]
                if nc < 2 or nc > 3:
                    self.game_map.set(row, col, 0)
                elif nc == 3:
                    self.game_map.set(row, col, 1)
        self.print_map()
コード例 #5
0
ファイル: TestGameMap.py プロジェクト: tangllllllll/gittest
class TestGameMap(TestCase):
    def setUp(self):
        self.game_map = GameMap(4, 3)

    def test_rows(self):
        self.assertEqual(4, self.game_map.rows, "Should get correct rows")

    def test_cols(self):
        self.assertEqual(3, self.game_map.cols, "Should get correct cols")

    @patch('random.random',
           new=Mock(side_effect=chain(cycle([0.3, 0.6, 0.9]))))
    def test_reset(self):
        self.game_map.reset()
        for i in range(0, 4):
            self.assertEqual(1, self.game_map.get(i, 0))
            for j in range(1, 3):
                self.assertEqual(0, self.game_map.get(i, j))

    def test_get_set(self):
        self.assertEqual(0, self.game_map.get(0, 0), "Cells init to zero")
        self.game_map.set(0, 0, 1)
        self.assertEqual(1, self.game_map.get(0, 0),
                         "Should get value set by set")

    def test_get_neighbor_count(self):
        expected_value = [[8] * 3] * 4
        self.game_map.cells = [[1] * 3] * 4
        for i in range(0, 4):
            for j in range(0, 3):
                x = self.game_map.get_neighbor_count(i, j)
                self.assertEqual(expected_value[i][j], x, '(%d,%d)' % (i, j))

    @patch('game_map.GameMap.get_neighbor_count', new=Mock(return_value=8))
    def test_get_neighbor_count_map(self):
        expected_value = [[8] * 3] * 4
        self.assertEqual(expected_value,
                         self.game_map.get_neighbor_count_map())

    def test_set_map(self):
        self.assertRaises(TypeError, self.game_map.set_map, {(0, 0): 1})
        self.assertRaises(AssertionError, self.game_map.set_map, [[1] * 3] * 3)
        self.assertRaises(TypeError, self.game_map.set_map, [['1'] * 3] * 4)
        self.assertRaises(AssertionError, self.game_map.set_map, [[2] * 3] * 4)

        self.game_map.set_map([[1] * 3] * 4)
        self.assertEqual([[1] * 3] * 4, self.game_map.cells)

    def test_print_map(self):
        self.game_map.cells = [[0, 1, 1], [0, 0, 1], [1, 1, 1], [0, 0, 0]]
        with patch('builtins.print') as mock:
            self.game_map.print_map()
            mock.assert_has_calls([
                call('0 1 1'),
                call('0 0 1'),
                call('1 1 1'),
                call('0 0 0'),
            ])
        self.game_map.cells = [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
        with patch('builtins.print') as mock:
            self.game_map.print_map()
            mock.assert_has_calls([
                call('1 1 1'),
                call('1 1 1'),
                call('1 1 1'),
                call('1 1 1'),
            ])
コード例 #6
0
class Game:

    TREASURE_TO_WIN = 3

    def __init__(self):
        self.game_map = GameMap(10)
        self.player = Player("Halk", 3)
        self.enemy = Enemy()

    @decorators.info_decorator
    @decorators.debug_decorator
    def start(self):
        """
        Start Game.

        :returns: None.
        :rtype: None.
        """

        while True:

            debug_status = "Off" if decorators.is_debug else "On"
            info_status = "Off" if decorators.is_info else "On"
            string = input(
                f"Start Game(1)/Load Game(2)/Exit Game(3)/Turn { debug_status } Debug(4)/Turn { info_status } Info(5):"
            )

            if string == '1':

                self.player = Player("Halk", 3)
                self.game_map = GameMap(10)
                custom_log.logger.info("Game Started!")
                self.play()

            elif string == '2':
                game_map = Serializer.load_map()

                if game_map == "":
                    custom_log.logger.error("Failed to Load Game")
                    continue

                custom_log.logger.info("Game Started!")
                self.play()

            elif string == '3':
                break

            elif string == '4':
                decorators.is_debug = not decorators.is_debug

            elif string == '5':
                decorators.is_info = not decorators.is_info

    @decorators.info_decorator
    @decorators.debug_decorator
    def play(self):
        """
        Function where whole game is happening.

        :returns: None.
        :rtype: None.
        """

        stop_flag = Event()

        enemy_thread = EnemyThread(self.enemy, self.player, self.game_map,
                                   stop_flag)
        enemy_thread.start()

        custom_log.logger.info(
            "---------------------------------------------------")

        while True:

            valid_direction = self.game_map.get_player_valid_directions()

            custom_log.logger.info(
                "Input 'save'/'load' to save/load the game.")
            custom_log.logger.info(f"Valid directions - {valid_direction}")

            self.player.check_status(self.game_map)
            self.player.print_status()

            self.game_map.print_map()

            direction = DungeonInput.get_direction()

            if direction == "save":
                Serializer.save_map(self.game_map)
                continue

            elif direction == "load":
                new_game_map = Serializer.load_map()

                if new_game_map == "":
                    custom_log.logger.error("Failed to Load Game")
                    continue

                self.game_map = new_game_map
                continue

            if direction not in valid_direction:
                custom_log.logger.warning("Can't move there!")
                continue

            self.player.move(self.game_map, direction)

            custom_log.logger.info(
                "---------------------------------------------------")

            if self.player.hp <= 0:
                self.end_game()
                break
            elif self.player.bag == Game.TREASURE_TO_WIN:
                self.win_game()
                break

        stop_flag.set()

    @decorators.info_decorator
    @decorators.debug_decorator
    def end_game(self):
        """
        Ends game prints map.

        :returns: None.
        :rtype: None.
        """
        custom_log.logger.info("You Lost!")
        self.game_map.print_map()

    @decorators.info_decorator
    @decorators.debug_decorator
    def win_game(self):
        """
        Wins game prints map.

        :returns: None.
        :rtype: None.
        """
        custom_log.logger.info("You Won!")
        self.game_map.print_map()
コード例 #7
0
ファイル: test_game_map.py プロジェクト: NemoNemo03/N-Stock
class TestGameMap(TestCase):
    def setUp(self):
        self.game_map = GameMap(4, 3)

    def test_init(self):
        self.assertRaises(TypeError, GameMap, ('a', 3))
        self.assertRaises(TypeError, GameMap, (4, 'b'))

    def test_rows(self):
        self.assertEqual(4, self.game_map.rows, "Should get correct rows")

    def test_cols(self):
        self.assertEqual(3, self.game_map.cols, "Should get correct rows")

    @mock.patch('random.random',
                new=mock.Mock(side_effect=chain(cycle([0.3, 0.6, 0.9]))))
    def test_reset(self):
        self.game_map.reset()
        for i in range(0, 4):
            self.assertEqual(1, self.game_map.get(i, 0))
            for j in range(1, 3):
                self.assertEqual(0, self.game_map.get(i, j))
        self.assertRaises(TypeError, self.game_map.reset, possibility='ab')

    def test_get_set(self):
        self.assertEqual(0, self.game_map.get(0, 0), "Cells init to 0")
        self.game_map.set(0, 0, 1)
        self.assertEqual(1, self.game_map.get(0, 0),
                         "Should get value set by set")
        self.assertRaises(TypeError, self.game_map.get, ("d3d3f", 0))
        self.assertRaises(TypeError, self.game_map.get, (0, 'b'))
        self.assertRaises(TypeError, self.game_map.set, ('a', 0, 1))
        self.assertRaises(TypeError, self.game_map.set, (0, 'b', 1))
        self.assertRaises(TypeError, self.game_map.set, (0, 0, 'c'))

    def test_get_neighbor_count(self):
        expected_value = [[8] * 3] * 4
        self.game_map.cells = [[1] * 3] * 4
        for i in range(0, 4):
            for j in range(0, 3):
                self.assertEqual(expected_value[i][j],
                                 self.game_map.get_neighbor_count(i, j),
                                 '(%d %d)' % (i, j))
        self.assertRaises(TypeError, self.game_map.get_neighbor_count,
                          ('a', 0))
        self.assertRaises(TypeError, self.game_map.get_neighbor_count,
                          (0, 'b'))

    @mock.patch('game_map.GameMap.get_neighbor_count',
                new=mock.Mock(return_value=8))
    # game_map.GameMap.get_neighbor_count
    def test_get_neighbor_count_map(self):
        expected_value = [[8] * 3] * 4
        self.assertEqual(expected_value,
                         self.game_map.get_neighbor_count_map())

    def test_set_map(self):
        self.assertRaises(TypeError, self.game_map.set_map, {(0, 0): 1})
        self.assertRaises(AssertionError, self.game_map.set_map, [[1] * 3] * 3)
        self.assertRaises(TypeError, self.game_map.set_map, [['1'] * 3] * 4)
        self.assertRaises(AssertionError, self.game_map.set_map, [[2] * 3] * 4)

        self.game_map.set_map([[1] * 3] * 4)
        self.assertEqual([[1] * 3] * 4, self.game_map.cells)

    def test_print_map(self):
        self.game_map.cells = [[0, 1, 1], [0, 0, 1], [1, 1, 1], [0, 0, 0]]
        with mock.patch('builtins.print') as mock1:
            self.game_map.print_map()
            mock1.assert_has_calls([
                mock.call('0 1 1'),
                mock.call('0 0 1'),
                mock.call('1 1 1'),
                mock.call('0 0 0'),
            ])
コード例 #8
0
ファイル: game.py プロジェクト: gcbounous/python
class Game:
    """Defines a game object. Is the acctual game populated with it's map component objects."""

    def __init__(self, name, text, robot_point = None):
        """
        """
        self._name = name
        self._game_map = GameMap(text, robot_point)
        self._status = globals_.Status.NEW
        self._visible_map = None

    def start(self):
        """
            Method that starts a game, loading the robot if needed.
            It leaves the game ready to be played.
        """
        self._game_map.load_robot()
        if self._visible_map is None:
            self._visible_map = GameMap(robot_point = self._game_map.get_robot_point())
            self._visible_map.append(self._game_map.get_new_room(self._visible_map))

        os.system("setterm -cursor off")
        self._play()
        os.system("setterm -cursor on")

    def get_name(self):
        """
        """
        return self._name

    def get_status(self):
        """
        """
        return self._status

    def get_game_map(self):
        """
        """
        return self._game_map

    def print_map(self, visible_only = True):
        """
            Cleans terminal and prints map
        """
        os.system("clear")
        # os.system("cls") # windows
        if visible_only:
            self._visible_map.print_map()
        else:
            self._game_map.print_map()

    ####  private functions ###
    def _on_key_press(self):
        """
            Method that allows to the input on the key stroke without sowing in the terminal
            Reference:
                - http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
        """
        stdin_file_descriptor = sys.stdin.fileno()
        old_settings = termios.tcgetattr(stdin_file_descriptor)
        try:
            tty.setraw(stdin_file_descriptor)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(stdin_file_descriptor, termios.TCSADRAIN, old_settings)
        return ch

    def _play(self):
        """
            Game loop.
        """
        self._status = globals_.Status.IN_PLAY
        known_door_points = list()

        while True:
            self.print_map()
            self._print_keys()

            move = self._on_key_press()
            # move = raw_input() # windows
            while not self._game_map.move_is_valid(move):
                move = self._on_key_press()
                # move = raw_input() # windows

            if move == globals_.KEYS['QUIT']:
                print 'quit'
                break

            self._game_map.move_robot(move)

            if self._game_map.robot_at_door():
                current_point = self._game_map.get_robot_point()
                current_point = Point(current_point.get_x(),current_point.get_y())
                if current_point not in known_door_points:
                    self._visible_map.append(self._game_map.get_new_room(self._visible_map, move))
                    known_door_points.append(current_point)

            if self._game_map.is_end_of_game():
                self.print_map()
                self._status = globals_.Status.OVER
                print "---- YOU WIN!! ----"
                break

    def _print_keys(self):
        """
            Prints the keys to be used to play
        """
        keys = ""
        for name, k in globals_.KEYS.items():
            if name != 'QUIT':
                keys = "{}\n{}\t-\t[{}]".format(keys, name, k)
        keys = "{}\n{}\t-\t[{}]".format(keys, 'QUIT', globals_.KEYS['QUIT'])

        print keys 

    def __repr__(self):
        """
        """
        return "<Game: name {},\ntext: \n{}>".format(self._name, str(self))

    def __str__(self):
        """
            Tranforms the _game_map into text
        """
        game_text = ""
        robot_point = self._robot.get_point()
        row = 0
        for obj in self._game_map:
            if robot_point is not None and obj.get_point() == robot_point:
                obj = self._robot
            if obj.get_point().get_y() == row + 1:
                game_text = "{}\n".format(game_text)
                row += 1
            game_text = "{}{}".format(game_text, obj.get_symbol())
        return game_text