Exemplo n.º 1
0
def main():
	
	print_instruction()
	
	board = []
	for i in range(9):
		board.append(-1)
		
	win = False
	move = 0
	while not win:

		print_board(board)
		print "Turn number" + str(move+1)
		if move % 2 == 0:
			turn = 'X'
		else:
			turn = 'O'

		user = get_input(turn)
		while board[user] != -1:
			print "Invalid move! Cell already taken. Please try again.\n"
			user = get_input(turn)
		board[user] = 1 if turn == 'X' else 0

		move += 1
		if move > 4:
			winner = check_win(board)
			if winner != -1:
				out = "The winner is"
				out += "X" if winner == 1 else "O"
				out += "=D"
				quit_game(board,out)
			elif move >= 9:
				quit_game(board, "No winner :(")
Exemplo n.º 2
0
def main():

    print_instruction()

    board = []
    for i in range(9):
        board.append(-1)

    win = False
    move = 0
    while not win:

        print_board(board)
        print "Turn number" + str(move + 1)
        if move % 2 == 0:
            turn = 'X'
        else:
            turn = 'O'

        user = get_input(turn)
        while board[user] != -1:
            print "Invalid move! Cell already taken. Please try again.\n"
            user = get_input(turn)
        board[user] = 1 if turn == 'X' else 0

        move += 1
        if move > 4:
            winner = check_win(board)
            if winner != -1:
                out = "The winner is"
                out += "X" if winner == 1 else "O"
                out += "=D"
                quit_game(board, out)
            elif move >= 9:
                quit_game(board, "No winner :(")
Exemplo n.º 3
0
def send_data(data):
    """
        Send data to server

        Parameters
        ----------
        data: str
            The data that'll be send to server

        Returns
        -------
        bool
            If the data was send
    """
    send = False
    if data == 'p' or data == 'P':
        bd.print_board()
        send = False
    elif data != '':
        tcp_sock.send(data.encode())
        send = True
    else:
        print('Invalid data. Send again')
        send = False

    return send
Exemplo n.º 4
0
def main():
    moves = 0
    instructions()
    human, computer = x_or_o()
    curr_player = pick_first_player(human, computer)
    board = new_board()

    while moves < 9:
        if curr_player == human:
            board[human_move(
                board
            )] = human  # Set the board[human_num] to the human pick of X or O
            curr_player = computer  # Switch to the other player
            print_board(board)
            # Check to see if there's a winner after 5 moves.
            if moves >= 5:  # After 5 moves, check if there's a winner
                if winner(board) == human:
                    print("GAME OVER! You have bested me this time, Player.")
                    break
        else:
            board[comp_move(
                board, computer, human
            )] = computer  # Set the board[comp_num] to the opposite of the human pick of X or O
            curr_player = human  # Switch to the other player
            print_board(board)
            if moves >= 5:  # After 5 moves, check if there's a winner
                if winner(board) == computer:
                    print("MWHAHAHA! Computers have taken over the world.")
                    break
        moves += 1
    if moves == 9:  # If there's no winner at 9 moves, it's a tie
        print("TIE! We are of equal intelligence.")
    restart()
Exemplo n.º 5
0
def start_game():
    player_1, player_2 = get_player()
    end = False
    # Afficher le plateau
    board = np.zeros(shape=(8, 8))  # Plateau vierge
    # Position init
    board[3][3] = 1
    board[3][4] = 2
    board[4][3] = 2
    board[4][4] = 1
    print_board(board, str(player_1), str(player_2))
    while not end:
        black_legal_moves = get_legal_move(board, 2)
        if black_legal_moves:
            moves = print_legal_moves(board, black_legal_moves, 2)
            board = take_player_turn(board, moves, 2)
        white_legal_moves = get_legal_move(board, 1)
        if white_legal_moves:
            moves = print_legal_moves(board, white_legal_moves, 1)
            board = take_player_turn(board, moves, 1)
        if not white_legal_moves and not black_legal_moves:
            end = True

    score_black = len(np.where(board == 2)[0])
    score_white = len(np.where(board == 1)[0])
    if score_black > score_white:
        winner = player_1
    elif score_black == score_white:
        winner = "draw"
    else:
        winner = player_2

    print("Winner : {}".format(winner))
Exemplo n.º 6
0
def main(player1, player2):
    game_winner = False
    start_text = Style.Foreground.violet + "Let's get started!" + Style.end
    board_at_start = make_board(player1.pawn, player2.pawn, empty_cell)
    move = 1

    print("Hello players!")
    if_instructions = input("Would you like to see the instructions?\n"
                            "y/n\n")
    if if_instructions == "n":
        pass
    else:
        instructions()
    print(start_text)
    board = board_at_start
    while not game_winner:
        if (move % 2) == 0:
            playing_player = player2
        else:
            playing_player = player1
        print_board(board)
        board = player_move(playing_player, board)
        board = check_if_player_has_a_queen(playing_player, board)
        game_winner = check_if_player_won(player1, player2, board)
        move += 1
    print("Congratulations, " + game_winner.name + ", you won!!!! ")
    print(game_winner.color + """          o 
       o^/|\\^o
    o_^|\\/*\\/|^_o
   o\\*`'.\\|/.'`*/o
    \\\\\\\\\\\\|//////
     {><><@><><}
     `\"\"\"\"\"\"\"\"\"`""" + Style.end)
Exemplo n.º 7
0
def display_rules():
    print("\033[41mRules\033[0m")  # Affiche "Rules" en fluo rouge
    print("\033[32mThe goal of the game: \033[0m")
    print(
        "\033[36m Having more checkers of his color than the opponent at the end of the game. The game ends when neither player can make a legal move or when all 64 squares are occupied.\033[0m"
    )
    print("\033[32mStarting position:\033[0m")
    print("\033[36m At the beginning of the game,\033[0m")
    print("\033[34m  two black pawns in:\033[0m")
    print("\033[34m  (3;4) and (4;3)\033[0m")
    print("\033[36m AND\033[0m")
    print("\033[37m  two white pawns in:\033[0m")
    print("\033[37m  (3;3) and (4;4)\033[0m")
    print("\033[36m See the example:\033[0m")
    board = np.zeros(shape=(8, 8))  # Plateau vierge
    # Position init
    board[3][3] = 2
    board[3][4] = 1
    board[4][3] = 1
    board[4][4] = 2
    print_board(board, "Player 1", "Player 2")

    print(
        "\033[36m Black always starts first and then the two opponents take turns. \033[0m"
    )
    print("\033[32mPawn laying:\033[0m")
    print(
        "\033[36m  On his turn, the player must place his checker on an empty square on the board, adjacent to an opponent's checker. He must also, when placing his pawn on the board, place one or more of his opponent's pawns between the pawn he is placing and a pawn of his own colour, already placed on the board. A move that frames the opponent's checkers can be made horizontally, vertically or diagonally. The checkers that the player has just framed become his own and take his colour. \033[0m"
    )
Exemplo n.º 8
0
 def __init__(self, player1_colour, player2_colour):
     self.player1_colour = player1_colour
     self.player2_colour = player2_colour
     self.player1 = None
     self.player2 = None
     self.board = create_board()
     print_board(self.board)
     self.clock = pygame.time.Clock()
def play_game(play_func_O=get_user_input,
              play_func_X=get_user_input,
              N=1,
              should_print_board=False):    
    global is_O
    global is_X
    global symbol

    global player_O_score
    global player_X_score

    global board
    #print(N)
    is_O = True
    is_X = False
    symbol = 'O'

    player_O_score = 0
    player_X_score = 0

    board = empty_board()

    game_counter = 0
    while True:
        try:
            if is_O:
                board = put_symbol(board, symbol, play_func_O(board))
                symbol = 'X'
            else:
                board = put_symbol(board, symbol, play_func_X(board))
                symbol = 'O'

            if should_print_board:
                print_board(board)

            is_O = not is_O
            is_X = not is_X

            # If someone wins, empty the board and show the score
            if update_score(has_winner(board), log=should_print_board) is not None:
                board = empty_board()
                is_O = True
                is_X = False
                symbol = 'O'

                game_counter += 1
                if game_counter >= N:
                    return (player_O_score, player_X_score)


        except PositionOccupiedError:
            print("That position is already occupied.")
        except (ValueError, IndexError):
            print("You don't entered a valid position")
Exemplo n.º 10
0
def initializeBoard(number_of_ships):
    """
        Initialize a board with n ships

        Parameters
        ----------
        number_of_ships: int
            The number of ships
    """
    # bd.board_file('board.txt')
    bd.initializeBoard(number_of_ships)
    bd.print_board()
Exemplo n.º 11
0
    def draw_move_and_check_win(self, column_to_play, player):
        game_over = False
        if is_valid_location(self.board, column_to_play):
            drop_piece(self.board, column_to_play, player.piece_id)

            print_board(self.board)
            four_in_a_row = winning_move(self.board, player.piece_id)
            self.display.draw_board(self.board, four_in_a_row)
            if four_in_a_row:
                print(f"{player.name} ({player.colour_name}) has won!")
                game_over = True
        else:
            print(f"Ignoring invalid column {column_to_play}")
        return game_over
Exemplo n.º 12
0
 def calc_nn_move(self, board, player):
     val = board.print_board()
     val = val[0:len(val)-1] 
     vals = val.split(',')
     features = np.array(vals).astype(float)
     features = features.reshape(1,6,7,1)
     return self.nn.predict(features)[0]
Exemplo n.º 13
0
def play(game_board, x_player, o_player):
    """Play a game."""
    players = [x_player, o_player]
    active_player = 0

    winner = TOKENS.BLANK

    while winner is TOKENS.BLANK:
        print("~~~~~~~~~~Turn {}~~~~~~~~~~".format(active_player))
        print_board(game_board)
        game_board = players[active_player % len(players)].play(game_board)
        winner = evaluate_board(game_board)
        active_player += 1

    print("~~~~~~~~~GAME OVER~~~~~~~~~~")
    print_board(game_board)
    print("{}wins!".format(value_to_str(winner)))
Exemplo n.º 14
0
 def learn_next_move(self, board, player):
     cols = np.array(board.get_valid_columns()) - 1
     val = board.print_board()
     val = val[0:len(val)-1] 
     vals = val.split(',')
     sample = np.array(vals).astype(float)
     sample = sample.reshape(1,6,7,1)
     prediction = self.nn.predict(sample)[0]
     prediction = prediction[cols]
     return cols[np.argmax(prediction)]
Exemplo n.º 15
0
def make_a_move(player, game_history):
    have_played = False
    # last_play = -1 if (len(game_history) == 0) else game_history[-1]

    while (have_played == False):
        if (IN_REPLAY_MODE):
            col = replay_list.pop(0)
        else:
            col = player.play()

        have_played = b.move_piece(player.piece, col)

    player.last_move = col
    # print(player.name, player.last_move)
    game_history.append(col)

    eog = b.check_eog(col)
    if (TOUR_BY_TOUR):
        clear()
        b.print_board()
        input()
    return eog
Exemplo n.º 16
0
def game_loop(board, is_player1, use_bot, diff):
    global is_won, is_tie, moves_remaining
    while not (is_won or is_tie):
        print("Moves left: %d" % moves_remaining)
        pos = None
        if (not is_player1) and use_bot:
            pos = minimax.best_move(board, False, diff, moves_remaining)
        else:
            bd.print_board(board)
            pos = bd.get_input(board)
        bd.place_piece(board, pos, is_player1)
        moves_remaining = moves_remaining - 1
        is_won = bd.check_win(board, pos, is_player1)
        is_tie = (not is_won) and (moves_remaining == 0)
        if (is_won or is_tie):
            break
        is_player1 = not is_player1
    bd.print_board(board)
    if is_tie:
        print("TIE!")
    else:
        player = 1 if is_player1 else 2
        print("Player %d is the winner!" % player)
Exemplo n.º 17
0
def main():
	
	print_instruction()
	
	board = []
	for i in range(9):
		board.append(-1)
		
	win = False
	move = 0
	while not win:

		print_board(board)
		print "Turn number" + str(move+1)
        	if move % 2 == 0:
            		#this is the user
            		turn = 'X'
            		user = get_input(turn)
            		while board[user] != -1:
                		print "Invalid move! Cell already taken. Please try again.\n"
                		user = get_input(turn)
            		board[user] = 1
        	else:
            		#this will be the computer
            		turn = 'O'
            		comp=generate_o(board)#computer behaviour define
            		board[comp]=0
		move += 1
		if move > 4:
			winner = check_win(board)
			if winner != -1:
				out = "The winner is"
				out += "X" if winner == 1 else "O"
				out += "=D"
				quit_game(board,out)
			elif move >= 9:
				quit_game(board, "No winner :(")
Exemplo n.º 18
0
    def _game_turn(self, board, human_player: str, goes_first: int):
        player = self.side_value[human_player]
        new_board = None

        if goes_first == player:
            if self.it == 0:
                print("Human goes first!")
                print("-" * 25)

            new_board = self._human_turn(board, player)
            print_board(new_board)

            if check_win(new_board, player):
                return player
            if check_tie(new_board):
                return 0

            new_board = self._bot_turn(new_board, player * -1)
            print_board(new_board)

            if check_win(new_board, player * -1):
                return player * -1
            if check_tie(new_board):
                return 0

        else:
            if self.it == 0:
                print("Bot goes first!")
                print("-" * 25)
            new_board = self._bot_turn(board, player * -1)
            print_board(new_board)

            if check_win(new_board, player * -1):
                return player * -1
            if check_tie(new_board):
                return 0

            new_board = self._human_turn(new_board, player)
            print_board(new_board)

            if check_win(new_board, player):
                return player
            if check_tie(new_board):
                return 0

        return new_board
Exemplo n.º 19
0
def main():
    board = Board()
    dice = board.throw_dice()
    color = "B"
    line = ""
    board.print_board()
    try:
        while True:
            if color == "B":
                dice = board.throw_dice()
                print("DICE: ", dice)
                i = 0
                while i < len(dice):
                    line = input("What to move " + str(dice[i]) + " places? (0 to switch dice)")
                    if int(line) == 0:
                        tmp = dice[0]
                        for i in range(len(dice) - 1):
                            dice[i] = dice[i + 1]
                        dice[len(dice) - 1] = tmp
                        continue
                    elif line == "exit":
                        return
                    pos = int(line)
                    if board.move_checker(color, pos, dice[i]):
                        i += 1
                    else:
                        print("Cannot move this, try again!")
                    board.print_board()
                color = OTHER[color]
            else:
                dice = board.throw_dice()
                print("DICE: ", dice)
                try:
                    if len(dice) == 2:
                        try:
                            board = copy.deepcopy(play(board, color, dice))
                        except:
                            board = copy.deepcopy(play(board, color, [dice[1], dice[0]]))
                        # print("Max: \n", play(board, color, dice).print_board())
                    elif len(dice) == 4:
                        board = copy.deepcopy(play(board, color, [dice[0], dice[1]]))
                        board = copy.deepcopy(play(board, color, [dice[2], dice[3]]))
                    board.print_board()
                    color = OTHER[color]
                except:
                    color = OTHER[color]
    except:
        print("End of game")
Exemplo n.º 20
0
def client():
    global START, END
    global REF, PLY1, PLY2
    global B, C, M

    global CLIENT
    CLIENT.connect((HOST, PORT))

    while True:
        message = ""
        message = int(CLIENT.recv(1024).decode("UTF-8"))
        print(message)

        if message < 0:
            break

        # first (not my turn)
        elif message == 0:
            print_board(B.board, B.color, B.mycolor)
            message = str(message)
            CLIENT.send(message.encode("UTF-8"))

        elif message == 1:
            print_board(B.board, B.color, B.mycolor)
            # TODO: change here
            mystone = B.person_choice()
            ####################
            B.move(mystone)
            message = str(tuple2int(mystone) + 100)
            M = tuple2int(mystone)
            CLIENT.send(message.encode("UTF-8"))

        # not first (not my turn)
        elif message < 100:
            if M != message:
                opstone = int2tuple(message)
                B.move(opstone)
            print_board(B.board, B.color, B.mycolor)
            if not the_end(B.board, B.color):
                message = str(message)
                CLIENT.send(message.encode("UTF-8"))

        # not first (my turn)
        elif message < 200:
            message = message % 100
            opstone = int2tuple(message)
            B.move(opstone)
            print_board(B.board, B.color, B.mycolor)

            if not the_end(B.board, B.color):
                # TODO: change here
                mystone = B.person_choice()
                ####################
                B.move(mystone)
                message = str(tuple2int(mystone) + 100)
                M = tuple2int(mystone)
                CLIENT.send(message.encode("UTF-8"))
        # win
        elif message < 10000:
            (_, b, w) = decode_result(message)
            print("Win!\n")
            print("black", b, " vs ", w, "white\n")
            print_board(B.board, B.color, B.mycolor)
            CLIENT.close()
            break
        # lose
        elif message < 20000:
            (_, b, w) = decode_result(message)
            print("Lose!\n")
            print("black", b, " vs ", w, "white\n")
            print_board(B.board, B.color, B.mycolor)
            CLIENT.close()
            break
        # draw
        elif message < 30000:
            (_, b, w) = decode_result(message)
            print("Draw!\n")
            print(b, " vs ", w, "\n")
            print_board(B.board, B.color, B.mycolor)
            CLIENT.close()
            break
        else:
            print("???\n")
            break
    CLIENT.close()
Exemplo n.º 21
0
def server0():
    global START, END
    global REF, PLY1, PLY2
    global B, C, M
    global PLAYER1, PLAYER2, PLAYER_OF_COLOR, COLOR_OF_PLAYER

    while True:
        #TODO: 初期化処理
        START = True
        END = False
        # PLAYER1 = None
        # PLAYER2 = None
        # REFEREE = None
        PLY1 = False
        PLY2 = False
        REF = True
        B = Board()
        TIME["player1"] = TIMELIMIT["player1"]
        TIME["player2"] = TIMELIMIT["player2"]
        ####
        while (PLAYER1 is None) or (PLAYER2 is None):
            pass
        # end while
        while True:
            if START:
                r = random.choice([True, False])
                PLY1 = True
                PLY2 = True
                REF = False
                START = False
                SOCKET_OF_PLAYER["player1"] = PLAYER1
                SOCKET_OF_PLAYER["player2"] = PLAYER2
                PLAYER_OF_COLOR["black"] = "player1" if r else "player2"
                PLAYER_OF_COLOR["white"] = "player2" if r else "player1"
                COLOR_OF_PLAYER["player1"] = "black" if r else "white"
                COLOR_OF_PLAYER["player2"] = "white" if r else "black"

                if r:
                    PLAYER1.send("1".encode("UTF-8"))
                    PLAYER2.send("0".encode("UTF-8"))
                else:
                    PLAYER1.send("0".encode("UTF-8"))
                    PLAYER2.send("1".encode("UTF-8"))
                # end else
                print_board(B.board, B.color, B.mycolor)
            elif END:
                b, w = (count_color(B.board,
                                    BLACK), count_color(B.board, WHITE))
                if b > w:
                    message = str(encode_result((1, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["black"]].send(
                        message.encode("UTF-8"))
                    message = str(encode_result((2, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["white"]].send(
                        message.encode("UTF-8"))
                    MATCH[PLAYER_OF_COLOR["black"]] += 1
                elif b < w:
                    message = str(encode_result((2, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["black"]].send(
                        message.encode("UTF-8"))
                    message = str(encode_result((1, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["white"]].send(
                        message.encode("UTF-8"))
                    MATCH[PLAYER_OF_COLOR["white"]] += 1
                else:
                    message = str(encode_result((3, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["black"]].send(
                        message.encode("UTF-8"))
                    message = str(encode_result((3, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["white"]].send(
                        message.encode("UTF-8"))
                    MATCH[PLAYER_OF_COLOR["none"]] += 1
                # end else
                break
            else:
                if PLY1 or PLY2:
                    continue
                if is_valid_move(B.board, B.color, M):
                    B.move(M)
                    print_board(B.board, B.color, B.mycolor)
                    if the_end(B.board, B.color):
                        message = str(tuple2int(M))
                        PLAYER1.send(message.encode("UTF-8"))
                        PLAYER2.send(message.encode("UTF-8"))
                        END = True
                    else:
                        if B.color == BLACK:
                            message = str(tuple2int(M) + 100)
                            SOCKET_OF_PLAYER[PLAYER_OF_COLOR["black"]].send(
                                message.encode("UTF-8"))
                            message = str(tuple2int(M))
                            SOCKET_OF_PLAYER[PLAYER_OF_COLOR["white"]].send(
                                message.encode("UTF-8"))
                        # end if
                        if B.color == WHITE:
                            message = str(tuple2int(M))
                            SOCKET_OF_PLAYER[PLAYER_OF_COLOR["black"]].send(
                                message.encode("UTF-8"))
                            message = str(tuple2int(M) + 100)
                            SOCKET_OF_PLAYER[PLAYER_OF_COLOR["white"]].send(
                                message.encode("UTF-8"))
                        # end if
                    # end if
                    REF = False
                    PLY1 = True
                    PLY2 = True
                else:
                    b, w = (count_color(B.board,
                                        BLACK), count_color(B.board, WHITE))
                    message = str(encode_result((0, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["black"]].send(
                        message.encode("UTF-8"))
                    message = str(encode_result((1, b, w)))
                    SOCKET_OF_PLAYER[PLAYER_OF_COLOR["white"]].send(
                        message.encode("UTF-8"))
                    break
                # end if
            # end if
        # end while
        while PLAYER1 or PLAYER2:
            pass
        #TODO: 終了処理
        print("reached!")
        match = MATCH["player1"] + MATCH["player2"] + MATCH["none"]
        if match >= MATCHNUMBER:
            print("player1 wins %d times, player2 wins %d times (draw %d)." %
                  (MATCH["player1"], MATCH["player2"], MATCH["none"]))
            break
Exemplo n.º 22
0
def main():
   board = Board(BoardType.BASE_EXP)
   print_board(board)
Exemplo n.º 23
0
def player_move(player, board_state):
    """
    Make a move according to the players
    :param player: The player that is playing now.
    :type player: an instance of the class Player in players
    :param board_state: The board that is played.
    :type board_state: nested list
    :return: the board after a move has been made.
    :rtype: nested list
    """
    move = True
    piece_kind = False
    piece_row, piece_column = 0, 0
    move_valid = False
    times_tried_to_make_a_move = 0
    final_board = None
    impossible_move_message = "You can't move like that :(\n" + \
                              "Please pick a different move, or choose to move a different piece."
    choose_another = False
    while move:

        while not piece_kind:
            move_valid = False
            piece_row, piece_column, piece_kind = player.choose_piece(
                board_state)

        while not move_valid:
            if piece_kind == player.pawn:
                the_chosen_move = player.choose_where_to_move_for_pawn()
                if the_chosen_move == ANOTHER_CHOICE:
                    move_valid = True
                    piece_kind = False
                    choose_another = True
                else:
                    final_board = player.pawn_move(the_chosen_move, piece_row,
                                                   piece_column, board_state)

            elif piece_kind == player.queen:
                horizontal_side, vertical_side, steps_num = player.choose_where_to_move_for_queen(
                )
                if horizontal_side == ANOTHER_CHOICE or vertical_side == ANOTHER_CHOICE or steps_num == ANOTHER_CHOICE:
                    move_valid = True
                    piece_kind = False
                    choose_another = True
                else:
                    final_board = player.queen_move(horizontal_side,
                                                    vertical_side, steps_num,
                                                    piece_row, piece_column,
                                                    board_state)

            if final_board is not None:
                return final_board
            elif choose_another:
                pass
            elif times_tried_to_make_a_move > 0:
                print(impossible_move_message)
                print_board(board_state)
                move_valid = False
            else:
                print(impossible_move_message)
                times_tried_to_make_a_move += 1
                move_valid = False
Exemplo n.º 24
0
def print_instruction():
	print "Use the cell number designations to make your move"
	print_board([2,3,4,5,6,7,8,9,10])
Exemplo n.º 25
0
                raise Exception
            word = raw_input("word?")
            return ((x,y), direction, word)
        except:
           pass 

myboard = board.make_board()
bag     = letters.initializebag()


players = [["Alice", [], False], ["Bob", [], False]]

while True:
        for player in players:
            letters.refillrack(player[1],bag)
            board.print_board(myboard)
            print "you are " + player[0]
            letters.printrack(player[1])
            player[2] == False

            while player[2] == False:
                passes = raw_input("Pass?")
                if 'y' in passes:
                    player[2] = True
                    continue
            
                (position, orientation, word) = prompt_for_move()
                try:
                    newboard = letters.make_move(myboard, word, position, orientation, player[1])
                    myboard = newboard
                    break
Exemplo n.º 26
0
import board
import sys

peices = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]


board.print_board(peices)

gameRunning = 1

while gameRunning == 1:
    move = raw_input("Player X: ")
    result = board.add_character_to_2d_array_with_linear_number(peices, move, "X")
    if result != 0:
        peices = result
        board.print_board(peices)
    else:
        print "bad boy. no stealing spots! you forfeit your turn."

    result = board.check_win(peices, "X")
    if result == 1:
        print "Player X wins"
        sys.exit()

    move = raw_input("Player O: ")
    result = board.add_character_to_2d_array_with_linear_number(peices, move, "O")

    if result != 0:
        peices = result
        board.print_board(peices)
    else:
Exemplo n.º 27
0
    print('Enter the input to the server')
    inp = input()

    data = get_data(inp)

    if data:
        send = send_data(data)

        if send:
            response = tcp_sock.recv(1024).decode("utf-8")

            sucess = get_response_status(response)

            if sucess:
                if args.debug:
                    bd.print_board()

                if response != 'you win':
                    shot = get_shot(response)
                    hit = bd.shot_ship(shot)

                    if hit:
                        ship_destroyed = bd.check_ship_destroyed(shot)

                        if ship_destroyed:
                            print('SHIP DESTROYED')
                            end_game = bd.check_end_game()
                            if end_game:
                                print('END OF GAME')
                                tcp_sock.close()
                else:
Exemplo n.º 28
0
def quit_game(board, msg):
    print_board(board)
    print msg
    quit()
Exemplo n.º 29
0
from board import Board, print_board_heading, print_board
from player import Player
from ship import Ship
import os

SHIP_INFO = [("Aircraft Carrier", 5), ("Battleship", 4), ("Submarine", 3),
             ("Cruiser", 3), ("Patrol Boat", 2)]

if __name__ == "__main__":
    aircraft_carrier = Ship("Aircraft Carrier", 5)
    battleship = Ship("Battleship", 4)
    submarine = Ship("Submarine", 3)
    cruiser = Ship("Cruiser", 3)
    patrol_boat = Ship("Patrol Boat", 2)

    player_name = raw_input("Player 1, enter your name: ")
    player1 = Player(1, player_name)
    player1_board = Board()
    player1_opponent_board = Board()
    print_board(player1_board.grid)
Exemplo n.º 30
0
def run_alphabeta():
    global best_move, white_heuristic, black_heuristic, is_white_turn_global, average_total_nodes, average_time_per_move
    global num_wins_white, num_wins_black

    start_time = time.time()

    #change these heuristics depending on which problem you're doing
    white_heuristic = custom_heuristic_offensive
    black_heuristic = custom_heuristic_defensive

    #run boardgame matches a certain number of times
    for i in range(num_simulations):
        reset()

        white_workers, black_workers = setup()
        winner = False
        is_white_turn_global = True
        moves = np.array(np.zeros((0, 2, 2)))

        game_time = time.time()

        while (not winner):
            best_move = None
            #print(utility, is_white_turn_global)
            utility = alpha_beta(white_workers, black_workers, 0,
                                 is_white_turn_global, -99999, -99999)

            #make the move
            white_workers, black_workers = make_move(white_workers,
                                                     black_workers,
                                                     is_white_turn_global,
                                                     best_move)
            winner, utility, winner_name = winner_exists(
                white_workers, black_workers)
            moves = np.insert(moves, len(moves), best_move, 0)

            is_white_turn_global = not is_white_turn_global
            #print_board(white_workers, black_workers)

        average_time_per_move += (time.time() - game_time) / len(moves)
        #The final state of the board (who owns each square) and the winning player.
        print_board(white_workers, black_workers)
        print("Winner: " + winner_name)
        print()

        #The number of opponent workers captured by each player, as well as the total number of moves required till the win.
        print("Pieces captured by white: " + str(16 - len(black_workers)))
        print("Pieces captured by black: " + str(16 - len(white_workers)))
        print("Number of moves: " + str(len(moves)))

        #update simulation variables
        if winner_name == 'white':
            num_wins_white += 1
        elif winner_name == 'black':
            num_wins_black += 1
        average_total_nodes += total_nodes / len(moves)

    print()
    print("=== SIMULATION RESULTS ===")
    print("Number of runs: " + str(num_simulations))
    print("White wins: " + str(num_wins_white),
          "Black wins: " + str(num_wins_black))
    print()
    #The total number of game tree nodes expanded by each player in the course of the game.
    print("Average white nodes expanded per game: " +
          str(white_nodes / num_simulations))
    print("Average black nodes expanded per game: " +
          str(black_nodes / num_simulations))
    print()
    #The average number of nodes expanded per move and the average amount of time to make a move.
    print("Average nodes expanded per move: " +
          str(average_total_nodes / num_simulations))
    print("Average time per move: " +
          str(average_time_per_move / num_simulations))
    print()

    end_time = time.time()
    print("Time: " + str(end_time - start_time))
    print("Average time per game: " +
          str((end_time - start_time) / num_simulations))
Exemplo n.º 31
0
 def make_move(self, board: list) -> int:
     print_board(board)
     return int(input("Enter position: "))
Exemplo n.º 32
0
def main():
    # creating boards for player1 and player2
    board1 = create_board()
    board2 = create_board()

    # input players' name
    player1_name = input('First players name: ')
    player2_name = input('Second players name: ')

    # creating ships on player1's board
    ship1_ver1 = gen_random_ship(board1, 4, "ver")
    ship1_ver2 = gen_random_ship(board1, 3, "ver")
    ship1_hor1 = gen_random_ship(board1, 2, "hor")
    ship1_hor2 = gen_random_ship(board1, 3, "hor")

    # creating ships on player2's board
    ship2_ver1 = gen_random_ship(board2, 4, "ver")
    ship2_ver2 = gen_random_ship(board2, 3, "ver")
    ship2_hor1 = gen_random_ship(board2, 3, "hor")
    ship2_hor2 = gen_random_ship(board2, 2, "hor")

    print_board(board1)

    while True:
        print("\033[1;34;40m \n")
        print(ship1_ver1)
        print(ship1_ver2)
        print(ship1_hor1)
        print(ship2_ver1)
        print(ship2_ver2)
        print(ship2_hor2)

        # board, guessing, hit count for player1
        player(board1, player1_name)
        print_board(board1)
        if hit_ship(board1, ship1_ver1, 4, "ver") \
           or hit_ship(board1, ship1_ver2, 3, "ver") \
           or hit_ship(board1, ship1_hor1, 2, "hor") \
           or hit_ship(board1, ship1_hor2, 3, "hor"):
            print("It was a boat")

        # end play for player1
        if all_fleet_hit(board1, 12):
            answer = input(
                "{} WIN. Game over \n New game? Y/N".format(player1_name))
            if answer == "Y":
                main()
            else:
                exit()

        # board, guessing, hit count for player2
        print("\033[0;32;47m \n")
        print_board(board2)
        player(board2, player2_name)
        print_board(board2)
        if hit_ship(board2, ship2_ver1, 4, "ver") \
           or hit_ship(board2, ship2_ver2, 3, "ver") \
           or hit_ship(board2, ship2_hor2, 2, "hor")\
           or hit_ship(board2, ship2_hor1, 3, "hor"):
            print("It was a boat")

        # end play for player2
        if all_fleet_hit(board2, 12):
            answer2 = input(
                "{} WIN. Game over \n New game? Y/N".format(player2_name))
            if answer2 == "Y":
                main()
            else:
                exit()
Exemplo n.º 33
0
def quit_game(board, msg):
	print_board(board)
	print msg 
	quit()
Exemplo n.º 34
0
                if score[0] >= maxEval[0]:
                    maxEval = score
                    maxEval[1] = move
            return maxEval
        else:
            minEval = [inf, None]

            for move in moves:
                new_board = deepcopy(board)
                row, col = move // 3, move % 3

                new_board[row][col] = player
                score = self.move_minimax(new_board, player * -1, depth + 1)

                if score[0] <= minEval[0]:
                    minEval = score
                    minEval[1] = move

            return minEval


if __name__ == "__main__":
    test_board = [[1, 1, 0], [-1, 1, 1], [0, -1, -1]]

    print_board(test_board)
    bot = Bot(player=1)

    best_move = bot.move_minimax(test_board, bot.player)

    print("Best move: ", best_move)
Exemplo n.º 35
0
def instructions():
    """
    Prints the instructions to the game.
    """
    pawn1 = Style.Foreground.red + "0" + Style.end
    pawn2 = Style.Foreground.blue + "0" + Style.end
    empty_cell = 0
    queen = Style.Foreground.red + "q" + Style.end

    regular_board = make_board(pawn1, pawn2, empty_cell)

    ex_board1 = [[pawn1, empty_cell, empty_cell, empty_cell],
                 [empty_cell, empty_cell, empty_cell, empty_cell],
                 [empty_cell, queen, empty_cell, empty_cell],
                 [empty_cell, empty_cell, empty_cell, pawn2]]

    print("The checkers board is 8 by 8. This is how it looks at the start:")
    print_board(regular_board)
    input("Press Enter to continue.")

    print("\n"
          "Each player has pieces in different color:\n" +
          Style.Foreground.blue + "Blue" + Style.end + " or " + Style.Foreground.red + "Red" + Style.end + ".\n"
          "There are two kinds of pieces: pawn-",
          pawn1, "and queen-", queen + ".\n"
          "A pawn that crosses the board and reaches the other players' side becomes a queen.")
    input("Press Enter to continue.")

    print("\n"
          "The rows in the board are marked in numbers. \n"
          "The columns in the board are marked in capital letters.\n"
          "Each piece is marked first by the row number and then by the column letter. \n"
          "for example:\n" +
          pawn1, "is in" + Style.Foreground.cyan + " 0A" + Style.end + ".\n" +
          queen, "is in" + Style.Foreground.cyan + " 2B" + Style.end + ".\n" +
          pawn2, "is in" + Style.Foreground.cyan + " 3D" + Style.end + ".\n")
    print_board(ex_board1)
    input("Press Enter to continue.")

    print("\n"
          "After choosing a piece you'll need to pick where to move. \n"
          "You can pick to move:", Style.Foreground.cyan + "left \\ right" + Style.end + ". \n"
          "You can also write",
          Style.Foreground.cyan + "l \\ r" + Style.end + " for short. \n"
          "It is also possible to write", Style.Foreground.cyan + "a \\ d" + Style.end + " respectively. \n" +
          Style.Foreground.red + "Clarification:\n" + Style.end +
          "left  is always: <---- \n"
          "right is always: ---->")
    input("Press Enter to continue.")

    print("\n"
          "of course if you choose a queen, you'll need also to choose how to move vertically. \n"
          "You can pick to move:", Style.Foreground.cyan + "up \\ down" + Style.end + ". \n"    
          "You can also write", Style.Foreground.cyan + "u \\ d" + Style.end + " for short. \n"
          "It is also possible to write", Style.Foreground.cyan + "w \\ s" + Style.end + " respectively. \n" +
          Style.Foreground.red + "Clarification: " + Style.end +
          "write the move correctly, otherwise, the computer won't understand your move! \n")
    input("Press Enter to continue.")

    print("\n"
          "Lastly - if you choose a queen - you'll need to chose the number of steps." +
          Style.Foreground.red + "Clarification: " + Style.end +
          "jumping over a pawn counts as two steps!")
    input("Press Enter to continue.")

    print("\n"
          "If you changed your mind and would like to move a different piece, "
          "simply write", Style.Foreground.cyan + "another" + Style.end + ".\n")
    input("Press Enter to continue.")
    print("\n\n\n")
Exemplo n.º 36
0
    rows = board.all_two_rows(b, letter) 
    for r in rows:  
        third = board.third_space(r[0][0], r[0][1], r[1][0], r[1][1])
        if third != None:
            row = [r[0], r[1], third]
            row.sort()
            print row

def test_winning_move(b):
    r = board.winning_move(b, "O")
    print r

def test_all_winning_moves(b, letter):
    r = board.all_winning_moves(b, letter)
    print r
   
def test_fork(b, letter):
    board.fork(b, letter) 

if __name__ == "__main__":
    b = [[0, 1, 2], [1, 0, 0], [0, 0, 2]]

    print "\nTesting with " + str(b) 
    board.print_board(b)
    board.fork(b, "X") 
    board.block(b, "O")
    board.win(b, "X")
    board.fork(b, "X")
    board.block(b, "O")
    board.win(b, "X")
Exemplo n.º 37
0
    sub = 1.0
    # .9,.7,.5,.3
    if empty == 3:
        sub = .9
    elif empty == 2:
        sub = .8
    elif empty == 1:
        sub = .7
    elif empty == 0:
        sub = .6
    return val * sub


board = board.Board()
board.print_board()
print()

while True:
    best_move = None
    best_alpha = float('-inf')
    moveset = ['up', 'down', 'left', 'right']
    for move in moveset:
        t = time.time()
        test = deepcopy(board)
        test.move_board(move)
        if np.array_equal(test.get_board(), board.get_board()):
            print("continuing...")
            continue
        alpha = expectimax(test, 4)
        if time.time() - t < .05: