Как завершить цикл while в функции, используя другую функцию.(Игра Крестики-нолики) - PullRequest
1 голос
/ 28 сентября 2019

Я пишу программу Tic Tac Toe на Python.Я сделал функции, чтобы напечатать доску, принять пользовательский ввод и фактически играть в игру (доска меняется с каждым вводом).Однако я не могу запустить свою функцию output(gboard) в своей основной функции exec(), чтобы завершить цикл while True:.Вот код:

def board(gboard):
    print("\n"*10)
    print(gboard[7]+'|'+gboard[8]+'|'+gboard[9])
    print(gboard[4]+'|'+gboard[5]+'|'+gboard[6])
    print(gboard[1]+'|'+gboard[2]+'|'+gboard[3])


def outcome(gboard):
    global ini
    if(gboard[1] == 'X') and (gboard[2] == 'X') and gboard[3] == 'X':
        print('Winner is X!')
        ini = 0
        return ini



def exec():
    move_counter = 0
    ini = 1
    winner = 'X'
    outcomes = ['X','O']

    print("Welcome to Tic Tac Toe!")
    print("Here's how the game works:\nEach number on the keypad represents a place on the table.")
    print("For example the number 1 stands for the box in column 1 row 3, while number 6 stands for column 3 row 2.")
    print("You will tell the computer where you wish to play using this system!")
    print("\n"*2+"Here is a visual representation of the board and the key numbers: ")
    print('7|8|9')
    print('4|5|6')
    print('1|2|3')
    print('If you wish to play X in the middle, you tell the computer to place X in position 5. Here is how a blank board will evolve:')
    print(' | | ')
    print(' |X| ')
    print(' | | ')
    print("So. Let's play!")

    player2 = None
    player1 = input('Player 1, would you like to be X or O(represents the letter)?: ')
    player1 = player1.upper()
    if(player1 == 'X'):
        player2 = 'O'
    else:
        player2 = 'X'
    print(f"Ok. Player 1 is {player1} and so that means that Player 2 is {player2}")


    gboard = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
    while True:
        move = int(input('Player 1, where would you like to play?: '))
        gboard[move] = player1
        move_counter += 1
        board(gboard)
        outcome(gboard)
        if(ini == 0) or move_counter == 9:
            break

        move2 = int(input('Player 2, where would you like to play?: '))
        gboard[move2] = player2
        move_counter += 1
        board(gboard)
        outcome(gboard)

        if(ini == 0) or move_counter == 9:
            break





    print('DONE!')
exec()

В этом коде я ввел только одно условие выигрыша, если в нижней строке все X - это то, что я использую для тестирования программы.Когда я запускаю программу и вхожу в нижний ряд с X, она печатает «Winner is X!»но не прерывает цикл.Однако, когда move_counter достигает 9, он прерывает цикл while.Вот исполнение:

  Welcome to Tic Tac Toe!
Here's how the game works:
Each number on the keypad represents a place on the table.
For example the number 1 stands for the box in column 1 row 3, while number 6 stands for column 3 row 2.
You will tell the computer where you wish to play using this system!


Here is a visual representation of the board and the key numbers:
7|8|9
4|5|6
1|2|3
If you wish to play X in the middle, you tell the computer to place X in position 5. Here is how a blank board will evolve:
 | |
 |X|
 | |
So. Let's play!
Player 1, would you like to be X or O(represents the letter)?: X
Ok. Player 1 is X and so that means that Player 2 is O
Player 1, where would you like to play?: 1
 | |
 | |
X| |
Player 2, where would you like to play?: 4
 | |
O| |
X| |
Player 1, where would you like to play?: 2
 | |
O| |
X|X|
Player 2, where would you like to play?: 5
 | |
O|O|
X|X|
Player 1, where would you like to play?: 3
 | |
O|O|
X|X|X
Winner is X!
Player 2, where would you like to play?:

Я не ожидаю, что программа спросит игрока 2, где они хотели бы сыграть после определения победителя.Почему моя функция результата не выходит из цикла while?

Ответы [ 4 ]

1 голос
/ 28 сентября 2019

Кажется, ваша переменная ini в вашей функции exec отличается от переменной ini от функции outcome (одна локальная, а другая глобальная переменная).Вы можете это исправить, просто объявив ini в exec функции в качестве глобальной переменной, например:

def exec():
    move_counter = 0
    global ini <------- here
    ini = 1
    winner = 'X'
    outcomes = ['X','O']

Удачи!

0 голосов
/ 28 сентября 2019

Вы должны поместить ini var как глобальную переменную .

Попробуйте поставить его в начале, вне области действия метода, и импортировать global ini внутри них.


ini = None # <--- declare ini as global without value  

def board(gboard):
    print("\n"*10)
    print(gboard[7]+'|'+gboard[8]+'|'+gboard[9])
    print(gboard[4]+'|'+gboard[5]+'|'+gboard[6])
    print(gboard[1]+'|'+gboard[2]+'|'+gboard[3])


def outcome(gboard):
    global ini
    if(gboard[1] == 'X') and (gboard[2] == 'X') and gboard[3] == 'X':
        print('Winner is X!')
        ini = 0
        return ini



def exec():
    global ini # <--- import ini global in this scope
    move_counter = 0
    ini = 1
    winner = 'X'
    outcomes = ['X','O']

    print("Welcome to Tic Tac Toe!")
    print("Here's how the game works:\nEach number on the keypad represents a place on the table.")
    print("For example the number 1 stands for the box in column 1 row 3, while number 6 stands for column 3 row 2.")
    print("You will tell the computer where you wish to play using this system!")
    print("\n"*2+"Here is a visual representation of the board and the key numbers: ")
    print('7|8|9')
    print('4|5|6')
    print('1|2|3')
    print('If you wish to play X in the middle, you tell the computer to place X in position 5. Here is how a blank board will evolve:')
    print(' | | ')
    print(' |X| ')
    print(' | | ')
    print("So. Let's play!")

    player2 = None
    player1 = input('Player 1, would you like to be X or O(represents the letter)?: ')
    player1 = player1.upper()
    if(player1 == 'X'):
        player2 = 'O'
    else:
        player2 = 'X'
    print(f"Ok. Player 1 is {player1} and so that means that Player 2 is {player2}")


    gboard = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
    while True:
        move = int(input('Player 1, where would you like to play?: '))
        gboard[move] = player1
        move_counter += 1
        board(gboard)
        outcome(gboard)
        if(ini == 0) or move_counter == 9:
            break

        move2 = int(input('Player 2, where would you like to play?: '))
        gboard[move2] = player2
        move_counter += 1
        board(gboard)
        outcome(gboard)

        if(ini == 0) or move_counter == 9:
            break





    print('DONE!`enter code here`')
exec()
0 голосов
/ 28 сентября 2019

Почему моя функция результата не выходит из цикла while?

Поскольку ini по-прежнему равно 1. Ваша основная функция имеет локальную переменную с именем ini, поэтому, даже если вы установите глобальное значение ini из outcome, оно будет проигнорировано.

Вы не должны использовать глобальную переменную для этого.У вас правильная идея с return ini.Однако вызывающий код не заботится об этом имени - он заботится только о значении .Когда вы звоните outcome и Х выиграл, он будет return значение 0.Вам следует присвоить это:

ini = outcome(gboard)

Следующим шагом является то, что outcome необходимо вернуть значение, даже если X не победил.(И, конечно же, вы должны проверить другие способы, в которых Х может выиграть и О может победить.) Вы можете использовать несколько различных значений, чтобы указать, кто выиграл, или следует ли продолжить игру.

0 голосов
/ 28 сентября 2019

Вы устанавливаете в exec () ini = 1, поэтому, даже если оно установлено равным 0 при выигрыше, оно снова будет равно 1.Вы можете удалить ini = 1 из вашего exec и объявить его выше всех методов, так что он будет иметь значение 1, когда игра начнется, и будет просто установлен в 0, когда он закончится.

...