コード例 #1
1
ファイル: simulation.py プロジェクト: seadraa/CS440-AI
  def humanVsAI(self, AI):
    while status[0] != 1:

      self.board.makeMove(move1);
      #print "player 1 move"
      #print move1;

      temp = board(None);
      
      self.board.copycctor(temp);

      move2 = minPlayer.generateMove(temp);
      
      self.board.makeMove(move2);
      #print "player 2 move"
      #print move2;

      status = self.board.getStatus();
    #  self.board.printBoard();
      #sprint;
      #time.sleep(1)
    self.board.printBoard();

    # Print Scores
    print self.board.getStatus();
コード例 #2
0
ファイル: rule_checker.py プロジェクト: kyliec362/393_remote
    def check_history(self, boards, stone):
        """
        Verifies that board history is valid
        :return: Bool
        """
        if len(boards) == 1:
            return empty_board(boards[0]) and stone == black
        # check to see if liberties removed from previous boards
        for b in boards:
            curr_board = board(b)
            if len(curr_board.get_no_liberties(black)) > 0 or len(
                    curr_board.get_no_liberties(white)) > 0:
                return False
        if len(boards) == 2:
            if not empty_board(boards[1]):
                return False
            last_player = last_turn_player(boards)
            # white can't go first
            if empty_board(boards[1]):
                if stone == black:
                    return False
                if len(board(boards[0]).get_points(white)) >= 1:
                    return False
            return self.valid_between_two_boards(
                last_player, [last_played_point(boards, last_player), boards],
                stone)
        else:  # 3 boards received
            # ko rule violation
            if boards[0] == boards[2]:
                return False
            # can't go twice in a row
            last_player = last_turn_player(boards)
            if stone == last_player:
                return False
            last_boards = boards[1:]
            if last_player == last_turn_player(last_boards):
                if empty_board(boards[2]) and last_player == black:
                    return False
                if boards[1] == boards[2]:
                    return self.valid_between_two_boards(
                        last_player,
                        [last_played_point(boards, last_player), boards],
                        stone)
                return False

            # check valid move between oldest and middle boards and middle and current board
            valid_1_2 = self.valid_between_two_boards(
                last_player, [last_played_point(boards, last_player), boards],
                stone)
            valid_2_3 = self.valid_between_two_boards(
                last_turn_player(last_boards), [
                    last_played_point(last_boards,
                                      last_turn_player(last_boards)),
                    last_boards
                ], stone)
            if (last_player
                    == last_turn_player(last_boards)) or (not valid_1_2
                                                          or not valid_2_3):
                return False
        return True
コード例 #3
0
ファイル: player.py プロジェクト: MicahThompkins/go_project
 def make_capture_1_move(self, curr_board, stone, point):
     curr_board = board(curr_board)
     updated_board = curr_board.place(stone, point)
     stones_to_remove = board(updated_board).get_no_liberties(get_opponent_stone(stone))
     if len(stones_to_remove) > 0:
         return True
     return False
コード例 #4
0
ファイル: main.py プロジェクト: hmm-norah/snake
def main():

    game = board()
    screen.fill(WHITE)

    finished = False
    while not finished:
        clock.tick(fps)

        status = game.update()

        while status == 0:
            pygame.display.flip()
            clock.tick(fps)
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        game = board()
                        screen.fill(WHITE)
                        status = 1
                elif event.type == pygame.QUIT:
                    status = 1
                    finished = True

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                finished = True
コード例 #5
0
ファイル: rule_checker.py プロジェクト: kyliec362/393_remote
 def valid_between_two_boards(self, stone, move, initial_stone):
     """
     Compares two boards and determines if the play between them is valid
     :return: Bool
     """
     if move[0] == "pass":
         return True
     # move is a play
     boards = move[1]
     current_board = board(boards[0])
     previous_board = board(boards[1])
     if not self.check_valid_capture(current_board, previous_board, stone):
         return False
     if current_board.game_board == previous_board.game_board and stone == initial_stone:
         return False
     if get_opponent_stone(stone) == last_turn_player(boards):
         return False
     # both players can't have an increase in stones on the board
     num_stones_current = len(current_board.get_points(stone))
     num_stones_previous = len(previous_board.get_points(stone))
     num_opp_stones_current = len(
         current_board.get_points(get_opponent_stone(stone)))
     num_opp_stones_previous = len(
         previous_board.get_points(get_opponent_stone(stone)))
     if (num_stones_current !=
         (num_stones_previous + 1)) or (num_opp_stones_current >
                                        num_opp_stones_previous):
         return False
     if self.invalid_swaps(current_board.game_board,
                           previous_board.game_board):
         return False
     return True
コード例 #6
0
ファイル: agent.py プロジェクト: JimmyChiu702/TCG_project2
    def take_action(self, before):
        best_v = float('-inf')
        best_a = None
        best_op = None
        for op in range(4):
            after = board(before)
            reward = after.slide(op)
            if reward != -1:
                tmp_v = reward + self.evaluate(after)
                if tmp_v > best_v:
                    best_v = tmp_v
                    best_a = action.slide(op)
                    best_op = op
        if not self.isFirst:
            if best_v != float('-inf'):
                self.update(self.last_state, best_v)
            else:
                self.update(self.last_state, 0)
        self.last_state = board(before)
        self.last_state.slide(best_op)
        self.last_value = self.evaluate(self.last_state)
        self.isFirst = False

        if best_a == None:
            return action()
        else:
            return best_a
コード例 #7
0
ファイル: player.py プロジェクト: aLatif01/YoureFired
 def __init__(self):
     # this player's ships
     self.shipList = []
     self.shipCoordinateList = []
     # this player's board
     self.myBoard = board(8, 8)
     # opponent's board
     self.opBoard = board(8, 8)
コード例 #8
0
 def apply_action(self, move):
     reward = move.apply(self.state())
     state = board(self.state())
     if reward == -1:
         return False
     usage = self.millisec() - self.ep_time
     self.ep_state = state
     record = board(self.state(
     )), move, reward, usage  # state, action, reward, time usage
     self.ep_moves += [record]
     self.ep_score += reward
     return True
コード例 #9
0
    def test_illegal_boardSize(self):
        illegalVal = -1
        legalVal = 2
        try:
            board(boardSize={'x':illegalVal,'y':legalVal})
        except:
            self.assertTrue(True)

        try:
            board(boardSize={'x':legalVal,'y':illegalVal})
        except:
            self.assertTrue(True)
コード例 #10
0
 def apply_action(self, move):
     # print('prev board\n', self.state())
     reward = move.apply(self.state())
     state = board(self.state())
     # print('new board\n', self.state())
     usage = self.millisec() - self.ep_time
     self.ep_state = state
     record = board(self.state(
     )), move, reward, usage  # state, action, reward, time usage
     self.ep_moves += [record]
     self.ep_score += reward
     return True
コード例 #11
0
    def test_illegal_boardSize(self):
        illegalVal = -1
        legalVal = 2
        try:
            board(boardSize={'x': illegalVal, 'y': legalVal})
        except:
            self.assertTrue(True)

        try:
            board(boardSize={'x': legalVal, 'y': illegalVal})
        except:
            self.assertTrue(True)
コード例 #12
0
ファイル: main.py プロジェクト: MarioBonse/KakuroSolverCSP
def main():
    if len(sys.argv) == 1:
        name = "test_10(30x30!)"
    else:
        name = sys.argv[1]
    try:
        sq = board.board(load=True, name="../KakuroStored/" + name + ".csv")
    except:
        sq = board.board(load=True, name="KakuroStored/" + name + ".csv")
    sq.print()
    print("\n\n THE SOLUTION IS:")
    start = time.time()
    sq.solve()
    print("in %.10f seconds" % (time.time() - start))
コード例 #13
0
ファイル: player.py プロジェクト: MicahThompkins/go_project
 def randomize_next_move(self, n, curr_board, stone, point, boards):
     if n == 1:
         return boards
     curr_board = board(curr_board)
     updated_board = curr_board.place(stone, point)
     new_boards = [updated_board] + boards[:min(2, len(boards))]
     opponent_random_move = self.next_player_move(stone, new_boards)
     if opponent_random_move == "pass":
         new_boards = [new_boards[0]] + [new_boards[0]] + [new_boards[1]]
     else:
         new_boards = [board(new_boards[0]).place(get_opponent_stone(stone), opponent_random_move)] + \
                      [new_boards[0]] + [new_boards[1]]
     point = self.make_a_move_dumb(new_boards)
     return self.randomize_next_move(n - 1, new_boards[0], stone, point, new_boards)
コード例 #14
0
ファイル: main.py プロジェクト: raiizoor/GamesWithPython
def main(StandardScren):
    restart_screen(StandardScren)
    width = StandardScren.getmaxyx()[1]
    x_center = (width - 1) // 2
    posicoes = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]

    while True:
        entrada = StandardScren.getkey()
        if entrada == 'q':
            break
        if entrada == 'h':
            about(StandardScren)
        else:
            board(StandardScren, posicoes, x_center)
コード例 #15
0
    def expand(self):

        # go through 4 moves here
        if self.player_turn == 1:
            for move in [0, 1, 2, 3]:

                # if the move is legal add a child node to the child array
                if self.state.is_valid_move(move):

                    test_board = self.state
                    temp_board = board()
                    temp_board.score = test_board.score
                    for x in [0, 1, 2, 3]:
                        for y in [0, 1, 2, 3]:
                            temp_board.tiles[x][y] = test_board.tiles[x][y]
                    temp_board.move_tiles(move)

                    child = Node(temp_board, 2, self.DQN, move, self)
                    self.children.append(child)

        # add random tile to each spot
        else:
            for x in [0, 1, 2, 3]:
                for y in [0, 1, 2, 3]:
                    if self.state.tiles[x][y] == 0:

                        test_board = self.state

                        temp_board_2 = board()
                        temp_board_2.score = test_board.score

                        temp_board_4 = board()
                        temp_board_4.score = test_board.score

                        for r in [0, 1, 2, 3]:
                            for q in [0, 1, 2, 3]:
                                temp_board_2.tiles[r][q] = test_board.tiles[r][
                                    q]
                                temp_board_4.tiles[r][q] = test_board.tiles[r][
                                    q]

                        temp_board_2.tiles[x][y] = 2
                        temp_board_4.tiles[x][y] = 4

                        child_2 = Node(temp_board_2, 1, self.DQN, 9, self)
                        child_4 = Node(temp_board_4, 1, self.DQN, 9, self)

                        self.children.append(child_2)
                        self.children.append(child_4)
コード例 #16
0
    def __init__(self):
        """
		Initialize arguments
		Args:
		None
		Returns:
		None
		"""
        # this player's ships
        self.shipList = []
        self.shipCoordinateList = []
        # this player's board
        self.myBoard = board(8, 8)
        # opponent's board
        self.opBoard = board(8, 8)
コード例 #17
0
def _test_print_jump_table():
    my_board = board.board()
    p1 = player(my_board, my_board.player_1, my_board.mark_player_1)
    p1.dump_jump_table()
    print "********** player move ************"
    p1.move()
    p1.dump_jump_table()
コード例 #18
0
    def runGame(self, AI):
        status = self.board.getStatus()
        self.board.printBoardforGame()
        while status[0] != 1:
            print status
            move = input("Enter your move \n")
            parsedMove = parseUserInput(move)
            parsedMove.append(1)

            if not isValidMove(parsedMove, self.board):
                print "Please enter a valid move"
                continue
            self.board.makeMove(parsedMove)
            self.board.printBoardforGame()
            print
            #print "player 1 move"
            #print move1;

            temp = board(None)

            self.board.copycctor(temp)

            move2 = AI.generateMove(temp)

            self.board.makeMove(move2)
            #print "player 2 move"
            #print move2;
            print move2
            status = self.board.getStatus()
            self.board.printBoardforGame()
            print
        self.board.printBoardforGame()

        # Print Scores
        print self.board.getStatus()
コード例 #19
0
    def __init__(self):
        """ Constructor for the game class.  Makes a simple game with a board """

        # Is putting more than assignments in the constructor bad practice?
        # I couldn't think of better way to do it...
        self.game_size = input("What size would you like to play? >> ")
        self.board = b.board(self.game_size)
コード例 #20
0
 def __init__(self,
              wplayer='human',
              bplayer='human',
              clock=60 * 60,
              logfile='d:\\temp\\chesslog.txt'):
     self.zboard = board(plainboardinit)
     self.white = {
         'col': 'w',
         'player': wplayer,
         'time': clock,
         'hist': [],
         'is_in_check': False
     }
     self.black = {
         'col': 'b',
         'player': bplayer,
         'time': clock,
         'hist': [],
         'is_in_check': False
     }
     self.turn = self.white
     self.turn_count = 1
     self.undo_stack = []
     self.ai = AI()
     self.full_notation = ''  # quite as the values in hist, but with the count and # + ? !
     with open(logfile, 'w') as f:
         self.logfile = logfile  #sys.stdout
コード例 #21
0
    def __init__(self):
    
        self.board = board()
        #self.intelligence = intelligence()
        self.human_sequence_list = [0, 0, 0, 0]
        self.computer_sequence_list = [0, 0, 0, 0]
        
        """ 
        idea initial
        sequence_list
        position 0 in list -> 2 pieces with one open side
        position 1 in list -> 2 pieces with two open side
        position 2 in list -> 3 pieces with one open side
        position 3 in list -> 3 pieces with two open side
        position 4 in list -> 4 pieces with one open side
        position 5 in list -> 4 pieces with two open side
        position 6 in list -> 5 pieces with one open side
        position 7 in list -> 5 pieces with two open side

        idea implement
        position 0 in list -> 2 pieces
        position 1 in list -> 3 pieces
        position 2 in list -> 4 pieces
        position 3 in list -> 5 pieces
        """
        self.list_pos_human = []
        self.list_pos_computer = []
コード例 #22
0
ファイル: main.py プロジェクト: EngineersBox/Chess
 def __init__(self, master):
     self.GameBoard = board.board()
     self.bPlayer = players.blackPlayer()
     self.wPlayer = players.whitePlayer()
     for i in range(16):
         if i < 8:  #pawn
             self.GameBoard.setPos(1, i, self.bPlayer.pieces[i])
             self.GameBoard.setPos(6, i, self.wPlayer.pieces[i])
         elif 8 <= i < 10:  #knight
             self.GameBoard.setPos(0, 1, self.bPlayer.pieces[i])
             self.GameBoard.setPos(0, 6, self.bPlayer.pieces[i])
             self.GameBoard.setPos(7, 1, self.wPlayer.pieces[i])
             self.GameBoard.setPos(7, 6, self.wPlayer.pieces[i])
         elif 10 <= i < 12:  #bishop
             self.GameBoard.setPos(0, 2, self.bPlayer.pieces[i])
             self.GameBoard.setPos(0, 5, self.bPlayer.pieces[i])
             self.GameBoard.setPos(7, 2, self.wPlayer.pieces[i])
             self.GameBoard.setPos(7, 5, self.wPlayer.pieces[i])
         elif 12 <= i < 14:  #rook
             self.GameBoard.setPos(0, 0, self.bPlayer.pieces[i])
             self.GameBoard.setPos(0, 7, self.bPlayer.pieces[i])
             self.GameBoard.setPos(7, 0, self.wPlayer.pieces[i])
             self.GameBoard.setPos(7, 7, self.wPlayer.pieces[i])
         elif 14 == i:  #queen
             self.GameBoard.setPos(0, 3, self.bPlayer.pieces[i])
             self.GameBoard.setPos(7, 3, self.wPlayer.pieces[i])
         elif 15 == i:  #king
             self.GameBoard.setPos(0, 4, self.bPlayer.pieces[i])
             self.GameBoard.setPos(7, 4, self.wPlayer.pieces[i])
     self.master = master
     self.create_widgets()
     self.clickCount = 1
     self.pos1 = []
     self.pos2 = []
コード例 #23
0
    def humanVsAI(self, AI):
        while status[0] != 1:

            self.board.makeMove(move1)
            #print "player 1 move"
            #print move1;

            temp = board(None)

            self.board.copycctor(temp)

            move2 = minPlayer.generateMove(temp)

            self.board.makeMove(move2)
            #print "player 2 move"
            #print move2;

            status = self.board.getStatus()
        #  self.board.printBoard();
        #sprint;
        #time.sleep(1)
        self.board.printBoard()

        # Print Scores
        print self.board.getStatus()
コード例 #24
0
def main_loop(stdscr):
	k=0
	main_board=board.board(35,35)
	bloques=blocks.blocks(20,stdscr)
	enemigos=generate_enemys() #Se generan los enemigos que son los nombres de los ficheros
	proceso_key=Thread(target=catch_key, args=(stdscr,main_board,enemigos,bloques,))
	proceso_key.start()
コード例 #25
0
ファイル: rule_checker.py プロジェクト: kyliec362/393_remote
 def calculate_score(self, input_board):
     """
     Calculates the score of each player for a given board
     :return: JSON
     """
     white_score = 0
     black_score = 0
     curr_board = board(input_board)
     for i in range(len(curr_board.game_board)):  # row
         for j in range(len(curr_board.game_board[i])):  # col
             if curr_board.game_board[i][j] == black:
                 black_score += 1
             elif curr_board.game_board[i][j] == white:
                 white_score += 1
             else:
                 reachable_white = curr_board.reachable(
                     make_point(j, i), white)
                 reachable_black = curr_board.reachable(
                     make_point(j, i), black)
                 # if both white and black can reach it, it is neutral
                 if reachable_black and reachable_white:
                     continue
                 elif reachable_black:
                     black_score += 1
                 elif reachable_white:
                     white_score += 1
     return {"B": black_score, "W": white_score}
コード例 #26
0
ファイル: playGame.py プロジェクト: seadraa/CS440-AI
    def runGame(self, AI):
        status = self.board.getStatus()
        self.board.printBoardforGame()
        while status[0] != 1:
            print status
            move = input("Enter your move \n")
            parsedMove = parseUserInput(move)
            parsedMove.append(1)

            if not isValidMove(parsedMove, self.board):
                print "Please enter a valid move"
                continue
            self.board.makeMove(parsedMove)
            self.board.printBoardforGame()
            print
            # print "player 1 move"
            # print move1;

            temp = board(None)

            self.board.copycctor(temp)

            move2 = AI.generateMove(temp)

            self.board.makeMove(move2)
            # print "player 2 move"
            # print move2;
            print move2
            status = self.board.getStatus()
            self.board.printBoardforGame()
            print
        self.board.printBoardforGame()

        # Print Scores
        print self.board.getStatus()
コード例 #27
0
    def AI_move(self,
                init_borad_state,
                lastmove,
                turn_col,
                w_game_hist,
                b_game_hist,
                depth=5,
                verbose=0):
        self.logit('/n/n', 5 * '-', 'CALL AI_move', '-' * 5)
        self.logit('depth:', depth, 'init_borad_state', init_borad_state,
                   'lastmove', lastmove)

        self.game_hist['w'] = w_game_hist
        self.game_hist['b'] = b_game_hist
        if lastmove != None:
            lm_move_triplet = (lastmove[2], lastmove[3], lastmove[4])
            action = {
                'origin': lastmove[1],
                'move': lm_move_triplet,
                'path': []
            }
        else:
            action = {'origin': '', 'move': '', 'path': []}
        ai_board = board(init_borad_state)
        rrr = self.Value(ai_board, turn_col, depth, depth, -999, 999, action)
        if verbose > 0:
            print rrr
            print '\n'.join([str(x) + ':' + str(rrr[x]) for x in rrr])
            print '-' * 10
        return rrr['move']
        return "ERROR - no of the suggested moves is valid; unles mate - it's an error"
コード例 #28
0
    def rollout(self):

        # test_board = self.state
        temp_board = board()
        temp_board.score = self.state.score
        for x in [0, 1, 2, 3]:
            for y in [0, 1, 2, 3]:
                temp_board.tiles[x][y] = self.state.tiles[x][y]

        # add a random tile if the player is 2 and then play rest of game
        if self.player_turn == 2:
            temp_board.add_new_tile()

            while not temp_board.game_is_over():

                # call the DQN and perform the best move
                cur_state = create_state(temp_board)
                cur_state = cur_state.reshape(1, self.DQN.state_shape[1])
                move = self.DQN.act(cur_state)

                temp_board.move_tiles(move)
                temp_board.add_new_tile()

            # back prop the result of the game
            self.back_prop(temp_board.score)

        # if the player is 1
        elif self.player_turn == 1:

            cur_state = create_state(temp_board)
            cur_state = cur_state.reshape(1, self.DQN.state_shape[1])
            predictions = self.DQN.model.predict(cur_state)[0]

            score = max(predictions)
            self.back_prop(score)
コード例 #29
0
 def test_should_detect_draw(self):
     t3 = board.board(mock())
     t3.board = "".join(["OXO",
                         "XOX",
                         "XOX"])
     t3 | should | be_draw
     t3 | should_not | be_winner
コード例 #30
0
    def __init__(self, name):

        self.ships = []
        self.board = board()
        self.name = name
        self.other_player = None
        self.letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
コード例 #31
0
 def test_boardSize(self):
     xVal = 5
     yVal = 3
     test_board = board(boardSize={'x':xVal,'y':yVal})
     board_size = test_board.get_board_size()
     self.assertEqual(xVal,board_size['x'])
     self.assertEqual(yVal,board_size['y'])
コード例 #32
0
    def __init__(self, boardSize: int) -> None:
        """
        The main form of the Mine Sweeper game
        It generates buttons and shows the form
        """

        self.board = board(size=boardSize)

        self.window = Tk()
        self.window.title("Mine Sweeper")
        self.window.geometry('1000x900')
        self.window.configure(background="white", padx=50, pady=50)

        for i_index in range(boardSize):
            for j_index in range(boardSize):
                icon = PhotoImage(Image.open("flag.png"))
                btn = ttk.Button(
                    self.window, image=icon
                )  #.grid(row=i, column=j, padx=2, pady=2, ipadx=7, ipady=30)
                btn.grid(row=i_index,
                         column=j_index,
                         padx=2,
                         pady=2,
                         ipadx=7,
                         ipady=30)
                # btn.configure(image = icon)
                btn.bind('<Button-1>', self.left_click)
                btn.bind('<Button-3>', self.right_click)
                # btn.pack()

        self.window.pack_propagate()
        self.window.mainloop()
コード例 #33
0
    def rollout(self):

        # test_board = self.state
        temp_board = board()
        temp_board.score = self.state.score
        for x in [0, 1, 2, 3]:
            for y in [0, 1, 2, 3]:
                temp_board.tiles[x][y] = self.state.tiles[x][y]

        # if the player is 2 select a random move for them (adding a random tile)
        if self.player_turn == 2:
            temp_board.add_new_tile()

        turn_count = 0
        while not temp_board.game_is_over():

            # perform a random legal move
            move = random.getrandbits(2)
            while not temp_board.is_valid_move(move):
                move = (move + 1) % 4

            temp_board.move_tiles(move)
            temp_board.add_new_tile()
            turn_count += 1

        # back prop the result of the game
        self.back_prop(temp_board.score)
コード例 #34
0
 def take_action(self, state):
     legal = [op for op in range(4) if board(state).slide(op) != -1]
     if legal:
         op = self.choice(legal)
         return action.slide(op)
     else:
         return action()
コード例 #35
0
ファイル: rule_checker.py プロジェクト: kyliec362/393_remote
def check_liberties_removed(boards):
    for b in boards:
        curr_board = board(b)
        if len(curr_board.get_no_liberties(black)) > 0 or len(
                curr_board.get_no_liberties(white)) > 0:
            return False
    return True
コード例 #36
0
ファイル: simulation.py プロジェクト: seadraa/CS440-AI
  def run(self, maxPlayer, minPlayer, isTest):
    status = self.board.getStatus();
    if not isTest:
      while status[0] != 1:
        temp = board(None);
        
        self.board.copycctor(temp);
        move1 = maxPlayer.generateMove(temp);
        
        self.board.makeMove(move1);
        #print "player 1 move"
        #print move1;

        temp = board(None);
        
        self.board.copycctor(temp);
        status = self.board.getStatus();
        if status[0] != 1:
          move2 = minPlayer.generateMove(temp);
          self.board.makeMove(move2);
        else:
          break;
        #print "player 2 move"
        #print move2;

        status = self.board.getStatus();
        #self.board.printBoard();
        #print;
        #time.sleep(1)
      print;
      self.board.printBoard();

      # Print Scores
      print self.board.getStatus();
    else:
      temp = board(None);
      
      self.board.copycctor(temp);
      #temp.printOccupants();
      move1 = maxPlayer.generateMove(temp);
      print;
      #self.board.printOccupants();
      
      self.board.makeMove(move1);
      print move1;
      self.board.printOccupants();
コード例 #37
0
    def initialize(self, remotedocument, wshandler, sessionid, tabid):
        # remember these for later use
        self.rdoc = remotedocument
        self.wsh = wshandler
        log.info('New session opened, id=' + self.wsh.id)

        self.board = board(self.rdoc, 13, 500.0)
        self.rdoc.body.append(self.board.svg)
コード例 #38
0
 def assert_winner(self, scenario):
     (starting_board, move) = scenario
     t3 = board.board(mock())
     t3.board = starting_board
     t3 | should_not | be_winner
     # when
     t3.move(board.PLAYER_X, move)
     # then
     t3 | should | be_winner
     t3 | should_not | be_draw
コード例 #39
0
ファイル: wrapper.py プロジェクト: wusui/toybox
def solver_filter(in_data, pfunc):
    """
    Generate a board from in_data. Send an error message if appropriate
    """
    cboard = board(in_data, pfunc)
    if len(cboard.msg_type) > 0:
        return make_emesg(cboard)
    if check_check(cboard, BLACK):
        return "SET UP ERROR|Black should not start in check|120|360"
    return "ATTENTION|Chess solver not yet implemented|120|360"
コード例 #40
0
ファイル: boardReceiver.py プロジェクト: poratGalpo/AI_module
 def get_board(self, refreshBoard = False):
     """
     This method returns the board to the caller,
     :param refreshBoard: boolean indicating if it is necessary to refresh before the return
     :return: board instance and direction
     """
     if refreshBoard is True:
         self.refresh_board()
     current_board = board.board(preMade_data=self._map_sub._board)
     return current_board, self._map_sub._direction
コード例 #41
0
ファイル: boardReceiver.py プロジェクト: poratGalpo/AI_module
 def refresh_board(self):
     """
     sets the board's var _instance var to be the next map
     :return: True upon success, False otherwise
     """
     self._map_sub._board = None
     while self._map_sub._board == None:
         self._map_sub.listener()
     current_board = board.board(preMade_data=self._map_sub._board)
     return current_board, self._map_sub._direction
コード例 #42
0
ファイル: xiangqi.py プロジェクト: kirakira/zaixianxiangqi
def buildBoardFromMoves(moves):
    b = board()
    for move in moves:
        if move == "":
            continue
        if isRegularMove(move):
            b.move(int(move[0]), int(move[1]), int(move[2]), int(move[3]))
        else:
            logging.error("unknown move: " + move)
    return b
コード例 #43
0
ファイル: chesslib.py プロジェクト: bobev18/my-py-chess
 def __init__(self,wplayer='human',bplayer='human',clock=60*60,logfile='d:\\temp\\chesslog.txt'):
     self.zboard = board(plainboardinit)
     self.white = {'col':'w', 'player':wplayer, 'time':clock, 'hist': [], 'is_in_check':False}
     self.black = {'col':'b', 'player':bplayer, 'time':clock, 'hist': [], 'is_in_check':False}
     self.turn = self.white
     self.turn_count = 1
     self.undo_stack = []
     self.ai = AI()
     self.full_notation = '' # quite as the values in hist, but with the count and # + ? !
     with open(logfile,'w') as f:
         self.logfile = logfile #sys.stdout
コード例 #44
0
ファイル: world.py プロジェクト: iparedes/bugs1
    def __init__(self):
        self.habs={}
        self.cycles=0
        self.habcount=0
        self.maxpop=0
        self.board=board.board(BOARDSIZE,BOARDSIZE)
        self.deaths=[] # Ident of bugs dead during the cycle
        self.newborns=[] # Newborns during the cycle
        self.graveyard=[] # Dead bugs

        self.sowrate=SOWRATE
コード例 #45
0
ファイル: search.py プロジェクト: wordswords/astarpython
    def run(self):
        """ Run the search """

        # setup board
        self.theboard = board(sys.argv[1], sys.argv[2], sys.argv[3])
        print self.theboard
        start = self.theboard.start
        goal = self.theboard.goal

        # initialise start node
        self.g_score[start] = 0
        self.f_score[start] = self.g_score[start] + self.heuristic_cost_estimate(start, goal)
        self.openset.add(start)

        while self.count(self.openset) > 0:
            # while we still have nodes left to evaluate

            # pick the next node to evaluate as the one we estimate has the shortest path cost to reach the goal node
            # that hasn't already been evaluated
            f_score_sorted = sorted(
                self.f_score, key=lambda square: self.g_score[square] + self.heuristic_cost_estimate(square, goal)
            )
            i = 0
            for i in range(len(f_score_sorted) - 1):
                if f_score_sorted[i] not in self.closedset:
                    break

            current = f_score_sorted[i]

            if current == goal:
                return self.reconstruct_path(goal)

            try:
                self.openset.remove(current)
            except KeyError, e:
                pass

            self.closedset.add(current)
            for neighbour in self.neighbour_nodes(current):
                if neighbour not in self.closedset:

                    temp_g_score = self.g_score[current] + 1
                    if (neighbour not in self.openset) or (temp_g_score < self.g_score[neighbour]):
                        # if the neighbour node has not yet been evaluated yet, then we evaluate it
                        # or, if we have just found a shorter way to reach neighbour from the start node,
                        # then we replace the previous route to get to neighbour, with this new quicker route
                        self.came_from[neighbour] = current
                        self.g_score[neighbour] = temp_g_score
                        self.f_score[neighbour] = self.g_score[neighbour] + self.heuristic_cost_estimate(
                            neighbour, goal
                        )

                        if neighbour not in self.openset:
                            self.openset.add(neighbour)
コード例 #46
0
ファイル: game.py プロジェクト: jonoff/tictacten
 def __init__(self, p1, p2):
     self.board = big_board()
     self.mini = board()
     self.turn = 1
     self.current_player = None
     self.p1 = p1
     self.p1.set_mark(marks[0])
     self.p2 = p2
     self.p2.set_mark(marks[1])
     self.marks = {self.p1: marks[0], self.p2: marks[1]}
     self.gameover = False
     self.last_move = move()
コード例 #47
0
ファイル: world.py プロジェクト: iparedes/bugs2
    def __init__(self):
        self.habs={}
        self.cycles=0
        self.habcount=0
        self.maxpop=0
        self.board=board.board(BOARDSIZE,BOARDSIZE)
        self.deaths=[] # Ident of bugs dead during the cycle
        self.newborns=[] # Newborns during the cycle
        self.graveyard=[] # Dead bugs

        # Per thousand of cells growing food per cycle
        self.sowratevalues=[0.0001,0.001,0.01,0.1,1,2,5,10,50,100]
        self.sowrate=self.sowratevalues[SOWRATE]
コード例 #48
0
ファイル: boardReceiver.py プロジェクト: poratGalpo/AI_module
    def __init__(self):
        """

        :rtype: stub_boardReceiver
        """
        first_map = self.extract_map_from_file(self.fileIndexes[self._self_index])
        self._board = board.board(preMade_data=first_map)
        try:
            location = self._board.get_car_placement()
        except:
            print 'No car was found'
        self.car_initial_location['x'] = location['x']
        self.car_initial_location['y'] = location['y']
        self._direction = self.randomize_direction()
        self._self_index += 1
        return
コード例 #49
0
ファイル: game.py プロジェクト: BigMacStorm/AOI
	def minimaxRecurse(self, simBoard, depth):
		if depth == 0 or not simBoard.possible():
			return self.evaluate(simBoard)
		moves = simBoard.getMoveList()
		bestScore = -999999999
		currentScore = 0
		for x in moves:
			simBoard = board.board(simBoard)
			simBoard.makeMove(x[0], x[1])
			simBoard.changePlayer()

			currentScore = self.minimaxRecurse(simBoard, depth-1)
			currentScore *= -1

			if currentScore > bestScore:
				bestScore = currentScore
		return bestScore
コード例 #50
0
ファイル: ai.py プロジェクト: bobev18/my-py-chess
    def AI_move(self,init_borad_state,lastmove,turn_col,w_game_hist,b_game_hist,depth=5,verbose=0):
        self.logit('/n/n',5*'-','CALL AI_move','-'*5)
        self.logit('depth:',depth,'init_borad_state',init_borad_state,'lastmove',lastmove)

        self.game_hist['w']=w_game_hist
        self.game_hist['b']=b_game_hist
        if lastmove != None:
            lm_move_triplet=(lastmove[2],lastmove[3],lastmove[4])
            action = {'origin':lastmove[1],'move':lm_move_triplet,'path':[]}
        else:
            action = {'origin':'','move':'','path':[]}
        ai_board = board(init_borad_state)
        rrr = self.Value(ai_board,turn_col,depth,depth,-999,999,action)
        if verbose>0:
            print rrr
            print '\n'.join([str(x)+':'+str(rrr[x]) for x in rrr])
            print '-'*10
        return rrr['move']
        return "ERROR - no of the suggested moves is valid; unles mate - it's an error"
コード例 #51
0
ファイル: game.py プロジェクト: BigMacStorm/AOI
	def minimaxHandler(self, depth):
		moves = self.board.getMoveList()
		bestMove = [None, -999999999]
		simMove = [None, 0]
		for x in moves:
			simBoard = board.board(self.board)
			simBoard.makeMove(x[0], x[1])
			simBoard.changePlayer()

                        simMove[0] = [0,0,0]
			simMove[0][0] = x[0]
			simMove[0][1] = x[1]

			simMove[1] = self.minimaxRecurse(simBoard, depth-1)
			simMove[1] *= -1

			if simMove[1] > bestMove[1]:
				bestMove[0] = simMove[0]
				bestMove[1] = simMove[1]
		return bestMove
コード例 #52
0
    def test_xy_crop(self):

        x_original = 5
        y_original = 5
        sampleBoard = board(boardSize={'x':x_original,'y':y_original})
        try:
            sampleBoard.get_xy_map(-1,2)
            self.assertTrue(False)
        except:
            self.assertTrue(True)


        try:
            sampleBoard.get_xy_map(1,-1)
            self.assertTrue(False)
        except:
            self.assertTrue(True)

        x_param = 1
        y_param = 2
        cropped_board = sampleBoard.get_xy_map(x_param,y_param)
        self.assertEqual(cropped_board.get_board_size()['x'],x_param*2+1)
        self.assertEqual(cropped_board.get_board_size()['y'],y_param*2+1)
コード例 #53
0
ファイル: solve_main.py プロジェクト: sshortess/queens
def do_solver(n):
   """
   """
   b = board.board(n)
   row = 0
   col = 0
   i = 0
   while len(b.queen_list) < (n): #target number of queens on board

      i +=1
      q = queens.queen(row,col,n)
      q.mak_mask()
      b.add_queen(q)
      """
      print "\niteration", i
      b.print_board()

      print "queens placed", len(b.queen_list)
      print ""
      """
      if len(b.queen_list) == n:
         print "\niteration", i
         b.print_board()

         print "queens placed", len(b.queen_list)
         print ""
         break

      row,col = do_next_slot(b,row,col)
      if row is None:
         print "\niteration", i
         b.print_board()

         print "queens placed", len(b.queen_list)
         print "\tout of squares\n"
         print ""
         break
コード例 #54
0
ファイル: xiangqi.py プロジェクト: jyoung913/zaixianxiangqi
def makeMove(game, red, newMovesString):
  oldMoves = game.moves.split('/')
  newMoves = newMovesString.split('/')
  if len(newMoves) != len(oldMoves) + 1:
    raise ValueError('new moves is not based on old moves')
  for i in range(0, len(oldMoves)):
    if newMoves[i] != oldMoves[i]:
      raise ValueError('new moves diverged from old moves')

  b = board()
  for move in oldMoves:
    if move == '':
      continue
    if isRegularMove(move):
      b.move(int(move[0]), int(move[1]), int(move[2]), int(move[3]))
    else:
      logging.error('unknown move: ' + move)

  newMove = newMoves[-1]
  if isRegularMove(newMove):
    if red != b.redToGo:
      raise ValueError('player is not in move')

    if not b.checkedMove(int(newMove[0]), int(newMove[1]), int(newMove[2]), int(newMove[3])):
      raise ValueError('invalid move: ' + newMove)

    if b.hasWinningMove():
      newMovesString += '/R' if b.redToGo else '/B'
    elif b.isLosing():
      newMovesString += '/B' if b.redToGo else '/R'
  elif newMove == "B" or newMove == "R":
    raise ValueError('user cannot declare result')
  else:
    raise ValueError('unknown move: ' + newMove)

  game.moves = newMovesString
コード例 #55
0
    def test_car_initial_placement(self):
        try:
            #   Assuming board default sizes are x:10 y:10
            board(carPlacement={'x':11,'y':12})
            self.assertFalse(True)

        except:
            self.assertTrue(True)

        try:
            board(boardSize={'x':3,'y':3},carPlacement={'x':3,'y':3})
            self.assertFalse(True)
        except:
            self.assertTrue(True)

        try:
            board(boardSize={'x':3,'y':3},carPlacement={'x':1,'y':1})
            self.assertTrue(True)
        except:

            self.assertFalse(True)
コード例 #56
0
import os, inspect, sys
sys.path.append(os.path.dirname(inspect.getfile(inspect.currentframe())) + "/../lib")

import board
import cli_renderer

t3 = board.board(cli_renderer.BoardRendererCli(sys.stdout))

players = [board.PLAYER_O, board.PLAYER_X]
i = 0

while not t3.winner() and not t3.draw():
    player = players[i % len(players)]
    location = raw_input("move for {who} ? ".format(who=player))
    try:
        t3.move(player, location)
    except Exception as e:
        print e.args[0]
        continue
    i += 1
    print

if t3.draw():
    print "Draw!"
else:
    print "{player}'s win!".format(player=player)
コード例 #57
0
ファイル: game.py プロジェクト: CaptainSharf/Donkey-Kong-game
import pygame
from board import board
from stuff import *
from objects import fireball
from player import *
clock=pygame.time.Clock()
white=(255,255,255)
gamexit=False
ex=False
while not gamexit:
    bo=board()
    if ex==False:
        wally(bo)
        donk.put(bo,white)
        putcoin(bo)
        p.put(bo,white)
        control(bo,donk)
        ex=checkcollision(bo,p.x,p.y)
        collectcoin(bo,p.x,p.y)
       # if bo.b[p.x][p.y].char=="C":
        #    print "S"
        p.fall(bo)
        q.put(bo,32,3,white)
        if p.y==3:
            p.score+=50
            refresh()
        #if bo.b[p.x][p.y].char!="P":
        #ex=p.collide(bo)
        prnt("Your Score:"+str(p.score),bo,63)
        prnt("Lives Left:"+str(p.lives),bo,65)
    else:
コード例 #58
0
 def setUp(self):
     self.dict = trie.trie()
     self.dict.readDict("../dict.txt")
     self.b = board.board(5, dict)
コード例 #59
0
ファイル: playGame.py プロジェクト: seadraa/CS440-AI
def main():
    b = board("./game_boards/Keren.txt")
    p1 = MinimaxPlayer(2)
    g = Game(b)
    g.runGame(p1)