首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择位置函数在Tac脚趾游戏中不起作用

选择位置函数在Tac脚趾游戏中不起作用
EN

Stack Overflow用户
提问于 2022-06-16 13:54:10
回答 1查看 51关注 0票数 -1

我使用python制作了一个that游戏,所以我在choose_position()函数中遇到了问题,它可以根据玩家选择的数字(1比9)设置行和插槽,但是行和槽总是0,所以它总是第一个列表中的第一个组件,不会改变,我也不知道为什么。

下面是用户选择5(所以行应该等于1,槽等于2)但仍然行和槽都是0的例子:

代码语言:javascript
复制
from tabnanny import check


board = [["-","-","-"],["-","-","-"],["-","-","-"]]
def print_board(board):
    for  row in board:
        for slot in row:
            print(f"{slot}",end=" ")
        print()

def current_user(user):
    if user: return "x"
    else:return "o"

def choose_position(choice,row,slot):
    print("this is choice:",choice,type(choice))#just checking the choice value and type
    if choice in [1,2,3]:
        row = 0
        slot = choice-1
    elif choice in [4,5,6]:
        row = 1
        slot = choice-4
    elif choice in [7,8,9]:
        row = 2
        slot = choice -7

def limit(choice):
    if int(choice)>9 or int(choice)<1:
        print("please enter a number between 1 and 9 if you would be so good")
        return True
    else: return False

def isnum(choice):
    if not choice.isnumeric():
        print("Please enter a valid number if you would be so good")
        return True
    else: return False

def check_input(choice):
    if isnum(choice): return True
    if limit(choice): return True
    return False

def quit(choice):
    if choice == "q": return True
    else: return False

user = True #x means true,false means o
turns = 0
row = 0
slot = 0
while turns < 9:
    print(turns)

    print_board(board)
    active_user = current_user(user)
    choice = input("enter a position between 1 and 9:\n")
    if quit(choice):break

    if check_input(choice):
        print("oups wrong")
        continue
    choose_position(int(choice),row,slot)
    print(row,slot)#just checking row and slot values

    board[row][slot] = active_user

    turns+=1
    user = not user
EN

回答 1

Stack Overflow用户

发布于 2022-06-16 14:04:11

您的问题是,您通过值传递变量。这意味着如果调用choose_position(int(choice),row,slot),python将生成rowslot值的本地副本(仅在choose_position()中有效)。在函数期间,只有这些局部变量在返回时被更改和丢弃。具有相同名称的“外部”变量将永远不会更改。

您应该研究“”和关键字"ref“。或者,您可以将这些值返回为list (甚至更好的是元组),并将它们分配给传入的值。如下所示:

代码语言:javascript
复制
(row, slot) = choose_position(int(choice))

在你的功能中,你会写:

代码语言:javascript
复制
return (row, slot)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72647072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档