示例#1
0
    def create_grid(self, from_position, to_position, field_size):
        from_x, from_y = from_position.as_tuple()
        to_x, to_y = to_position.as_tuple()

        for y in range(from_y, to_y, field_size):
            for x in range(from_x, to_x, field_size):
                self.game_objects.append(Field(x, y, field_size))
示例#2
0
 def move(self, state: Field) -> Tuple[int, int]:
     transformed_field = self._transform_field(state.field)
     while True:
         self._log("eps:", self._params["eps"])
         mode = None
         if np.random.rand() < self._params["eps"]:
             mode = "exploring"
             self._log(mode)
             decision_field = np.random.randint(9)
         else:
             mode = "exploiting"
             self._log(mode)
             decision = self._model.predict(transformed_field)[0]
             self._log("Q's:\n", decision.reshape(3, 3).T)
             decision_field = decision.argmax()
         move = np.unravel_index(decision_field, (3, 3))
         if state.is_valid(*move):
             self._protocol.append({
                 "state": deep_copy(state.field),
                 "action": decision_field,
             })
             return move
         else:
             if mode == "exploiting":
                 self._invalid_moves += 1
             self._train(state.field, decision_field,
                         self._params["invalid_move_reward"])
示例#3
0
    def _events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
            if event.type == pygame.MOUSEBUTTONUP:
                # After game over next click exists game
                if self._game_state != 0:
                    return False

                pos = pygame.mouse.get_pos()

                # Generate real field after first click
                if self._first_time:
                    self.field_map = FieldGenerator(
                        self.field_x, self.field_y, self.mines,
                        (pos[0], pos[1] - self.tile_size)).generate()
                    self.field = Field(self.field_map, self.tile_size)
                    self._first_time = False

                # Open tile (left mouse)
                if event.button == 1:
                    self._open_tile(pos)

                # Place flag (right mouse)
                elif event.button == 3:
                    self._flag(pos)
示例#4
0
 def _train(self, state: Field, action: int, reward: float) -> None:
     if not self._do_train: return
     self._log("reward:", reward)
     self._log("state:\n",
               Field.to_ascii(state, np.unravel_index(action, (3, 3))))
     state = self._transform_field(state)
     target_vec = self._model.predict(state)[0]
     self._log("Q's:\n", target_vec.reshape(3, 3).T)
     target_vec[action] = reward
     self._log("target:\n", target_vec.reshape(3, 3).T)
     self._model.fit(state, np.array([target_vec]), epochs=1, verbose=0)
示例#5
0
    def from_config(cls, config, player_position_generator):
        ball = Ball.from_config(config)
        home_team = Team.from_config(config)
        away_team = Team.from_config(config)
        home_goal = Goal.from_config(config)
        away_goal = Goal.from_config(config)
        away_goal.position = -away_goal.position
        field = Field.from_config(config)
        duration = config["duration"]
        friction = config["friction"]

        return Game(ball, home_team, away_team, home_goal, away_goal, field, duration, friction, player_position_generator)
示例#6
0
    def __init__(self, display, x: int, y: int, mines: int, data: tuple,
                 use_score: bool):
        """Initialize gameloop.

        Args:
            x: Field width in tiles.
            y: Field height in tiles.
            mines: Amount of mines on the field.
            data: Game difficulty and player name for database.
            use_score: Save score after game.
        """
        self.field_x = x
        self.field_y = y
        self.mines = mines
        self.tile_size = 36  # Should always be 36

        # Generate dummy field to show before first click
        self.field_map = FieldGenerator(self.field_x, self.field_y, 0,
                                        (0, 0)).generate()
        self.field = Field(self.field_map, self.tile_size)

        self._game_state = 0  # Game state: -1 Game over, 10 Game won, 0 Game in progress
        self._flagged_mines = 0
        self._flags = mines  # Flags player can use
        self._font = pygame.font.SysFont("Arial", 32)

        # Database for scores
        self._database = sqlite3.connect("src/database/scores.db")
        # Create table for first run
        self._database.execute("""
            CREATE TABLE IF NOT EXISTS scores (
                id INTEGER PRIMARY KEY,
                score INTEGER,
                mode INTEGER,
                name TEXT
            );
            """)
        self._database.commit()
        self._data = data
        self._use_score = use_score

        self._start_time = 0
        self._time = 0
        self._first_time = True
        self._clock = pygame.time.Clock()
        self._display = display
示例#7
0
 def __init__(self, size):
     self._size = size
     self._fields = [x[:] for x in [[Field(None)] * size] * size]
示例#8
0
 def revert_move(self, move):
     self._fields[move.row()][move.column()] = Field(None)
示例#9
0
    def apply_move(self, move, player):
        if self.is_field_used(move.row(), move.column()):
            raise Exception('Invalid move')

        self._fields[move.row()][move.column()] = Field(player)
示例#10
0
 def move(self, field: Field) -> tuple:
     move = (-1, -1)
     while not field.is_valid(*move):
         move = (randint(3), randint(3))
     return move
示例#11
0
 def __init__(self, id: int):
     self.id = id
     self.fields = [
         Field(x, y) for y, x in product(BOARD_SIZE_RANGE, repeat=2)
     ]
示例#12
0
	def __init__(self, x: int, y: int, boardId: int):
		self.field = Field(x, y)
		self.boardId = boardId
示例#13
0
 def setUp(self):
     self.field_map = [[1, 1, 1], [1, -1, 1], [1, 1, 1]]
     self.field = Field(self.field_map, 36)
示例#14
0
 def __init__(self):
     tiles = self.fillTiles()
     field = Field(template=Template(generator=ClassicGenerator()),
                   tilePack=Pack(listGenerator(tiles)))
     Game.__init__(self, field)