首页 > 解决方案 > 如何获取tic tac toe python代码告诉用户他们选择的地方无效,需要选择1到9之间的空格

问题描述

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'"

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

标签: python

解决方案


你可以这样做:

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()

我添加try: except: pass到错误部分,所以如果输入不是数字,它将再次重复问题。


推荐阅读