【问题标题】:Python Not Exiting Tic Tac Toe GamePython 不退出井字游戏
【发布时间】:2017-07-18 21:22:45
【问题描述】:

我有一个非常基本的 Python 井字游戏。出于某种原因,当用户输入“e”时,游戏并没有退出。这是为什么呢?

import os
import sys
os.system("cls")

one = "1"
two = "2"
three = "3"
four = "4"
five = "5"
six = "6"
seven = "7"
eight = "8"
nine = "9"
selection = ""

def instructions():
    print("""
Welcome to Tic-Tac-Toe!
To Play, Enter a number between 1-9 to select that space
""")

def board():
    print("\t{} | {} | {}\n\t---------\n\t{} | {} | {}\n\t---------\n\t{} | {} | {}".format(one,two,three,four,five,six,seven,eight,nine))
    selection = input("\nSelect a number:\n")
    os.system("cls")

instructions()

while selection != "e":
    board()

【问题讨论】:

    标签: python tic-tac-toe


    【解决方案1】:

    原因很简单,棋盘中的选择变量和外面选中的不一样。

    快速解决方法是添加

    global selection
    

    在功能板的开头。 您应该考虑阅读 Python 中的变量范围。

    最终的代码将是

    def board():
        global selection
        print("\t{} | {} | {}\n\t---------\n\t{} | {} | {}\n\t---------\n\t{} | {} | {}".format(one,two,three,four,five,six,seven,eight,nine))
        selection = input("\nSelect a number:\n")
        os.system("cls")
    

    【讨论】:

    • 我在开头的 selection = "" 更改为 global selection = '" 但我有语法错误
    • 一开始选择的初始化已经是全局的了。您需要做的只是添加行“全局选择”作为板内的第一行。全局选择后不要写任何东西。只是。从下一行您可以更改 selection 的值,它将更改您在外部引用的相同选择。
    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2013-12-21
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多