【问题标题】:Cannot get my tic-tac-toe game to run correctly in python无法让我的井字游戏在 python 中正确运行
【发布时间】:2019-08-05 05:03:26
【问题描述】:

我为一个用 python 编写的井字游戏编写了代码。我完全按照这些步骤操作,但我认为该游戏是专门为 Jupyter 笔记本编写的,因为它在真正的 Python 解释器中无法正常工作(我在 VS 代码中写出了所有代码)。它随机分配哪个玩家先走,哪个玩家应该先走,但该玩家的标记没有正确分配,另一个玩家永远无法移动。此外,移动的玩家,无论何时选择顶行的位置(索引 7-9),都将自动获胜。

这是在 Python 3 中。我尝试过调试,但代码在语法上是有效的,所以我无法查明它的逻辑问题。

def display_board(board):  # Board setup
  print('\n'*100)
  print(board[7] + '|' + board[8] + '|' + board[9])
  print(board[4] + '|' + board[5] + '|' + board[6])
  print(board[1] + '|' + board[2] + '|' + board[3])

def player_input():  # Player assignment - use while loop to keep asking until a valid character is entered

    marker = ''
    while marker != 'X' and marker != 'O':
        marker = input('Player1: Choose X or O: ').upper()

    if marker == 'X':
        return ('X','O')
    else:
        return ('O','X')

def place_marker(board, marker, position):   # Allows player to place their marker at specific board index

    board[position] = marker

def win_check(board, mark):  # Check all rows, columns, diagonals for sharing the same marker to check for a winner
    return ((board[1] and board[2] and board[3] == mark) or   # Rows
    (board[4] and board[5] and board[6] == mark) or
    (board[7] and board[8] and board[9] == mark) or
    (board[1] and board[4] and board[7] == mark) or   # Columns
    (board[2] and board[5] and board[8] == mark) or
    (board[3] and board[6] and board[9] == mark) or
    (board[1] and board[5] and board[9] == mark) or   # Diagonals
    (board[3] and board[5] and board[7] == mark))

import random

def choose_first():  # Randomize who goes first

    flip = random.randint(0,1)
    if flip == 0:
        return 'Player 1'
    else:
        return 'Player 2'

def space_check(board, position):   # Check to see if a space on the board is still available
   return board[position] == ' '

def full_board_check(board):  # Checks to see if board is full resulting in a draw
    for i in range(1,10):
        if space_check(board,i):  # If there is free space, board is NOT full
            return False
    return True

def player_choice(board):  # Asks for the player's next move choice
    position = 0

    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        position = int(input('Choose a position: (1-9): '))

    return position

def replay():   # Asks if the players want to play again
    choice = input("Play again? Enter Yes or No: ")
    return choice == 'Yes'

# Logic to run the game
# While loop needed to keep running the game
# Need to break out of the while loop on replay()

print ('Welcome to TIC TAC TOE')

while True:
    # Game Setup (Board, Players, Player turns)
    the_board = [' ']*10
    player1_marker,player2_marker = player_input()

    turn = choose_first()
    print(turn + ' will go first')

    play_game = input('Ready to play? y or n: ')
    if play_game == 'y':
        game_on = True
    else: game_on = False

    # Game Play
    while game_on:
        if turn == 'Player1':
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player1_marker,position)

            # Check if they won
            if win_check(the_board,player1_marker):
                display_board(the_board)
                print('PLAYER 1 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):  # Check for tie
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 2'

        else:   
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player2_marker,position)

            # Check if they won
            if win_check(the_board,player2_marker):
                display_board(the_board)
                print('PLAYER 2 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 1' 

    if not replay():
        break

我希望游戏在每个玩家之间来回切换,并分配给他们正确的标记,但我无法弄清楚为什么没有发生这种情况,因为它看起来对我来说是正确的。

【问题讨论】:

  • 你的代码太复杂了。尝试使用简单的二维矩阵作为电路板。我敢肯定,一旦您将事情简化一点,您就会发现问题,对于没有编写代码的人来说,这将更加困难。

标签: python tic-tac-toe


【解决方案1】:

转牌没有正确转到“玩家 1”的原因是您在该玩家的检查中缺少一个空格。您也没有正确检查玩家何时获胜,这就是为什么您会出现这种奇怪的顶行行为。您需要检查每个位置,而不仅仅是最后一个。我还添加了对用户输入的检查,以确保用户输入的是数字,否则不会崩溃。

我完全不明白为什么你基本上是把你的电路板颠倒打印出来的,但我把它留了下来。

试试这个:

import random

def display_board(board):  # Board setup
  print('\n'*100)
  print(board[7] + '|' + board[8] + '|' + board[9])
  print(board[4] + '|' + board[5] + '|' + board[6])
  print(board[1] + '|' + board[2] + '|' + board[3])

def player_input():  # Player assignment - use while loop to keep asking until a valid character is entered

    marker = ''
    while marker != 'X' and marker != 'O':
        marker = input('Player1: Choose X or O: ').upper()

    if marker == 'X':
        return ('X','O')
    else:
        return ('O','X')

def place_marker(board, marker, position):   # Allows player to place their marker at specific board index

    board[position] = marker

def win_check(board, mark):  # Check all rows, columns, diagonals for sharing the same marker to check for a winner
    return ((board[1] == mark and board[2] == mark and board[3] == mark) or   # Rows
    (board[4] == mark and board[5] == mark and board[6] == mark) or
    (board[7] == mark and board[8] == mark and board[9] == mark) or
    (board[1] == mark and board[4] == mark and board[7] == mark) or   # Columns
    (board[2] == mark and board[5] == mark and board[8] == mark) or
    (board[3] == mark and board[6] == mark and board[9] == mark) or
    (board[1] == mark and board[5] == mark and board[9] == mark) or   # Diagonals
    (board[3] == mark and board[5] == mark and board[7] == mark))

def choose_first():  # Randomize who goes first
    flip = random.randint(0,1)
    if flip == 0:
        return 'Player 1'
    else:
        return 'Player 2'

def space_check(board, position):   # Check to see if a space on the board is still available
   return board[position] == ' '

def full_board_check(board):  # Checks to see if board is full resulting in a draw
    for i in range(1,10):
        if space_check(board,i):  # If there is free space, board is NOT full
            return False
    return True

def player_choice(board):  # Asks for the player's next move choice
    position = 0

    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        try:
            position = int(input('Choose a position: (1-9): '))
        except:
            print("Please enter a valid number.")

    return position

def replay():   # Asks if the players want to play again
    choice = input("Play again? Enter Yes or No: ")
    return choice == 'Yes'



# Logic to run the game
# While loop needed to keep running the game
# Need to break out of the while loop on replay()

print ('Welcome to TIC TAC TOE')

while True:
    # Game Setup (Board, Players, Player turns)
    the_board = [' ']*10
    player1_marker,player2_marker = player_input()

    turn = choose_first()
    print(turn + ' will go first')

    play_game = input('Ready to play? y or n: ')
    if play_game == 'y':
        game_on = True
    else: game_on = False

    # Game Play
    while game_on:
        if turn == 'Player 1':
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player1_marker,position)

            # Check if they won
            if win_check(the_board,player1_marker):
                display_board(the_board)
                print('PLAYER 1 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):  # Check for tie
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 2'

        else:   
            # Show the board
            display_board(the_board)
            # Choose a place to move
            position = player_choice(the_board)
            # Place the marker on the position
            place_marker(the_board,player2_marker,position)

            # Check if they won
            if win_check(the_board,player2_marker):
                display_board(the_board)
                print('PLAYER 2 HAS WON!')
                game_on = False
            else:
                if full_board_check(the_board):
                    display_board(the_board)
                    print("TIE GAME!")
                    game_on = False
                else:
                    turn = 'Player 1' 

    if not replay():
        break

【讨论】:

  • 哇,我以为我通过在每个索引后不包括“==mark”来简化事情,我感觉某处存在间距问题。谢谢您的帮助!至于为什么我的板子被“倒置”打印出来,只是为了让它像键盘上的小键盘,这样玩的人可以把它作为更好的参考。
  • @alex_a 我明白了。好吧,如果您的问题得到解决,请将我的答案标记为正确!
【解决方案2】:

你的问题是它不改变转弯是由于一个错字:你设置了turn = 'Player 1',然后检查if turn == 'Player1'(没有空格)。您即时获胜的另一个错误是由于具有(board[1] and board[2] and board[3] == mark) 之类的比较部分。这不起作用,因为board[1]board[2] 被转换为布尔值True(因为它们是' ' 而不是'')。您需要使用(board[1] == mark and board[2] == mark and board[3] == mark),或更简洁的all(board[i] == mark for i in (1,2,3))

【讨论】:

  • 啊,我感觉有间距问题导致我无法弄清楚在哪里。而且那个 for 循环更简洁,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2015-12-30
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多