コード例 #1
0
    def __init__(self, size):

        self.player = 0
        self.playerA = 'human'
        self.playerB = 'minimax'
        self.depth = 5
        self.useDecisionTree = 1
        self.dynamicDepth = 1
        self.board = GameBoard(size, size, self.playerA, self.playerB,
                               self.depth, self.useDecisionTree,
                               self.dynamicDepth)

        self.bars = {}
        self.width, self.height = self.board.width, self.board.height
        self.board_state_size = (self.width - 1) * self.height * 2

        self.state_to_move = {}
        self.move_to_state = {}

        for dot in cartesian(range(self.width), range(self.height)):
            if dot[0] < self.width - 1:
                move = (dot, right(dot))
                ind = self.__convert_move_to_state(move)
                self.state_to_move[ind] = move
                self.move_to_state[move] = ind
                self.bars[move] = None
            if dot[1] < self.height - 1:
                move = (dot, upper(dot))
                ind = self.__convert_move_to_state(move)
                self.state_to_move[ind] = move
                self.move_to_state[move] = ind
                self.bars[move] = None

        self.board.move_to_state = self.move_to_state
コード例 #2
0
ファイル: game.py プロジェクト: JasonAHeron/connect_four
def run_game(player_one, player_two):
    print 'Starting Game'
    game = GameBoard()
    turn = 0
    while game.winner is None:
        #player one plays even turns
        if turn % 2 == 0:
            current_player = player_one
        #player two plays odd turns
        else:
            current_player = player_two

        # get player input
        print game
        print '   '.join(str(number) for number in range(game.columns))
        column = raw_input('{} which column to place {}? '.format(
            current_player.name,
            current_player.piece
        ))

        # try to insert piece into board, retry turn if failure
        if not game.insert_piece(column, current_player.piece):
            print 'Column either full or invalid, please make another move'
            continue

        turn += 1
    print game
    print '{} wins in {} turns'.format(current_player.name, turn)
コード例 #3
0
def run_game(player_one, player_two):
    print 'Starting Game'
    game = GameBoard()
    turn = 0
    while game.winner is None:
        #player one plays even turns
        if turn % 2 == 0:
            current_player = player_one
        #player two plays odd turns
        else:
            current_player = player_two

        # get player input
        print game
        print '   '.join(str(number) for number in range(game.columns))
        column = raw_input('{} which column to place {}? '.format(
            current_player.name, current_player.piece))

        # try to insert piece into board, retry turn if failure
        if not game.insert_piece(column, current_player.piece):
            print 'Column either full or invalid, please make another move'
            continue

        turn += 1
    print game
    print '{} wins in {} turns'.format(current_player.name, turn)
コード例 #4
0
 def test_find_empty_cell(self):
     game_board = GameBoard()
     game_board.set_cell(1,1)
     game_board.set_cell(2,1)
     cell_list = [1,2,3]
     cell = game_board.get_empty_cell(cell_list)
     print game_board
     self.assertTrue(cell,3)
コード例 #5
0
def _gtest(width, height):
    """A small driver to make sure that the board works.  It's not
    safe to use this test function in production, because it uses
    input()."""
    print("Running _gtest... ")
    board = GameBoard(width, height)
    board.turn = 1
    board.scores = [0, 0]
    gui = GameGUI(board)
コード例 #6
0
    def reset(self):
        size = self.width
        self.board = GameBoard(size, size, self.playerA, self.playerB,
                               self.depth, self.useDecisionTree,
                               self.dynamicDepth)

        self.board.move_to_state = self.move_to_state

        return self.board.board_state
コード例 #7
0
    def __init__(self, armies, level=4, mode=DEFAULT_MODE, game_board=None):
        self._armies = armies

        if game_board is None:
            self._game_board = GameBoard(
                generate_base.generate_random_base_by_level(level=level))
        else:
            self._game_board = game_board

        self._sim = Simulator(self._game_board)
        self._mode = mode
        self.calc_fitness()
コード例 #8
0
def check_long_win(board: GameBoard, i, j):
    #Check if the slot (i,j) corresponds to a win in the horizontal direction
    piece_count = 1
    piece = board.piece
    pointer = j - 1
    while board.valid(i, pointer) and board[i, pointer] == piece:
        piece_count += 1
        pointer -= 1
    pointer = j + 1
    while board.valid(i, pointer) and board[i, pointer] == piece:
        piece_count += 1
        pointer += 1

    #print("LONG:", piece_count)
    return piece_count >= 4
コード例 #9
0
ファイル: logic.py プロジェクト: BTickell/bitTech
def check_long_win(board:GameBoard, i, j):
#Check if the slot (i,j) corresponds to a win in the horizontal direction
	piece_count = 1
	piece = board.piece
	pointer = j - 1
	while board.valid(i, pointer) and board[i, pointer] == piece:
		piece_count += 1
		pointer -= 1
	pointer = j + 1
	while board.valid(i, pointer) and board[i, pointer] == piece:
		piece_count += 1
		pointer += 1

	#print("LONG:", piece_count)
	return piece_count >= 4
コード例 #10
0
def test_vertical_win():
    game = GameBoard()
    game.insert_piece(0, 'X')
    game.insert_piece(0, 'X')
    game.insert_piece(0, 'X')
    assert game.winner is None
    game.insert_piece(0, 'X')
    assert game.winner == 'X'
コード例 #11
0
def test_horizontal_win():
    game = GameBoard()
    game.insert_piece(0, 'X')
    game.insert_piece(1, 'X')
    game.insert_piece(2, 'X')
    assert game.winner is None
    game.insert_piece(3, 'X')
    assert game.winner == 'X'
コード例 #12
0
 def score(self, game_board: board.GameBoard, cpu_turn: bool) -> int:
     if game_board.is_won():
         if cpu_turn:
             return 10
         else:
             return -10
     return 0
コード例 #13
0
ファイル: logic.py プロジェクト: BTickell/bitTech
def check_lat_win (board:GameBoard, i, j):
#Check if the slot (i,j) corresponds to a win in the vertical direction

	piece_count = 1 #keeps track of how many pieces are in a row of the same color, when it reaches 4 the game ends
	piece = board.piece
	pointer = i - 1 #current location
	while board.valid(pointer, j) and board[pointer, j] == piece: #while piece is same color as original and a valid board space
		piece_count += 1
		pointer -= 1
	pointer = i + 1
	while board.valid(pointer, j) and board[pointer, j] == piece:
		piece_count += 1
		pointer += 1

	#print("LAT:", piece_count)
	return piece_count >= 4
コード例 #14
0
ファイル: ttt2.py プロジェクト: mattvears/TicTacToe
	def ListToGameBoard(lst):
		""" convert python list to the GameBoard class """
		boardsize = int(len(lst) ** .5)
		gb = GameBoard()
		gb.board = [[0 for j in range(0, boardsize)] for i in range(0, boardsize)]
	
		row = 0
		col = 0	
		for item in lst:
			gb.board[row][col] = item	
			
			col += 1
			if col >= boardsize:
				col = 0
				row += 1		
		return gb				
コード例 #15
0
def _run(width,
         height,
         playerA,
         playerB,
         depth=3,
         useDecisionTree=True,
         dynamicDepth=False):
    print "Running... "
    board = GameBoard(width, height, playerA, playerB, depth, useDecisionTree,
                      dynamicDepth)
    board.turn = 1
    board.scores = [0, 0]
    try:
        gui = GameGUI(board)
        print "Hello"
    except Exception as e:
        pass
コード例 #16
0
 def test_cell_sum(self):
     game_board = GameBoard()
     self.assertFalse(game_board.check_for_win())
     game_board.set_cell(3,1)
     game_board.set_cell(5,1)
     game_board.set_cell(7,1)
     self.assertTrue(game_board.check_for_win())
コード例 #17
0
class TicTacToe(game.Game):
    def __init__(self, name, players=[]):
        super().__init__(name, players)
        self.board = GameBoard()

    def play_turn(self, player):
        while True:
            self.board.display_board()
            self.board.display_ui_board()
            userinput = input("Choose a letter..\n>>> ")
            if self.board.modify_ui(player.symbol, userinput):
                break
            else:
                print("This place isn't available")

    def play(self):
        assert len(
            self.players) == 2  # Make sure that 2 players are in the list

        players_cycle = cycle(self.players)

        while True:
            current_player = next(players_cycle)
            self.play_turn(current_player)
            win = self.board.check_win()
            if win:
                print("{} won".format(current_player.name))
                break
            full = self.board.check_full_board()
            if full:
                print("Draw")
                break
コード例 #18
0
 def __init__(self, player_1, player_2):
     self.logger = get_logger()
     self.logger.info("Starting game...")
     # Players
     self.player_1 = player_1
     self.player_2 = player_2
     # Boards
     self.logger.info("Creating boards...")
     self.board_1 = GameBoard(player=self.player_1,
                              color=self.PLAYER_1_COLOR)
     self.board_2 = GameBoard(player=self.player_2,
                              color=self.PLAYER_2_COLOR)
     # Set the opponents
     self.logger.info("Assingning opponents...")
     self.player_1.set_opponent_board(self.board_2)
     self.player_2.set_opponent_board(self.board_1)
     self.logger.info('Game started. Start placing ships!')
     self.status = self.GAME_STARTED
コード例 #19
0
def check_lat_win(board: GameBoard, i, j):
    #Check if the slot (i,j) corresponds to a win in the vertical direction

    piece_count = 1  #keeps track of how many pieces are in a row of the same color, when it reaches 4 the game ends
    piece = board.piece
    pointer = i - 1  #current location
    while board.valid(pointer, j) and board[
            pointer,
            j] == piece:  #while piece is same color as original and a valid board space
        piece_count += 1
        pointer -= 1
    pointer = i + 1
    while board.valid(pointer, j) and board[pointer, j] == piece:
        piece_count += 1
        pointer += 1

    #print("LAT:", piece_count)
    return piece_count >= 4
コード例 #20
0
def test_horizontal_win():
    game = GameBoard()
    game.insert_piece(0, 'X')
    game.insert_piece(1, 'X')
    game.insert_piece(2, 'X')
    assert game.winner is None
    game.insert_piece(3, 'X')
    assert game.winner == 'X'
コード例 #21
0
def test_vertical_win():
    game = GameBoard()
    game.insert_piece(0, 'X')
    game.insert_piece(0, 'X')
    game.insert_piece(0, 'X')
    assert game.winner is None
    game.insert_piece(0, 'X')
    assert game.winner == 'X'
コード例 #22
0
    def evaluate(self, num_games=20, max_turn_time=.2):
        """This function will play two neural nets against
        each other num_games times. It returs the ratio in
        which the first player won
        """
        logging.info("== Starting evaluation round ==")
        p1_wins = 0
        for i in range(num_games):
            players = [(self.p1, MCTS(.5)), (self.p2, MCTS(.5))]
            board = GameBoard()

            shuffle(players)
            turn = cycle(players)

            game_start = time.time()

            while not board.game_over():
                player = next(turn)

                start_turn = time.time()
                while (time.time() - start_turn) < max_turn_time:
                    player[1].search(board, player[0])

                pv = player[1].prob_vec(board)
                choose = np.random.choice(len(pv), p=pv)
                board.place_token(choose)

            if player[0] is self.p1:
                p1_wins += 1
                logging.info(
                    f"player 1 wins game {i+1} ({p1_wins} total wins)")
            else:
                logging.info(
                    f"player 2 wins game {i+1} ({i-p1_wins+1} total wins)")
            logging.debug(
                f"game {i} took {time.time()-game_start:.1f}s, {board.total_moves} moves\n{board}"
            )

            if p1_wins / num_games >= 0.55:  # end early if p1 has majority
                return 1
            elif (i - p1_wins + 1) / num_games >= 0.55:
                return 0
        return p1_wins / num_games
コード例 #23
0
ファイル: logic.py プロジェクト: BTickell/bitTech
def check_r_diag(board:GameBoard, i , j):

	piece_count = 1
	piece = board.piece
	lat_p = i + 1
	long_p = j + 1
	while board.valid(lat_p, long_p) and board[lat_p,long_p] == piece:
		piece_count += 1
		lat_p += 1
		long_p += 1
	lat_p = i - 1
	long_p = j - 1
	while board.valid(lat_p, long_p) and board[lat_p,long_p] == piece:
		piece_count += 1
		lat_p -= 1
		long_p -= 1

	#print("RDIAG:", piece_count)
	return piece_count >= 4
コード例 #24
0
    def _newgame(self):
        self.board = GameBoard(self.board.width, self.board.height)
        self.board.turn = 1
        self.board.scores = [0, 0]
        for square in self.squares:
            self.cv.itemconfig(self.squares[square], fill='lightyellow')
        for bar in self.bars:
            self.cv.itemconfig(self.bars[bar], fill='lightgray')

        self.cv.update()
コード例 #25
0
def check_r_diag(board: GameBoard, i, j):

    piece_count = 1
    piece = board.piece
    lat_p = i + 1
    long_p = j + 1
    while board.valid(lat_p, long_p) and board[lat_p, long_p] == piece:
        piece_count += 1
        lat_p += 1
        long_p += 1
    lat_p = i - 1
    long_p = j - 1
    while board.valid(lat_p, long_p) and board[lat_p, long_p] == piece:
        piece_count += 1
        lat_p -= 1
        long_p -= 1

    #print("RDIAG:", piece_count)
    return piece_count >= 4
コード例 #26
0
 def test_cell_sum(self):
     game_board = GameBoard()
     game_board.set_cell(1,1)
     game_board.set_cell(2,3)
     game_board.set_cell(3,5)
     cell_list = [1,2,3]
     self.assertEquals(game_board.sum_cells(cell_list), 9)
コード例 #27
0
    def test_computer_player(self):
        game_board = GameBoard()
        computerplayer = ComputerPlayer("Computer",game_board,1)
        name = computerplayer.name

        # Test name was set
        self.assertEqual(name,"Computer")

        # Test board is instance of GameBoard
        self.assertIsInstance(computerplayer.game_board,GameBoard)
        # Test player (id of 1) has marker value of 4
        self.assertEquals(computerplayer.marker_value, 4)
        # Make the first move
        computerplayer.make_move()
        self.assertFalse(game_board.is_cell_empty(5))
        # Make the another move
        computerplayer.make_move()
        self.assertFalse(game_board.is_cell_empty(1))
        # Make the third move
        computerplayer.make_move()
        self.assertFalse(game_board.is_cell_empty(9))
        self.assertTrue(game_board.check_for_win())
コード例 #28
0
    def test_computer_player(self):
        game_board = GameBoard()
        computerplayer = ComputerPlayer("Computer",game_board,1)
        name = computerplayer.name

        # Set first two cells and should return last cell
        game_board.set_cell(1,4)
        game_board.set_cell(2,4)

        cell_list = [1,2,3]

        cell = computerplayer.get_best_empty_cell(cell_list)
        self.assertEquals(cell,3)

        # Set last two cells and should return first cell
        game_board.set_cell(5,4)
        game_board.set_cell(6,4)

        cell_list = [4,5,6]

        cell = computerplayer.get_best_empty_cell(cell_list)
        self.assertEquals(cell,4)
コード例 #29
0
ファイル: dojo.py プロジェクト: pweids/ConnectZero
    def __init__(self, board=None, nnet=None, mcts=None, batch_size=10):
        """Pass the baord class (defaults to GameBoard), the neural net instance
        and the MCTS instance
        """
        logging.basicConfig(filename="dojo.log", level=logging.DEBUG,
            filemode='w')

        self.board = board or GameBoard()
        self.nnet = nnet or neural_net.NeuralNet()
        self.tree = mcts or MCTS(3)

        self.training_examples = []
        self.batch_size = batch_size
コード例 #30
0
 def resetGame(self):  #Reset Game (could probably do this more graciously)
     self.ATT_CAPTURED = 0
     self.DEF_CAPTURED = 0
     self.att_reward_total = 0
     self.def_reward_total = 0
     self.captured = []
     self.done = False
     self._board = GameBoard()
     self.action_space = []
     self._turns = 0
     self._state = Const.ATT_TURN
     self.action_space = self.newMovements(Const.ATT_SIDE_MARK)
     self.n_actions = len(self.action_space)
コード例 #31
0
def _runStats(width,
              height,
              playerA,
              playerB,
              depth=3,
              useDecisionTree=True,
              dynamicDepth=False):
    line = "%d, %d, %s, %s, %d, %d, %d\n" % (
        width, height, playerA, playerB, depth, useDecisionTree, dynamicDepth)
    writeToStats(line, useDecisionTree)

    start = time.clock()
    board = GameBoard(width, height, playerA, playerB, depth, useDecisionTree,
                      dynamicDepth)
    board.turn = 1
    board.scores = [0, 0]
    try:
        gui = GameGUI(board)
    except Exception as e:
        pass
    end = time.clock()
    line = "%f\n\n" % (end - start)
    writeToStats(line, useDecisionTree)
コード例 #32
0
    def __init__(self, level=4, mode=DEFAULT_MODE, game_board=None):
        self._army, titles = generate_army.generate_army_by_level(
            townhall_level=level)

        if game_board is None:
            self._game_board = GameBoard(
                generate_base.generate_base_by_level(level))
        else:
            self._game_board = game_board

        self._sim = Simulator(self._game_board)
        self._fit = 0
        self._mode = mode

        # calculate fitness once when created
        self.calc_fitness()
コード例 #33
0
	def __init__(self):
		self.logger = logger.create_logger('Controller')
		self.load_config(CONFIG_FILE)
		self.board = GameBoard(self.width, self.height)
		self.running = False
		self.paused = False
		self.visibility = random.randint(self.minvisibility, self.maxvisibility)
		
		# Put some trees on the board
		num_trees = random.randint(self.mintrees*self.width*self.height,
		                           self.maxtrees*self.width*self.height)

		for i in xrange(num_trees):
			x = random.randint(0, self.width - 1)
			y = random.randint(0, self.height - 1)

			if not self.board.get_object((x, y)):
				self.board.add_object(Tree(self.board, (x, y)))
コード例 #34
0
ファイル: application.py プロジェクト: Nachtfeuer/five-wins
    def __init__(self):
        """Initializing the application."""
        self.master = tk.Tk()
        self.master.title("Five Wins Game")
        self.master.geometry("800x600+50+50")
        self.master.config(bg="dodger blue")
        self.master.attributes("-alpha", 0.9)

        self.menubar = tk.Menu(self.master)

        file_menu = tk.Menu(self.menubar, tearoff=0)
        file_menu.add_command(label="Quit", command=self.quit_application)
        self.menubar.add_cascade(label="File", menu=file_menu)

        self.main_window = MainWindow(self.master)
        self.main_window.add(GameBoard(self.main_window), text="Game Board")

        self.master.config(menu=self.menubar)
コード例 #35
0
    def __init__(self):
        super(Tablut, self).__init__()
        self.att_reward_total = 0  #Following variable are used in printStats()
        self.def_reward_total = 0
        self.ATT_WIN_COUNT = 0
        self.DEF_WIN_COUNT = 0
        self.DEF_CAPTURED = 0
        self.ATT_CAPTURED = 0
        self._turns = 0
        self._state = Const.ATT_TURN  #See rule #3 of game rules
        self.done = False  #Used to stop game

        self.captured = []  #Keep track of captured pieces

        self._board = GameBoard()  #Instantiate board
        self.action_space = self.newMovements(
            Const.ATT_SIDE_MARK)  #Holds all possible moves for either side

        self.n_actions = len(
            self.action_space)  #Used for QLearningTable algorithm
コード例 #36
0
    def minimax(self, game_board: board.GameBoard, cpu_turn: bool,
                player_x_turn: bool) -> int:
        # If the game is over return the score
        s = self.score(game_board, cpu_turn)
        if s != 0:
            return s

        # Create the list of scores of all further possible moves
        scores = list()
        moves = game_board.available_moves()

        # Check for no available moves left, in which case tie
        if len(moves) == 0:
            return 0

        # Parity the turn
        player_x_turn = not player_x_turn

        # Get the score of each possible move
        for move in moves:
            trial_board: board.GameBoard = copy.deepcopy(game_board)

            # Determine the value of the play
            if player_x_turn:
                val = board.TTTValue.X
            else:
                val = board.TTTValue.O

            trial_board.make_move(move, val)

            # Find the minimax score of this new move
            scores.append(
                self.minimax(trial_board, not cpu_turn, player_x_turn))

        # Do the minimax calculation
        if not cpu_turn:
            return max(scores)
        else:
            return min(scores)
コード例 #37
0
 def test_marker_valuet(self):
     game_board = GameBoard()
     self.assertEquals(game_board.get_marker_value_by_id(1),4)
コード例 #38
0
def test_diagonal_win():
    game = GameBoard()
    game.insert_piece(0, 'X')
    game.insert_piece(1, 'Y')
    game.insert_piece(1, 'X')
    game.insert_piece(2, 'Y')
    game.insert_piece(2, 'Y')
    game.insert_piece(2, 'X')
    game.insert_piece(3, 'Y')
    game.insert_piece(3, 'Y')
    game.insert_piece(3, 'Y')
    assert game.winner is None
    game.insert_piece(3, 'X')
    assert game.winner == 'X'
コード例 #39
0
def run_simulation():
    print 'Game Start'
    game = GameBoard()
    game.insert_piece(0,'X')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
    game.insert_piece(1, 'Y')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
    game.insert_piece(0,'X')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
    game.insert_piece(2, 'Y')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
    game.insert_piece(0,'X')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
    game.insert_piece(2, 'Y')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
    game.insert_piece(0,'X')
    print game
    print '#'* 10, 'winner: {}'.format(game.winner), '#'* 10
コード例 #40
0
def test_insert_piece_failure():
    # ensure incorrectly inserting piece results in failure return
    game = GameBoard()
    assert game.insert_piece('test', 'X') is False
コード例 #41
0
from board import GameBoard
from players import Human_Player, AI_Player
import time

players = []
size = 11
depth = 2
Reverse = False
for i in range(len(sys.argv)):
    if sys.argv[i] == ‘-l’
       Reverse = True
    if sys.argv[i] == ‘-n’
       size = int(sys.argv[i+1])
end

board = GameBoard(size)
if not Reverse:
    players.append(Human_Player("human", board, 0, depth))
    players.append(AI_Player("COM", board, 1, depth))
else:
    players.append(Human_Player("COM", board, 0, depth))
    players.append(AI_Player("human", board, 1, depth))
        

playing = True
while playing:
#    print "\nMATCH: %s vs %s." % (players[0].get_name(), players[1].get_name())
    print board
    moves = 0
    current_player_id = 0
    active_turn = True
コード例 #42
0
 def test_get_cell(self):
     game_board = GameBoard()
     game_board.set_cell(3,1)
     self.assertEquals(game_board.get_cell(3), 1)
コード例 #43
0
 def test_is_empty(self):
     game_board = GameBoard()
     self.assertTrue(game_board.is_cell_empty(1))
コード例 #44
0
def test_insert_piece_success():
    # ensure correctly inserting piece results in successful return
    game = GameBoard()
    assert game.insert_piece(0, 'X') is True
コード例 #45
0
def test_insert_piece_failure():
    # ensure incorrectly inserting piece results in failure return
    game = GameBoard()
    assert game.insert_piece('test', 'X') is False
コード例 #46
0
def test_bad_int_entry():
    # ensure board state remains unchanged upon bad int entry
    game = GameBoard()
    empty_board = str(game)
    game.insert_piece(12315, 'X')
    assert str(game) == empty_board
コード例 #47
0
def test_good_string_entry():
    # ensure board state changes upon correct string entry
    game = GameBoard()
    empty_board = str(game)
    game.insert_piece('0', 'X')
    assert str(game) != empty_board
コード例 #48
0
def test_good_string_entry():
    # ensure board state changes upon correct string entry
    game = GameBoard()
    empty_board = str(game)
    game.insert_piece('0', 'X')
    assert str(game) != empty_board
コード例 #49
0
def test_insert_piece_success():
    # ensure correctly inserting piece results in successful return
    game = GameBoard()
    assert game.insert_piece(0, 'X') is True
コード例 #50
0
class Controller(object):
	logger = None
	board = None
	running = None
	paused = None
	width = None
	height = None
	minvisibility = None
	maxvisibility = None
	mintrees = None
	maxtrees = None
	visibility = None
	snapshot_file = None

	def __init__(self):
		self.logger = logger.create_logger('Controller')
		self.load_config(CONFIG_FILE)
		self.board = GameBoard(self.width, self.height)
		self.running = False
		self.paused = False
		self.visibility = random.randint(self.minvisibility, self.maxvisibility)
		
		# Put some trees on the board
		num_trees = random.randint(self.mintrees*self.width*self.height,
		                           self.maxtrees*self.width*self.height)

		for i in xrange(num_trees):
			x = random.randint(0, self.width - 1)
			y = random.randint(0, self.height - 1)

			if not self.board.get_object((x, y)):
				self.board.add_object(Tree(self.board, (x, y)))

	def load_config(self, filename):
		self.logger.info("Loading game configuration...")
		config = ConfigParser.ConfigParser()
		config.read(filename)

		self.snapshot_file = config.get("Server", "Snapshot")

		self.width = int(config.get("GameBoard", "Width"))
		self.height = int(config.get("GameBoard", "Height"))
		self.minvisibility = int(config.get("Player", "MinVisibility"))
		self.maxvisibility = int(config.get("Player", "MaxVisibility"))
		self.mintrees = float(config.get("GameBoard", "MinTrees"))
		self.maxtrees = float(config.get("GameBoard", "MaxTrees"))

		self.snowball_speed = int(config.get("Snowball", "Speed"))
		snowball.SPEED = self.snowball_speed

		self.logger.info("Min Visibility: " + str(self.minvisibility))
		self.logger.info("Max Visibility: " + str(self.maxvisibility))
		self.logger.info("Game Height: " + str(self.height))
		self.logger.info("Game Width: " + str(self.width))

	def create_player(self, username, connection):
		x = random.randint(0, self.width - 1)
		y = random.randint(0, self.height - 1)

		while self.board.get_object((x, y)):
			x = random.randint(0, self.width - 1)
			y = random.randint(0, self.height - 1)

		player = Player(username, connection, self.board, (x,y))
		return player

	def add_player(self, newPlayer):
		# check to see if player already exists
		if self.get_player(newPlayer.username):
			raise Exception('Player', 'Already exists')

		#add player to game
		self.board.add_object(newPlayer)

	def remove_player(self, player):
		self.board.remove_object(player)

	def get_player(self, name):
		for player in self.board.players:
			if player.username == name:
				return player

		return None

	def run(self):
		if(self.paused):
			self.logger.debug("Resuming game")
			self.paused = False
		else:
			self.logger.debug("Starting game")

		self.running = True
		snapshot_counter = 0

		while self.running and not self.paused and len(self.board.players) > 0 :
			self.step()
			time.sleep(0.5)
			
			snapshot_counter += 1
			if snapshot_counter == 10:
				snapshot_counter = 0
				file = open(self.snapshot_file, 'w')
				file.write(str(self.board))
				file.close()

		if self.running:
			self.logger.debug("Pausing game")
		else:
			# close the game
			self.logger.debug("Stopping game")
			#while len(self.board.players):
			#	self.board.players[0].disconnect()
			#	del self.board.players[0]

			self.board.clear()

		self.running = False

	def step(self):
		nextMoves = {}
		self.logger.debug("Getting players' moves")

		# for each player, create their visible map and ask for a move
		for player in self.board.players:
			if not player.connection.running:
				continue

			player.increment_steps()
			board = self.board.get_visible_board(player.coordinates, self.visibility)
			player.request_move(board)

		# wait for all of the players to respond (or timeout)
		for player in self.board.players:
			if player.connection.getting_move:
				player.connection.move_join()

			move = player.get_next_position(nextMoves)
			try:
				player.perform_action()
			except Exception as e:
				self.logger.info(e)
			#print move
			if move in nextMoves:
				nextMoves[move].append(player)
			else:
				nextMoves[move] = [player]

		# populate the nextMoves list with static objects
		for obj in self.board.staticObjects:
			if obj.coordinates in nextMoves:
				nextMoves[obj.coordinates].append(obj)
			else:
				nextMoves[obj.coordinates] = [obj]

		# populate the nextMoves list with dynamic objects
		for obj in self.board.dynamicObjects:
			move = obj.get_next_position(nextMoves)
			if move in nextMoves:
				nextMoves[move].append(obj)
			else:
				nextMoves[move] = [obj]


		# check for collisions and handle them
		for loc,lst in nextMoves.items():
			if len(lst) > 1:
				# if there are more than one object at that location
				for obj in lst:
					# loop through each of the objects and
					# have the dynamic ones handle the collision
					if(isinstance(obj, DynamicObject)):
						others = nextMoves[loc][:]
						others.remove(obj)
						obj.handle_collision(others)


		# apply all of the moves to the objects
		self.logger.debug("Applying moves")
		for obj in self.board.dynamicObjects:
			try:
				self.board.move_object(obj, obj.get_next_position(nextMoves))
			except Exception as e:
				self.logger.info(e)
		for player in self.board.players:
			if not self.board.move_object(player, player.get_next_position(nextMoves)):
				# if the player could not move (moved off game board)
				player.increment_deaths()

		#print self.board

	def pause(self):
		self.paused = True

	def resume(self):
		self.start()

	def stop(self):
		self.running = False

	def start(self):
		t = Thread(group = None, target = self.run)
		t.start()

	'''def reload_config(self):
コード例 #51
0
 def test_get_cell_offset(self):
     game_board = GameBoard()
     self.assertEquals(game_board.get_cell_offset(1,1), 1)
     self.assertEquals(game_board.get_cell_offset(3,3), 9)
     self.assertEquals(game_board.get_cell_offset(4,4), -1)
コード例 #52
0
ファイル: round.py プロジェクト: CorySpitzer/tron-engine
              name1="Contestant 1", name2="Contestant 2", 
              verbose=False, interactive=False, ansi=False, replay=False,
              **kwargs):
    delay = 1.0/FPS

    try:
        p1 = Player(cmd1, name1)
    except Exception, e:
        raise PlayerFailedException(name1, "Couldn't start process: "+str(e))

    try:
        p2 = Player(cmd2, name2)
    except Exception, e:
        raise PlayerFailedException(name2, "Couldn't start process: "+str(e))
    
    gameboard = GameBoard(board)

    if replay:
        replayfile = get_replayfile(replay)
        replayfile.write("+OK|{} {}|".format(gameboard.width, gameboard.height))
        for line in gameboard.board:
            replayfile.write(''.join(line).translate(P1BOARD))
            replayfile.write('\n')
        replayfile.write("|{}|{}|".format(name1, name2))

    result = None
    exception1 = None
    exception2 = None
    try:
        while True:
            if verbose:
コード例 #53
0
class BoardGenetics:
    MAXIMIZE_FITNESS = False
    DEFAULT_MODE = DESTORYER
    """
    This class manages all of the functions necessery in order to run GA.
    """
    def __init__(self, armies, level=4, mode=DEFAULT_MODE, game_board=None):
        self._armies = armies

        if game_board is None:
            self._game_board = GameBoard(
                generate_base.generate_random_base_by_level(level=level))
        else:
            self._game_board = game_board

        self._sim = Simulator(self._game_board)
        self._mode = mode
        self.calc_fitness()

    def get_gb(self):
        return self._game_board

    def set_armies(self, armies):
        self._armies = armies

    def minimize_fitness(self):
        return True

    def run(self, army):
        return self._sim.run(army)

    """
    Our fitness function, currently linear.
    """

    def calc_fitness(self):
        self._fit = 0
        try:
            for army in self._armies:
                outcome = self.run(army)

                # calculate fitness
                if self._mode == REGULAR:
                    self._fit += 2 * outcome["percent"] + 0.3 * outcome[
                        "stars"] + outcome["gold"] + outcome["elixir"]
                elif self._mode == DESTORYER:
                    self._fit += 2 * outcome["percent"] + 0.3 * outcome["stars"]
                elif self._mode == GOLD_DIGGER:
                    self._fit += outcome["gold"]
                elif self._mode == ELIXIR_LOVER:
                    self._fit += outcome["elixir"]
                elif self._mode == GOLD_DIGGER:
                    self._fit += outcome["gold"] + outcome["elixir"]

        except Exception as e:
            print(e)
            self._fit = 0
        self._fit /= len(self._armies)
        print(self._fit)

    def get_fitness(self):
        return self._fit

    def viz(self, index, viz_mode=True):
        if viz_mode:
            path = SAVE_FOLDER + "%04d.png" % index
            board_viz.viz_board(game_board=self._game_board,
                                army=self._armies[0],
                                path=path)
            self._game_board.update_viz()

    """
    Our mutation function.
    """

    def mutation(self, only_second=False):
        if not only_second:
            for i in range(random.randint(1, 5)):
                self.mutation_step_1()
        for i in range(random.randint(1, 2)):
            self.mutation_step_2()
        self.calc_fitness()

    # Swaps 2 random buildings of size 3
    def mutation_step_2(self):
        buildings = self._game_board.get_buildings()
        buildings = [b for b in buildings if b.get_size() == 3]
        i1, i2 = random.randint(0,
                                len(buildings) - 1), random.randint(
                                    0,
                                    len(buildings) - 1)

        x, y = buildings[i1].get_pos()
        buildings[i1].set_pos(buildings[i2].get_pos())
        buildings[i2].set_pos((x, y))

    def mutation_step_1(self):
        # getting buildings and buildings that are not empty
        buildings = self._game_board.get_buildings()

        # running through all the non empty buildings and try to replace them
        # with other buildings in the same size (including emptys)
        index = random.randint(3, len(buildings) - 1)
        building = buildings[index]

        # try swapping the building
        moved = False
        i = 0
        while i < 20:
            i += 1
            x, y = util.gen_board_location(BOARD_SIZE - building.get_size() +
                                           1)
            g = Building(pos=(x, y), size=building.get_size())

            # check for building at that location
            has_overlap = any([
                b.overlap(g) for b in buildings[:index] + buildings[index + 1:]
            ])

            # if building exists
            if not has_overlap:
                # swap between buildings if are the same size
                building.set_pos((x, y))
                break
コード例 #54
0
class Display:  # 棋盘显示程序
    def __init__(self, board=None, pipe=None, mode=None):
        global ori_board
        if board is None:
            self.game_board = GameBoard()
        else:
            self.game_board = board
        self.s = pipe
        self.turn = 1
        self.win = tk.Tk()
        ###
        if pipe is None:
            self.win.title("Surakarta")
        else:
            self.win.title(self_user_name)
        ###
        self.buffer = []
        ori_board = cv2.imread('resources/pictures/board.jpeg')
        ori_board = ori_board[..., ::-1]
        ori_board = cv2.resize(ori_board, (600, 600),
                               interpolation=cv2.INTER_NEAREST)
        ori_board = ImageTk.PhotoImage(Image.fromarray(ori_board))
        self.board_frame = tk.Frame(self.win)
        self.control_panel = tk.Frame(self.win,
                                      bg='WHITE',
                                      bd=0,
                                      height=600,
                                      width=200)
        self.display_canvas = tk.Canvas(self.board_frame,
                                        bg='WHITE',
                                        bd=0,
                                        heigh=600,
                                        width=600)
        self.display_canvas.create_image(0, 0, anchor='nw', image=ori_board)
        self.r = 15
        self.a = None
        self.b = None
        self.x = None
        self.y = None
        self.p = None
        self.history = []
        self.mode = mode
        self.display_posi = []
        self.my_turn_flag = None
        for i in range(15):
            line_display_posi = []  # 初始化 显示位置矩阵
            for j in range(15):
                x = 39.2 * j + 25
                y = 39.2 * i + 25
                line_display_posi.append(Position(x, y))
            self.display_posi.append(line_display_posi)
        if self.s is not None:
            while self.my_turn_flag is None:
                try:
                    print('try receiving1')
                    info = self.receive()
                    print(info)
                    info = info.split('.')
                    if info[1] == 'first':
                        self.my_turn_flag = True
                        t = Thread(target=self.receive_position)
                        t.start()
                    elif info[1] == 'second':
                        self.my_turn_flag = False
                        t = Thread(target=self.receive_position)
                        t.start()
                except IndexError:
                    pass

    def receive_position(self):
        while True:

            if self.my_turn_flag is False:
                print('receiving')
                if self.buffer == ['']:
                    self.buffer.pop()
                if self.buffer:
                    print('info', self.buffer)
                    ######
                    # if info=='quit.':
                    #     endbattle=1;
                    ######
                    info = self.buffer.pop(0)
                    info = info.split('.')[1].split(',')
                    self.game_board.make_move(
                        [int(info[0]), int(info[1])], self.turn)
                    self.display_chess(self.game_board)
                    self.turn = -self.turn
                    self.change_turn()
                else:
                    info = self.s.recv(1024).decode('utf-8')

                    if info == 'quit.':
                        # self.win.destroy()
                        self.win.quit()
                        a = quit_ui()

                    info = info.split('#')
                    for info_ in info:
                        self.buffer.append(info_)
                    info = self.buffer.pop(0)
                    info = info.split('.')[1].split(',')

                    self.game_board.make_move(
                        [int(info[0]), int(info[1])], self.turn)
                    self.display_chess(self.game_board)
                    self.turn = -self.turn
                    self.change_turn()

    def change_turn(self):
        if self.my_turn_flag:
            self.my_turn_flag = False
        else:
            self.my_turn_flag = True

    def receive(self):
        if self.buffer:
            info = self.buffer.pop(0)
            print('return', info)
            return info
        else:
            info = self.s.recv(1024).decode('utf-8')
            info = info.split('#')
            for info_ in info:
                self.buffer.append(info_)
            info = self.buffer.pop(0)
            print('return', info)
            return info

    def display_chess(self, game_board):  # 显示棋子函数
        self.display_canvas.delete("chess")
        for i in range(15):  # 遍历棋盘
            for j in range(15):
                if game_board.board[i][
                        j] == WHITE_CHESS:  # 如果是白棋,则跟觉显示矩阵和半径,绘制白棋
                    self.display_canvas.create_oval(
                        self.display_posi[i][j].x - self.r,
                        self.display_posi[i][j].y - self.r,
                        self.display_posi[i][j].x + self.r,
                        self.display_posi[i][j].y + self.r,
                        fill='GhostWhite',
                        tag='chess')
                elif game_board.board[i][
                        j] == BLACK_CHESS:  # 如果是黑棋,则跟觉显示矩阵和半径,绘制黑棋
                    self.display_canvas.create_oval(
                        self.display_posi[i][j].x - self.r,
                        self.display_posi[i][j].y - self.r,
                        self.display_posi[i][j].x + self.r,
                        self.display_posi[i][j].y + self.r,
                        fill='Black',
                        tag='chess')
        self.win.update()
        if game_board.judge() is not None:
            poi = game_board.judge()
            if game_board.board[poi[0]][poi[1]] == BLACK_CHESS:
                messagebox.showinfo('Game End', 'The Game is End!BLACK WIN!')
                self.win.quit()
            if game_board.board[poi[0]][poi[1]] == WHITE_CHESS:
                messagebox.showinfo('Game End', 'The Game is End!WHITE WIN!')
                self.win.quit()
            # messagebox.showinfo('Game End', 'The Game is End!')
            # self.win.quit()

    def place_chess(self, event):  # 点击,放置棋子
        if self.my_turn_flag or self.s is None:
            for row_index in range(15):  # 遍历棋盘
                for col_index in range(15):
                    if self.display_posi[row_index][col_index].x - self.r < event.x < self.display_posi[row_index][
                        col_index].x + self.r and self.display_posi[row_index][col_index].y - self.r < event.y < \
                            self.display_posi[row_index][col_index].y + self.r:  # 如果鼠标的点击范围在棋子的附近内
                        if self.game_board.board[row_index][
                                col_index] == NO_CHESS:  # 如果当前位置棋盘为空,则可以放置棋子
                            self.game_board.make_move([row_index, col_index],
                                                      self.turn, self.history)
                            self.turn = -self.turn
                            self.display_chess(self.game_board)
                            if self.s is not None:
                                print('position.' + str(row_index) + ',' +
                                      str(col_index))
                                self.s.send(
                                    bytes(
                                        'position.' + str(row_index) + ',' +
                                        str(col_index), 'utf-8'))
                                self.change_turn()
                            if self.mode is not None:
                                # ai = SearchEngine(self.game_board, self.turn)
                                ai = AlphaBeta(self.game_board, self.turn)
                                move = ai.search()
                                self.game_board.make_move([move[0], move[1]],
                                                          self.turn,
                                                          self.history)
                                self.turn = -self.turn
                                self.display_chess(self.game_board)
                            return

    def check_play_legal(self):
        if self.a != self.x or self.b != self.y:
            return True
        return False

    ###
    def quit(self, event):
        if self.s is not None:
            self.s.send(bytes('quit.', 'utf-8'))
            self.s.close()
        # self.win.destroy()

    ###
    def display(self):
        # self.display_chess(self.game_board)
        self.board_frame.pack(side=tk.LEFT)
        # self.control_panel.pack(side=tk.RIGHT)
        self.display_canvas.pack()
        self.win.bind("<Button-1>", self.place_chess)
        self.win.bind('<Tab>', self.quit)
        self.win.bind("<Return>", self.retract)

        self.win.mainloop()

    def retract(self, event):  # 撤销棋子函数
        print('enr')
        if self.s is None:
            move = self.history.pop()  # history 中储存了历史放置棋子队列,根据历史信息回退
            self.game_board.board[move[0]][move[1]] = NO_CHESS
            self.turn = -self.turn
            self.display_chess(self.game_board)

    def refresh(self):
        self.board_frame.pack(side=tk.LEFT)
        self.control_panel.pack(side=tk.RIGHT)
        self.display_canvas.pack()
        # self.display_chess(board)
        self.win.update()
コード例 #55
0
 def test_set_cell(self):
     game_board = GameBoard()
     game_board.set_cell(3,1)
     self.assertFalse(game_board.is_cell_empty(3))
コード例 #56
0
 def __init__(self, board=None, pipe=None, mode=None):
     global ori_board
     if board is None:
         self.game_board = GameBoard()
     else:
         self.game_board = board
     self.s = pipe
     self.turn = 1
     self.win = tk.Tk()
     ###
     if pipe is None:
         self.win.title("Surakarta")
     else:
         self.win.title(self_user_name)
     ###
     self.buffer = []
     ori_board = cv2.imread('resources/pictures/board.jpeg')
     ori_board = ori_board[..., ::-1]
     ori_board = cv2.resize(ori_board, (600, 600),
                            interpolation=cv2.INTER_NEAREST)
     ori_board = ImageTk.PhotoImage(Image.fromarray(ori_board))
     self.board_frame = tk.Frame(self.win)
     self.control_panel = tk.Frame(self.win,
                                   bg='WHITE',
                                   bd=0,
                                   height=600,
                                   width=200)
     self.display_canvas = tk.Canvas(self.board_frame,
                                     bg='WHITE',
                                     bd=0,
                                     heigh=600,
                                     width=600)
     self.display_canvas.create_image(0, 0, anchor='nw', image=ori_board)
     self.r = 15
     self.a = None
     self.b = None
     self.x = None
     self.y = None
     self.p = None
     self.history = []
     self.mode = mode
     self.display_posi = []
     self.my_turn_flag = None
     for i in range(15):
         line_display_posi = []  # 初始化 显示位置矩阵
         for j in range(15):
             x = 39.2 * j + 25
             y = 39.2 * i + 25
             line_display_posi.append(Position(x, y))
         self.display_posi.append(line_display_posi)
     if self.s is not None:
         while self.my_turn_flag is None:
             try:
                 print('try receiving1')
                 info = self.receive()
                 print(info)
                 info = info.split('.')
                 if info[1] == 'first':
                     self.my_turn_flag = True
                     t = Thread(target=self.receive_position)
                     t.start()
                 elif info[1] == 'second':
                     self.my_turn_flag = False
                     t = Thread(target=self.receive_position)
                     t.start()
             except IndexError:
                 pass
コード例 #57
0
def test_bad_string_entry():
    # ensure board state remains unchanged upon bad string entry
    game = GameBoard()
    empty_board = str(game)
    game.insert_piece('test', 'X')
    assert str(game) == empty_board
コード例 #58
0
ファイル: game.py プロジェクト: rwinsinger/Python-Tic-Tac-Toe
        players.reverse()

"""
  This is the main logic for the game.  It will:
    - create the board
    - prompt for number of players (human/computer)
    - prompt for player names
    - loop - allowing for multiple games for same players
    - loop - for each player move - re-displaying board each time
    - check for winner and display winner name or tie if game over
    - prompt to see if they want to play again
"""
# Create array to hold players
players = []

board = GameBoard()

print "\nWelcome to the TIC-TAC-TOE game!\n"

# Hard code this for now - will prompt later
num_players = get_num_humans() 

player_cnt = 0
# Prompt for player's names and then create player
while player_cnt < num_players:
    # Use static method to get name
    name = Player.get_player_name()

    # Create player and add to player list
    players.append(Player(name, board, player_cnt))
    player_cnt += 1