Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python程序在if语句后不返回函数_Python 3.x - Fatal编程技术网

Python 3.x Python程序在if语句后不返回函数

Python 3.x Python程序在if语句后不返回函数,python-3.x,Python 3.x,我正在编写一个Python Tic-Tac-Toe bot,它在一个if语句后一直停止,而不是重新启动函数(下面的代码)。我是Python的初学者,希望有更简单的答案 代码: 将函数放入while循环中 while True: process() 然后在你的函数中,当赢得比赛的条件达到时,放一个中断,这样就结束了循环。你不应该在每次if-elif循环后使用return。而是将其分配给一个变量,然后为每个循环增加该变量。每个def仅返回一个return: def some_functio

我正在编写一个Python Tic-Tac-Toe bot,它在一个
if
语句后一直停止,而不是重新启动函数(下面的代码)。我是Python的初学者,希望有更简单的答案

代码:


将函数放入while循环中

while True:
    process()

然后在你的函数中,当赢得比赛的条件达到时,放一个中断,这样就结束了循环。

你不应该在每次
if
-
elif
循环后使用
return
。而是将其分配给一个变量,然后为每个循环增加该变量。每个
def
仅返回一个
return

def some_function(x, y):
    x = []
    y = "Some String"
    x.append(y)
    return y

从你的代码中我可以看到,你正在处理3个不同的“哪里是开放点”列表。我认为,在选择放置地点之前,只需管理一个列表,并获得“开放”的位置会更容易

您试图调用同一个函数本身-这将导致每个函数调用都有大量的堆栈帧(python通过准备“变量堆栈”来隔离函数调用)该函数的内存区域在您离开该函数后被清理。如果您的函数递归调用自身-它们会累积并阻塞计算机内存)-大多数情况下,最好避免这种情况,并使用循环进行非递归编码

一块板自然会产生一个2维列表,你也可以选择用字母和1-索引来表示它,这会导致列表中的索引和“输出”之间的一些来回计算

我添加了一些做某些事情的函数(返回所有未使用的空格、设置空格、漂亮地打印电路板、检查wins):

主程序

import random

# prepare the empty field with spaces - it is the only list to tend to
field = [[" "," "," "],[" "," "," "],[" "," "," "]]
player = ""
# get all fields that are still open
open_fields = list(getFieldsNotUsed(field)) 

# loop while open fields are present
while open_fields:
    # toggle the player from "" (at start) to X, then from X to O and back
    player = "X" if player != "X" else "O"

    # choose randomly, set player, print field
    place_where = random.choice(open_fields)
    setField(player, place_where,field)
    printField(field)     

    # check win-conditions, continue loop if None else break
    win = checkWin(field)
    if win is None:
        open_fields = list(getFieldsNotUsed(field))
    else:
        # we got a winner - print it and exit loop
        print(win)
        break
else:
    print("Draw")


您可以在此处找到大多数使用函数(
ord
chr
int
范围
zip
)的文档:

了解
返回过程
返回过程()之间的区别很重要:

返回过程
不会执行任何操作,它只会退出函数,结果是对过程函数的引用。您的最后一行可以像
result=process()
那样使用它,然后您可以在该结果上循环,并且您可以在游戏结束时通过返回None而不是函数退出应用程序

returnprocess()
将执行process()函数并返回自己的结果。你会不止一次地进入函数,但这意味着它将开始链接对函数的调用,并在游戏结束时链接退出所有函数。对于tic-tac-toe,它应该可以工作,但对于更复杂的东西,这可能会导致堆栈溢出


正确的方法是在调用process()时有一个循环,而不必麻烦返回进程本身。

这个游戏玩的时候没有playerinteraction吗?
进程本身就是函数,只返回函数不会执行它。因此,将所有的
返回过程
替换为
返回过程()
,您应该解决“我的函数在1次迭代后停止”的问题。然而,这并不意味着你的代码是没有bug的,但这一个尤其会消失。
ordA = ord("A")  # get the ascii value of A so we can compute the letter by the list-index

def getFieldsNotUsed(f):
    """Return all possible fields that are empty (if .strip()ed)"""
    for r_idx,row in enumerate(field):
        for c_idx,col in enumerate(row):
            if col.strip() == "":
                # get the letter that belongs to "A" + the 0bases list index
                yield chr(ordA+r_idx)+str(c_idx+1)

def setField(player,coord,f):
    """Places player (X or O) at coord [A1,A2,A3,B1,B2,B3,C1,C2,C3]-string"""
    print(f"{player} sets at {coord}:\n")
    r_idx = ord(coord[0])-ordA # compute the list index for row 
    c_idx = int(coord[1])-1    # colum is easier, just int-ify the string and subtract 1
    f[r_idx][c_idx]=player

def printField(f):
    """Pretty prints the field given by f"""
    middle = 2
    for r in f:
        print("\t " + " | ".join( r ))
        if middle: # 0 is False
            print("\t" + "---|---|---")
            middle -= 1
    print("\n")

def checkWin(f):
    """Retunrs a winner-string or None - checks all rows && columns && both diagonals"""
    # check rows
    for r in f:
        if all( v == r[0] and v.strip() for v in r):
            return f"{r[0]} won!"
    # check cols
    for c in zip(*f):
        if all( v == c[0] and v.strip() for v in c):
            return f"{r[0]} won!"
    # check diag
    if (f[0][0] == f[1][1] == f[2][2] or 
        f[0][2] == f[1][1] == f[2][0]) and f[1][1].strip() :
        return f"{r[0]} won!"

    return None # no wins
import random

# prepare the empty field with spaces - it is the only list to tend to
field = [[" "," "," "],[" "," "," "],[" "," "," "]]
player = ""
# get all fields that are still open
open_fields = list(getFieldsNotUsed(field)) 

# loop while open fields are present
while open_fields:
    # toggle the player from "" (at start) to X, then from X to O and back
    player = "X" if player != "X" else "O"

    # choose randomly, set player, print field
    place_where = random.choice(open_fields)
    setField(player, place_where,field)
    printField(field)     

    # check win-conditions, continue loop if None else break
    win = checkWin(field)
    if win is None:
        open_fields = list(getFieldsNotUsed(field))
    else:
        # we got a winner - print it and exit loop
        print(win)
        break
else:
    print("Draw")