у меня ошибка во время выполнения для tic tac toe, поскольку я не использовал никаких функций в этой программе, пожалуйста, один раз посмотрите на код

#python #runtime-error #tic-tac-toe

#python #ошибка во время выполнения #крестики-нолики

Вопрос:

я получаю ошибку при запуске этого кода, я уже делал это с помощью функций, но на этот раз я думал сделать это без функций, но есть какая-то ошибка, я даже не знаю, что мы можем сделать это в крестики-нолики вот так

 from IPython.display import clear_output
import random
print('WELCOME TO TIC TAC TOEn')
board= [' '] * 10
player2 = ' '
player_1 = None
player_2 = None
turn = player_1
clear_output()
print('     |   |  ')
print('   ' board[7] ' | ' board[8] ' | ' board[9])
print('     |   |  ')
print('---------------')
print('     |   |  ')
print('   ' board[4] ' | ' board[5] ' | ' board[6])
print('     |   |  ')
print('---------------')
print('     |   |  ')
print('   ' board[1] ' | ' board[2] ' | ' board[3])
print('     |   |  ')
marker = ''
while not (marker == 'X' or marker == 'O'):
    marker = input('player 1 do you want to be X or On').upper()
    
    if marker == "X":
        player1 = "X"
        player2 = "O"
    else:
        player1 = "O"
        player2 = "X"
      
if random.randint(0,1) == 0:
    print('player 1 will go first')
    turn=player_1
else:
    print('player 2 will go first')
    turn=player_2
    
win_check = False
if ((board[7]==player1 and board[8]==player1 and board[9]==player1) or #horizontal check
           (board[4]==player1 and board[5]==player1 and board[6]==player1) or #horizontal check
           (board[1]==player1 and board[2]==player1 and board[3]==player1) or #horizontal check
           (board[1]==player1 and board[4]==player1 and board[7]==player1) or #vertical check
           (board[2]==player1 and board[5]==player1 and board[8]==player1) or #vertical check
           (board[3]==player1 and board[6]==player1 and board[9]==player1) or #vertical check
           (board[1]==player1 and board[5]==player1 and board[9]==player1) or #diagonal check
           (board[3]==player1 and board[5]==player1 and board[7]==player1)):
    win_check=True
elif ((board[7]==player2 and board[8]==player2 and board[9]==player2) or #horizontal check
           (board[4]==player2 and board[5]==player2 and board[6]==player2) or #horizontal check
           (board[1]==player2 and board[2]==player2 and board[3]==player2) or #horizontal check
           (board[1]==player2 and board[4]==player2 and board[7]==player2) or #vertical check
           (board[2]==player2 and board[5]==player2 and board[8]==player2) or #vertical check
           (board[3]==player2 and board[6]==player2 and board[9]==player2) or #vertical check
           (board[1]==player2 and board[5]==player2 and board[9]==player2) or #diagonal check
           (board[3]==player2 and board[5]==player2 and board[7]==player2)):
    win_check=False
    
board_check = True
for i in range(1,10):
        if board[i] == ' ':
            board_check = True
        else:
            board_check = False
position = 0
gameon = True
while gameon == True:
    if turn == player_1:
        while position not in [1,2,3,4,5,6,7,8,9] or not board[i] == ' ':
            position = int(input("Enter the position (1-9)"))
            board[position] = player1
            if win_check == True:
                print("player1 WON!!")
                print('     |   |  ')
                print('   ' board[7] ' | ' board[8] ' | ' board[9])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   ' board[4] ' | ' board[5] ' | ' board[6])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   ' board[1] ' | ' board[2] ' | ' board[3])
                print('     |   |  ')              

                gameon = False
                break
            else:
                if board_check == False:
                    print('     |   |  ')
                    print('   ' board[7] ' | ' board[8] ' | ' board[9])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   ' board[4] ' | ' board[5] ' | ' board[6])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   ' board[1] ' | ' board[2] ' | ' board[3])
                    print('     |   |  ')
                    print('game is Draw')
                else:
                    turn = player_2
                    
    else:
         while position not in [1,2,3,4,5,6,7,8,9] or  not board[i] == ' ':
            position = int(input("Enter the position (1-9)"))
            board[position] = player2
            print("player2 WON!!")
            print('     |   |  ')
            print('   ' board[7] ' | ' board[8] ' | ' board[9])
            print('     |   |  ')
            print('---------------')
            print('     |   |  ')
            print('   ' board[4] ' | ' board[5] ' | ' board[6])
            print('     |   |  ')
            print('---------------')
            print('     |   |  ')
            print('   ' board[1] ' | ' board[2] ' | ' board[3])
            print('     |   |  ')
            if win_check == True:
                print("player2 WON!!")
                print('     |   |  ')
                print('   ' board[7] ' | ' board[8] ' | ' board[9])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   ' board[4] ' | ' board[5] ' | ' board[6])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   ' board[1] ' | ' board[2] ' | ' board[3])
                print('     |   |  ')
                gameon = False
            else:
                if board_check == False:
                    print('     |   |  ')
                    print('   ' board[7] ' | ' board[8] ' | ' board[9])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   ' board[4] ' | ' board[5] ' | ' board[6])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   ' board[1] ' | ' board[2] ' | ' board[3])
                    print('     |   |  ')

                    print('game is Draw')
                else:
                    turn = player_1

        
    replay = input('Do you wnt to play again? Y or N').lower()
    if replay == 'y':
        continue
    else:
        break

        



  

если бы вы могли помочь, это было бы очень полезно для меня, как для новичка
в программировании на Python
в этом коде я не могу выйти из цикла while, и он не показывает никакого результата

Комментарии:

1. Добавьте трассировку ошибки в вопрос.

2. Ваш код, который проверяет выигрыш, находится до того, как кто-либо сыграет, он не в цикле. Цикл, который устанавливает, board_check перезаписывает значение каждый раз через цикл, так что это просто значение из board[9] . while position not in [1,2,3,4,5,6,7,8,9] or not board[i] == ' ' следует использовать and , а не or .

Ответ №1:

В коде должны быть функции, win_check и board_check , чтобы вы могли перепроверять статус при каждом повороте.

Попробуйте этот код:

 def win_check():
    if ((board[7]==player1 and board[8]==player1 and board[9]==player1) or #horizontal check
               (board[4]==player1 and board[5]==player1 and board[6]==player1) or #horizontal check
               (board[1]==player1 and board[2]==player1 and board[3]==player1) or #horizontal check
               (board[1]==player1 and board[4]==player1 and board[7]==player1) or #vertical check
               (board[2]==player1 and board[5]==player1 and board[8]==player1) or #vertical check
               (board[3]==player1 and board[6]==player1 and board[9]==player1) or #vertical check
               (board[1]==player1 and board[5]==player1 and board[9]==player1) or #diagonal check
               (board[3]==player1 and board[5]==player1 and board[7]==player1)):
        return True
    elif ((board[7]==player2 and board[8]==player2 and board[9]==player2) or #horizontal check
               (board[4]==player2 and board[5]==player2 and board[6]==player2) or #horizontal check
               (board[1]==player2 and board[2]==player2 and board[3]==player2) or #horizontal check
               (board[1]==player2 and board[4]==player2 and board[7]==player2) or #vertical check
               (board[2]==player2 and board[5]==player2 and board[8]==player2) or #vertical check
               (board[3]==player2 and board[6]==player2 and board[9]==player2) or #vertical check
               (board[1]==player2 and board[5]==player2 and board[9]==player2) or #diagonal check
               (board[3]==player2 and board[5]==player2 and board[7]==player2)):
        return False
    
def board_check():
   for i in range(1,10):
        if board[i] == ' ':
            return True
        return False
  

В игровом цикле обратитесь к ним как к функциям:

 if win_check() .......
if board_check() .......