首页 > 解决方案 > 如何让乌龟遵循我的 IF 语句

问题描述

我是编程新手。我正在尝试编写一个简单的井字游戏,我要求用户选择在哪里玩。我无法让 python 允许我向乌龟发出“移动”指令。我到目前为止的代码如下。(我两周前才开始)我创建了绘制、框架、x 和 o 的函数。我现在正试图让用户输入来选择放置 x 或 o 的位置。

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32

def x_to_nine():
    tic.up()
    tic.left(140)
    tic.forward(16)
    tic.down()
    exx()


x9 = x_to_nine

print(input("Player 1 choose x or o: "))

def player1_choice(x, o):
    if input == x or o:
        print(input("Choose location."))
    if input == x9:
        x_to_nine()
    elif input != x:
        print("You can only choose x or o:")

player1_choice(x, o)

标签: python

解决方案


我在代码中看到了一些问题。

您几乎没有可能应该是字符串的未知变量 - "x""o"

input()返回字符串,您应该将其分配给变量并与字符串进行比较。您无法比较input == o,因为o它是您未定义 anb 的变量,因为input它是函数的名称并且它不保留用户答案。

answer = input("Player 1 choose x or o: ")
#answer = answer.strip().lower()

if answer == "x":
     # ... code ...

你应该把一个嵌套if在另一个if

   if text == "x" or text == "o":
        location = input("Choose location.")
        location = location.strip().lower()
        print(location)
        if location == "x9":
            x_to_nine()
    else:
        print("You can only choose x or o:")

您应该将用户的答案发送给功能。

def player1_choice(text):
    if text == "x" or text == "o":
       # code

# --- main ---

answer = input("Player 1 choose x or o (or exit): ")
player1_choice(answer)

它将从变量中获取字符串answer并赋值给变量text,然后您在函数中使用`text


# --- functions ---

def x_to_nine():
    tic.up()
    tic.left(140)
    tic.forward(16)
    tic.down()
    exx()

def player1_choice(text):

    if text == "x" or text == "o":
        location = input("Choose location.")
        location = location.strip().lower()
        print(location)
        if location == "x9":
            x_to_nine()
    else:
        print("You can only choose x or o:")

# --- main ---

while True:
    answer = input("Player 1 choose x or o (or exit): ")
    answer = answer.strip().lower()
    print(answer)

    if answer == "exit":
        break

    player1_choice(answer)

推荐阅读