我是编程新手。我试图编写一个简单的井字游戏,要求用户选择在哪里玩。我无法使用python来向乌龟发出“移动”指令。我到目前为止的代码如下。 (我刚刚在两周前开始学习)我创建了绘制函数,框架以及x和o。我现在正在尝试获取用户输入,以选择将x或o放置在何处。
Win32上的Python 3.7.4(tags / v3.7.4:e09359112e,2019年7月8日,19:29:22)[MSC v.1916 32位(Intel)]
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)
我在代码中看不到什么问题。
您有一些未知变量,可能应该是字符串-"x"
,"o"
input()
返回字符串,您应该将其赋给变量并与字符串进行比较。您无法比较input == o
,因为o
是您没有定义的变量,因为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)