猫史档案馆


【Python作品分享】井字棋

用户:内向的疾风雀3FPu内向的疾风雀3FPu查看:0 回复:0 评论:0 创建时间:2024-07-07T15:51:29


【作品展示】

center_image

 

【作品介绍】

1~9整数下棋

 

【作品源代码】

# 定义棋盘,初始化为空格  
board = [' ' for _ in range(9)]  
  
# 显示棋盘当前状态  
def display_board():  
    print(f"{board[0]} | {board[1]} | {board[2]}")  
    print("---------")  
    print(f"{board[3]} | {board[4]} | {board[5]}")  
    print("---------")  
    print(f"{board[6]} | {board[7]} | {board[8]}")  
  
# 检查游戏是否有赢家  
def check_win(symbol):  
    win_conditions = [  
        [0, 1, 2],  
        [3, 4, 5],  
        [6, 7, 8],  
        [0, 3, 6],  
        [1, 4, 7],  
        [2, 5, 8],  
        [0, 4, 8],  
        [2, 4, 6]  
    ]  
    for condition in win_conditions:  
        if board[condition[0]] == symbol and board[condition[1]] == symbol and board[condition[2]] == symbol:  
            return True  
    return False  
  
# 检查棋盘是否已满  
def check_draw():  
    return ' ' not in board  
  
# 玩家放置标记  
def place_marker(symbol):  
    while True:  
        try:  
            position = int(input(f"Player {symbol}, choose your position (1-9): ")) - 1  
            if board[position] == ' ':  
                board[position] = symbol  
                break  
            else:  
                print("This position is already taken.")  
        except ValueError:  
            print("Please enter a valid number.")  
        except IndexError:  
            print("Please enter a number within the range.")  
  
# 游戏主循环  
def play_game():  
    turn = 0  
    while True:  
        display_board()  
        place_marker('X' if turn % 2 == 0 else 'O')  
        if check_win('X' if turn % 2 == 0 else 'O'):  
            display_board()  
            print(f"Player {'X' if turn % 2 == 0 else 'O'} wins!")  
            break  
        if check_draw():  
            display_board()  
            print("It's a draw!")  
            break  
        turn += 1  
  
play_game()

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页