当前位置: 首页>>代码示例>>Python>>正文


Python Board.add_piece方法代码示例

本文整理汇总了Python中board.Board.add_piece方法的典型用法代码示例。如果您正苦于以下问题:Python Board.add_piece方法的具体用法?Python Board.add_piece怎么用?Python Board.add_piece使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在board.Board的用法示例。


在下文中一共展示了Board.add_piece方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: random_play

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def random_play():
	random.seed()
	num_games = 20000
	batch_size = 10000
	games = [] #game = (list of board configs, winner)

	current_batch = 0
	for i in tqdm(range(num_games)):
		board = Board()
		boards = [copy.copy(board.board)]

		turn = constants.X_PIECE
		while not board.game_over():
			row, col = random.sample(board.next_moves, 1)[0]
			board.add_piece(row, col, turn)

			turn = (turn + 1) % 2
			boards.append(copy.copy(board.board))

		games.append((boards, board.board_winner()))
		current_batch += 1
		
		if current_batch == batch_size:
			with open('{}-saved_games.pkl'.format(time.time()), 'wb') as f:
				pickle.dump(games, f)
			current_batch = 0
			games = []
开发者ID:jjrob13,项目名称:deep_ultimate_tic_tac_toe,代码行数:29,代码来源:main.py

示例2: test_add_piece_invalid_column

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def test_add_piece_invalid_column():
    """
    Test adding a piece to the board outside of the columns
    """
    test_board = Board()
    assert test_board.can_add_piece(-1) is False and \
           test_board.add_piece(-1, 1) is False
    assert test_board.can_add_piece(test_board.COLUMNS) is False and \
           test_board.add_piece(test_board.COLUMNS, 1) is False
开发者ID:MasterOdin,项目名称:Connect4-AI,代码行数:11,代码来源:board_tester.py

示例3: user_play

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def user_play():
	board = Board()
	turn = constants.X_PIECE
	print board
	while not board.game_over():
		row, col = [int(x) for x in raw_input().split()]
		board.add_piece(row, col, turn)

		turn = (turn + 1) % 2
		print board
开发者ID:jjrob13,项目名称:deep_ultimate_tic_tac_toe,代码行数:12,代码来源:main.py

示例4: test_add_piece

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def test_add_piece():
    """
    Test adding a piece to the board
    """
    test_board = Board()
    test_board.add_piece(0, 2)
    assert test_board.board[0][test_board.ROWS-1] == 2 and \
        test_board.board[0][test_board.ROWS-2] == 0
    test_board.add_piece(0, 1)
    assert test_board.board[0][test_board.ROWS-1] == 2 and \
        test_board.board[0][test_board.ROWS-2] == 1
开发者ID:MasterOdin,项目名称:Connect4-AI,代码行数:13,代码来源:board_tester.py

示例5: test_check_win_column

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def test_check_win_column():
    """
    Test for checking for a connect 4
    """
    test_board = Board()
    i = 0
    while i < 4:
        test_board.add_piece(4, 1)
        i += 1
    assert test_board.check_winner(1)

    test_board.clear_board()
开发者ID:MasterOdin,项目名称:Connect4-AI,代码行数:14,代码来源:board_tester.py

示例6: test_add_piece_full_column

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def test_add_piece_full_column():
    """
    Attempt to add a piece to a full column
    """
    test_board = Board()
    i = 0
    while i < test_board.ROWS:
        assert test_board.can_add_piece(0) is True and \
            test_board.add_piece(0, 1) is True
        i += 1
    assert test_board.can_add_piece(0) is False and \
        test_board.add_piece(0, 1) is False
开发者ID:MasterOdin,项目名称:Connect4-AI,代码行数:14,代码来源:board_tester.py

示例7: test_print_with_few_pieces

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def test_print_with_few_pieces():
    """
    Print the board that contains a few pieces
    """
    test_board = Board()
    test_board.add_piece(0, 2)
    test_board.add_piece(5, 1)
    test_board.add_piece(6, 2)
    out = StringIO()
    test_board.print_board(out=out)
    expected = ("0 "*test_board.COLUMNS+"\n")*(test_board.ROWS-1)
    expected += "2 0 0 0 0 1 2 " + ("0 "*(test_board.COLUMNS-7))+"\n\n"
    assert expected == out.getvalue()
开发者ID:MasterOdin,项目名称:Connect4-AI,代码行数:15,代码来源:board_tester.py

示例8: random_against_model

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def random_against_model(ngames=100):
	from keras.models import model_from_json
	random.seed()
	model = model_from_json(open('keras_model.json').read())
	model.load_weights('model_weights.h5')
	model.compile(optimizer='adam',
		loss='sparse_categorical_crossentropy',
		metrics=['accuracy'])
	outcomes = []
	for _ in xrange(ngames):
		board = Board()

		prev_move = np.zeros(81, dtype='int32')
		turn = constants.X_PIECE
		while not board.game_over():
			if turn == constants.X_PIECE:
				x1 = np.asarray(board.board.flatten())
				x2 = prev_move
				X = np.asarray([np.hstack([x1, x2])])
				probs =  model.predict_proba(X)[0]
				#we need to eliminate any moves that are not allowed
				probs = [p if np.unravel_index(p_i, (9, 9)) in board.next_moves else 0\
					for p_i, p in enumerate(probs)]

				probs = my_normalize(probs)

				idx = range(len(probs))
				#predicted move to make
				move_idx = np.random.choice(idx, p=probs)
				
				row, col = np.unravel_index(move_idx, (9, 9))
				board.add_piece(row, col, turn)
			elif turn == constants.O_PIECE:
				try:
					row, col = random.sample(board.next_moves, 1)[0]
					board.add_piece(row, col, turn)
				except ValueError:
					print 'Try again'
					continue

			else:
				raise ValueError('Mistakes have been made')

			turn = (turn + 1) % 2

		print '{} Won the game!'.format(board.board_winner())
		outcomes.append(board.board_winner())

	print 'AI Won {:0.02f}% of the games!'.format(sum(1 if i == constants.X_PIECE else 0 for i in outcomes)/float(len(outcomes)))
	print '{:0.02f}% ties'.format(sum(1 if i == -1 else 0 for i in outcomes)/float(len(outcomes)))
开发者ID:jjrob13,项目名称:deep_ultimate_tic_tac_toe,代码行数:52,代码来源:main.py

示例9: run_game

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def run_game():
    """
    runs the game :D
    """
    game_board = Board()

    player1 = Human("1")
    player2 = AI("2")
    print(player1, "vs", player2)
    # players_turn = 1

    while not game_board.has_winner:
        col = player1.get_move(game_board)
        game_board.add_piece(col, player1.piece)
        col = player2.get_move(game_board)
        game_board.add_piece(col, player2.piece)
        game_board.print_board()
开发者ID:MasterOdin,项目名称:Connect4-AI,代码行数:19,代码来源:main.py

示例10: play_against_model

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def play_against_model():
	from keras.models import model_from_json
	model = model_from_json(open('keras_model.json').read())
	model.load_weights('model_weights.h5')
	model.compile(optimizer='adam',
		loss='sparse_categorical_crossentropy',
		metrics=['accuracy'])
	board = Board()

	prev_move = np.zeros(81, dtype='int32')
	turn = constants.X_PIECE
	while not board.game_over():
		if turn == constants.X_PIECE:
			x1 = np.asarray(board.board.flatten())
			x2 = prev_move
			X = np.asarray([np.hstack([x1, x2])])
			probs =  model.predict_proba(X)[0]
			#we need to eliminate any moves that are not allowed
			probs = [p if np.unravel_index(p_i, (9, 9)) in board.next_moves else 0\
				for p_i, p in enumerate(probs)]

			probs = my_normalize(probs)

			idx = range(len(probs))
			#predicted move to make
			move_idx = np.random.choice(idx, p=probs)
			
			row, col = np.unravel_index(move_idx, (9, 9))
			board.add_piece(row, col, turn)
		elif turn == constants.O_PIECE:
			print 'Allowed:'
			print board.next_moves
			try:
				row, col = [int(x) for x in raw_input('User move:').split()]
				board.add_piece(row, col, turn)
			except ValueError:
				print 'Try again'
				continue

		else:
			raise ValueError('Mistakes have been made')

		turn = (turn + 1) % 2
		print board

	print '{} Won the game!'.format(board.board_winner())
开发者ID:jjrob13,项目名称:deep_ultimate_tic_tac_toe,代码行数:48,代码来源:main.py

示例11: generate_random_games

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def generate_random_games(num_games, seed=1337):
	random.seed(seed)
	games = []
	for i in tqdm(range(num_games)):
		board = Board()
		boards = [copy.copy(board.board)]

		turn = constants.X_PIECE
		while not board.game_over():
			row, col = random.sample(board.next_moves, 1)[0]
			board.add_piece(row, col, turn)

			turn = (turn + 1) % 2
			boards.append(copy.copy(board.board))

		games.append((boards, board.board_winner()))

	return games
开发者ID:jjrob13,项目名称:deep_ultimate_tic_tac_toe,代码行数:20,代码来源:main.py

示例12: __init__

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
class Game:
    def __init__(self):
        pygame.init()
        
        self.screen = pygame.display.set_mode((600,600))
        
        self.background = pygame.Surface(self.screen.get_size())
        self.background.fill((255,255,255))
        self.background = self.background.convert()

        self.font = pygame.font.Font(None, 30)
        self.game_over_string = ""
        
        self.screen.blit(self.background, (0,0))
        
        self.screen_width = self.screen.get_size()[0]
        self.screen_height = self.screen.get_size()[1]
        
        self.board = Board(7, 7)

        self.game_state = GameState.playing
        
        self.piece_width = 50
        self.piece_height = 50
        self.piece_spacing = 10

        self.cursor_column = 3
        self.cursor_width = 30
        self.cursor_height = 30
        self.cursor_color = (128, 128, 128)
        
    def update(self):
        "Handle input."
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return False
                if self.game_state == GameState.playing:
                    if event.key == pygame.K_LEFT:
                        if self.cursor_column > 0:
                            self.cursor_column -= 1
                    if event.key == pygame.K_RIGHT:
                        if self.cursor_column < 6:
                            self.cursor_column += 1
                    if event.key == pygame.K_SPACE:
                        if self.board.add_piece(self.cursor_column, 1) == True:
                            if self.evaluate_board() == True:
                                ai_move = self.board.get_ai_move()
                                self.board.add_piece(ai_move, 2)
                                self.evaluate_board()
                    
        return True

    def render(self, screen):
        self.screen.fill((255,255,255))
        
        board_width = self.board.columns * (self.piece_width + self.piece_spacing)
        board_height = self.board.rows * (self.piece_height + self.piece_spacing)

        x_start = self.screen_width/2 - board_width/2
        y_start = self.screen_height/2 - board_height/2
        
        for x in range(self.board.columns):
            for y in range(self.board.rows):
                x_position = x_start + x*(self.piece_width+self.piece_spacing)
                y_position = y_start + y*(self.piece_height+self.piece_spacing)
                piece_color = (0,0,0)
                if self.board.matrix.item((y, x)) == 1:
                    piece_color = (255,0,0)
                elif self.board.matrix.item((y, x)) == 2:
                    piece_color = (0,255,0)
                    
                pygame.draw.rect(screen, piece_color, (x_position, y_position, self.piece_width, self.piece_height))

        x_cursor = x_start + self.cursor_column * (self.piece_width + self.piece_spacing) + (self.piece_width - self.cursor_width)/2
        y_cursor = y_start - self.piece_height + (self.piece_height - self.cursor_height)/2
        pygame.draw.rect(screen, self.cursor_color, (x_cursor, y_cursor, self.cursor_width, self.cursor_height))

        if self.game_state == GameState.ended:
            game_over_text = self.font.render(self.game_over_string, 1, (0,0,0))
            text_size = self.font.size(self.game_over_string)
            self.screen.blit(game_over_text, (self.screen_width/2 - text_size[0]/2, 20))

    """
    Evaluates the board. If a player has won or there is a draw,
    print out the result and return false. If play should instead 
    continue, return true.
    """
    def evaluate_board(self):
        evaluation = self.board.evaluate_board()
        if evaluation == 1:
            self.game_over_string = "Red won!"
        elif evaluation == 2:
            self.game_over_string = "Green won!"
        elif evaluation == -1:
            self.game_over_string = "Draw!"
        elif evaluation == 0:
            return True
#.........这里部分代码省略.........
开发者ID:isaacarvestad,项目名称:four-in-a-row,代码行数:103,代码来源:game.py

示例13: Game

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
class Game(object):
    def __init__(self, board,
            players=(Player(Color.WHITE), Player(Color.BLACK))):
        self.moves = []
        self.board = board
        self.players = players
        self.ply = 0

    @property
    def current_player(self):
        """The player whose turn it is."""
        return self.players[self.ply % 2]

    def _make_move(self, move):
        """Apply the given move to the board."""
        #Handle castling
        if type(move.piece) == King:
            dy = move.to[0] - move.start[0]
            if abs(dy) == 2:
                if dy == 2:
                    rook = self.board.piece_at((7, move.to[1]))
                    assert rook is not None, (move.piece, self.board._pieces)
                    self.board.move_piece(rook, (5, move.to[1]))
                else:
                    rook = self.board.piece_at((0, move.to[1]))
                    assert rook is not None, (move.piece, self.board._pieces)
                    self.board.move_piece(rook, (3, move.to[1]))
            move.piece.owner.castling.append((False, False))
        #Remove castling rights on rook moves
        elif type(move.piece) == Rook:
            if move.start[0] == 0:
                move.piece.owner.castling.append(
                        (False, move.piece.owner.castling[-1][1]))
            elif move.start[0] == 7:
                move.piece.owner.castling.append(
                        (move.piece.owner.castling[-1][0], False))
            else:
                move.piece.owner.castling.append(move.piece.owner.castling[-1])
        #Otherwise repeat the last set of castling rights
        else:
            move.piece.owner.castling.append(move.piece.owner.castling[-1])

        # handle en-passant
        if type(move.piece) == Pawn:
            pawn = move.piece
            pawn.just_moved = (pawn.y == pawn.start_rank)

        if move.captured is not None:
            self.board.remove_piece(move.captured)

        self.board.move_piece(move.piece, move.to)

        if move.promotion is not None:
            promoted = move.promotion(move.piece.owner, move.piece.location)
            self.board.remove_piece(move.piece)
            self.board.add_piece(promoted)

        self.moves.append(move)
        self.ply += 1

    def _undo_move(self):
        """Apply the move in reverse to the board."""
        # restore castling rights
        self.ply -= 1
        move = self.moves.pop()

        move.piece.owner.castling.pop()

        # if move was a castle, restore rook position
        if type(move.piece) == King:
            dy = move.to[0] - move.start[0]
            if dy == 2:
                rook = self.board.piece_at((5, move.to[1]))
                self.board.move_piece(rook, (7, move.to[1]))
            elif dy == -2:
                rook = self.board.piece_at((3, move.to[1]))
                self.board.move_piece(rook, (0, move.to[1]))

        # remove promoted piece
        # restore promoting pawn
        if move.promotion is not None:
            promoted = move.promotion(move.piece.owner, move.to)
            self.board.remove_piece(promoted)
            self.board.add_piece(move.piece)

        # restore piece location
        self.board.move_piece(move.piece, move.start)

        # restore captured piece
        if move.captured is not None:
            self.board.add_piece(move.captured)

    def is_legal(self, move):
        """Check if a move is legal.
        A move is legal if
        * a piece can reach the target square
        * an allied piece is not on the target square
        * moving would not place the owner in check."""
        piece = self.board.piece_at(move.to)
        if piece is None or piece.owner != move.piece.owner:
#.........这里部分代码省略.........
开发者ID:Ceasar,项目名称:Chess,代码行数:103,代码来源:game.py

示例14: main

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def main():
    players = white, black = (CPU(Color.WHITE), Human(Color.BLACK))
    white.opponent, black.opponent = black, white
    board = Board()
    for player in players:
        if player.color == Color.WHITE:
            pawn_rank = 1
            piece_rank = 0
        else:
            pawn_rank = 6
            piece_rank = 7
        for x in range(8):
            board.add_piece(Pawn(player, (x, pawn_rank)))
        board.add_piece(Rook(player, (0, piece_rank)))
        board.add_piece(Knight(player, (1, piece_rank)))
        board.add_piece(Bishop(player, (2, piece_rank)))
        board.add_piece(Queen(player, (3, piece_rank)))
        board.add_piece(King(player, (4, piece_rank)))
        board.add_piece(Bishop(player, (5, piece_rank)))
        board.add_piece(Knight(player, (6, piece_rank)))
        board.add_piece(Rook(player, (7, piece_rank)))
    game = Game(board, players)
    game.play()
    return 0
开发者ID:Ceasar,项目名称:Chess,代码行数:26,代码来源:main.py

示例15: trained_model_play

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import add_piece [as 别名]
def trained_model_play():
	"""
	NOTE: The models expect the board to be presented as player X's turn
	
	
	Algo:
	1. Start with 20000 randomly generated games
	2. Train a model to predict "winning" moves
	3. Generate 20000 new games, playing the model against itself
	4. Go to 2
	"""

	BOARD_DIM = 81 #i.e. 9x9
	POSS_MOVE_DIM = 81 #ie. same as board size
	INPUT_DIM = BOARD_DIM + POSS_MOVE_DIM #board, last_move
	OUTPUT_DIM = POSS_MOVE_DIM #which move should we make?

	NB_EPOCH = 5
	NB_ITER = 5 #number of reinforcement learning iterations

	#NOTE: X_PIECE always went first in the training data
	model = Sequential()
	model.add(Dense(2 * INPUT_DIM, input_dim=INPUT_DIM, activation='relu'))
	model.add(Dropout(0.2))
	model.add(Dense(2 * INPUT_DIM, activation='tanh'))
	model.add(Dropout(0.2))
	model.add(Dense(OUTPUT_DIM))
	model.add(Activation('softmax'))
	model.compile(optimizer='adam',
		loss='sparse_categorical_crossentropy',
		metrics=['accuracy'])


	num_games = 20000
	#game = (list of board configs, winner)
	games = generate_random_games(num_games)

	#we only want games with a definitive winner
	won_games = [(g, w) for g, w in games if w != constants.NO_PIECE]
	print 'Using {} games that have winner'.format(len(won_games))

	#we can easily scale up the number of games by transposing them
	won_games.extend(transpose_batch(won_games))

	train_model_on_games(model, won_games, nb_epoch=NB_EPOCH)

	for j in range(NB_ITER):
		games = []
		for i in range(num_games):
			board = Board()
			boards = [board.board]

			prev_move = np.zeros(BOARD_DIM, dtype='int32')
			turn = constants.X_PIECE
			while not board.game_over():
				if turn == constants.X_PIECE:
					x1 = np.asarray(board.board.flatten())
				elif turn == constants.O_PIECE:
					board_rep = invert_board(board.board)
					x1 = np.asarray(board_rep.flatten())
				else:
					raise ValueError('Mistakes have been made')

				x2 = prev_move
				X = np.asarray([np.hstack([x1, x2])])
				probs =  model.predict_proba(X)[0]
				#we need to eliminate any moves that are not allowed
				probs = [p if np.unravel_index(p_i, (9, 9)) in board.next_moves else 0\
					for p_i, p in enumerate(probs)]

				probs = my_normalize(probs)

				idx = range(len(probs))
				#predicted move to make
				move_idx = np.random.choice(idx, p=probs)
				
				row, col = np.unravel_index(move_idx, (9, 9))
				board.add_piece(row, col, turn)
				turn = (turn + 1) % 2
				prev_move = to_categorical([move_idx], 81)[0]

				boards.append(copy.copy(board.board))

			games.append((boards, board.board_winner()))

		won_games = [(g, w) for g, w in games if w != constants.NO_PIECE]
		print 'Using {} games that have winner after reinforcement iter {}'.format(len(won_games), j)
		#we can easily scale up the number of games by transposing them
		won_games.extend(transpose_batch(won_games))
		train_model_on_games(model, won_games, nb_epoch=NB_EPOCH)
	
	with open('keras_model.json', 'w') as f:
		f.write(model.to_json())
	
	model.save_weights('model_weights.h5')
开发者ID:jjrob13,项目名称:deep_ultimate_tic_tac_toe,代码行数:97,代码来源:main.py


注:本文中的board.Board.add_piece方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。