如何让tic-tac-toe python代码告诉用户他们选择的位置无效,需要选择1到9之间的空格

2024-07-04 07:43:51 发布

您现在位置:Python中文网/ 问答频道 /正文

theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
           '4': ' ' , '5': ' ' , '6': ' ' ,
           '1': ' ' , '2': ' ' , '3': ' ' }
 
board_keys = []
 
for key in theBoard:
   board_keys.append(key)

#这将在游戏中每次移动后打印更新的棋盘

def printBoard(board):
    print(board['7'] + ' |' + board['8'] + ' |' + board['9'])
    print('--+--+--')
    print(board['4'] + ' |' + board['5'] + ' |' + board['6'])
    print('--+--+--')
    print(board['1'] + ' |' + board['2'] + ' |' + board['3'])

#这将告诉用户,当他们键入无效输入时,可以选择1到9之间的输入。 def game():

   turn = 'X'
   count = 0
   # this prints that its x's or o's turn now and asks where they want to move to.
   for i in range(0, 10 ):
       printBoard(theBoard)
       print("It's your turn " + turn + "  please choose a number between 1 and 9")
       move = input()       
       
       if theBoard [move] == ' ':
           theBoard [move] = turn
           count += 1
       
       else:
           print("this place is already filled " + turn + " where do you want to move to?")
       
           # Now we will check if player X or O has won,for every move after 5 moves. 
       if count >= 5:
           if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # this goes across the top
               printBoard(theBoard)
               print("\ngame ooover\n")               
               print(" yipee " +turn + " won! yoohooo")               
               break
           elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # this goes across the middle
               printBoard(theBoard)
               print("\ngame oooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
           elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # this goes across the bottom
               printBoard(theBoard)
               print("\ngame ooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
           elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # this goes down the left side
               printBoard(theBoard)
               print("\ngame ooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
           elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # this goes down the middle
               printBoard(theBoard)
               print("\ngame ooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
           elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # this goes down the right side
               printBoard(theBoard)
               print("\ngame oooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
           elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # this goes diagonal
               printBoard(theBoard)
               print("\ngame ooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
           elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # this goes diagonal
               printBoard(theBoard)
               print("\ngame ooover\n")               
               print(" yipee " +turn + " won! yoohooo")
               break
             # \n means create a new line asking the question. 
             # if neither X nor O wins and the board is full, we'll declare the result as 'tie' because well its a tie.
       if count == 9:
           print("\nGame Over\n")               
           print("It's a Tie!!")
           break 
 
        # now we have to change the player after every move so that each player gets a turn.
       if turn =='X':
           turn = 'O'
       else:
           turn = 'X'       
  

现在我们将询问玩家是否希望重新启动游戏,如果是,则游戏将重新启动并再次打印棋盘,如果不是,则游戏将在此结束

   restart = input("would you like to play Again?(yup/nah)")
   if restart == "yup" or restart == "Yup": 
       for key in board_keys:
           theBoard[key] = " "
 
       game()


if __name__ == "__main__":
   game()

这是我所有的代码。每当我输入一个不在1到9之间的数字时,它就会断开并这样说“

Traceback (most recent call last):
  File "main.py", line 123, in <module>
    game()
  File "main.py", line 51, in game
    if theBoard [move] == ' ':
KeyError: '0'"

我试过很多方法,但似乎找不到解决问题的正确方法


Tags: theboardmoveifthisturnprintbreak
2条回答

确保move变量是int变量类型。它可能是一个字符串,需要转换为int,以便您可以将其用作电路板的索引

下面是一个你可以做到这一点的例子。创建函数getMove()

def getMove():
  got_move = False

  while got_move is False:
    move = input("Enter a number 1-9: ")

    if move.isdigit():
      move = int(move)

      if move <= 9 and move >= 1:
        got_move = True
      else:
        print("\n*** move is out of bounds. Numbers 1-9 only ***\n")
    else:
      print("\n*** Invalid input. Numbers 1-9 only ***\n")

  return move

然后更改分配“移动”的代码,如下所示:

move = getMove()

您可以这样做:

theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
           '4': ' ' , '5': ' ' , '6': ' ' ,
           '1': ' ' , '2': ' ' , '3': ' ' }
 
board_keys = []
 
for key in theBoard:
   board_keys.append(key)
#this will print the updated board after every move in the game.

def printBoard(board):
    print(board['7'] + ' |' + board['8'] + ' |' + board['9'])
    print(' + + ')
    print(board['4'] + ' |' + board['5'] + ' |' + board['6'])
    print(' + + ')
    print(board['1'] + ' |' + board['2'] + ' |' + board['3'])
#this will tell the user when they type an invalid input to choose an input specifically between 1 to 9. def game():

turn = 'X'   
count = 0
# this prints that its x's or o's turn now and asks where they want to move to.
for i in range(0, 10 ):
    printBoard(theBoard)
    print("It's your turn " + turn + "  please choose a number between 1 and 9")
    move = input()       
    try: #here
        if str(theBoard[move]) == ' ':
            theBoard[move] = turn
            count += 1
    except KeyError: #here
        pass #here
        
       
    else:
        print("this place is already filled " + turn + " where do you want to move to?")
       
           # Now we will check if player X or O has won,for every move after 5 moves. 
    if count >= 5:
        if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # this goes across the top
            printBoard(theBoard)
            print("\ngame ooover\n")               
            print(" yipee " +turn + " won! yoohooo")               
            break
        elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # this goes across the middle
            printBoard(theBoard)
            print("\ngame oooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # this goes across the bottom
            printBoard(theBoard)
            print("\ngame ooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # this goes down the left side
            printBoard(theBoard)
            print("\ngame ooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # this goes down the middle
            printBoard(theBoard)
            print("\ngame ooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # this goes down the right side
            printBoard(theBoard)
            print("\ngame oooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # this goes diagonal
            printBoard(theBoard)
            print("\ngame ooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # this goes diagonal
            printBoard(theBoard)
            print("\ngame ooover\n")               
            print(" yipee " +turn + " won! yoohooo")
            break
        # \n means create a new line asking the question. 
             # if neither X nor O wins and the board is full, we'll declare the result as 'tie' because well its a tie.
        if count == 9:
            print("\nGame Over\n")               
            print("It's a Tie!!")
            break 
 
        # now we have to change the player after every move so that each player gets a turn.
        if turn =='X':
            turn = 'O'
        else:
            turn = 'X'       
  
# now we will ask if player wants to restart the game or not, if yes then the game will restart and print the board again, if not then the game will end there.
restart = input("would you like to play Again?(yup/nah)")
if restart == "yup" or restart == "Yup": 
    for key in board_keys:
       theBoard[key] = " "
 
       game()


if __name__ == "__main__":
   game()

我将^{}添加到错误部分,因此如果输入不是数字,它将再次重复该问题

相关问题 更多 >

    热门问题