无法为2d array/lis中的元素获取正确的索引

2024-06-26 01:55:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试写一个程序,这是一个连接四游戏与零重力,这意味着你可以从任何一边的董事会,我目前正在选择一个专栏和放置我的作品从顶部。同时,我的程序会询问用户,他们想在棋盘上放置多少个方块,使游戏更难进行。当我输入实例C8时,它会查看列表中每个列表中第8个元素的第8行。有什么想法吗?在

我编辑的代码如下:

#this imports random for my blocks 
import random




#this makes my board
table = [[ "   ","C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10"],
         [ " R1|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R2|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R3|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R4|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R5|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R6|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R7|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R8|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
         [ " R9|", " |", " |", " |", " |", " |", " |", " |", " |", " |", " |"],
       [ "R10|" ," |", " |", " |", " |", " |", " |", " |", " |", " |", " |"]]
#my two different player pieces
player1="#|"
player2="@|"
block="B|"
row=11
columns=11
#this is a function i can call to print the table
def printTable(table):
    for row in table:
        for value in row:
            print (value,end=' ')
        print ('\n')

#this ask the user how many blocks they want on their board then places it on there
def block(table):
    blockQuestion=(input("how many blocks would you like to put on the table? \n (please enter a number between 1 and 25)"))
    number=blockQuestion[:2]
    number=int(number)
    number=number-1
    print("this is number ",number)
    count = 0      
    number=int(number)
    while number >= count:
        x=random.randint(1,10)
        y=random.randint(1,10)
        print("x and y ", x,y)

        table[x][y]="B|"
        count +=1

    printTable(table)
    move()



#this is my function to ask the user for their move.
def move():
    move=input("Please choose where you would like to drop your marker \n (For instance C1, R5)")
    move.split()
    rorc=move[0:1]
    ans=move[1:3]
    answer=int(ans)

    print(rorc," ",answer)

    if "R" in move:
        row(answer)

    if "C" in move:
        col(answer)
#this is my function if the user wants to go by row
def row(answer):
    side=input("would you like to insert it from the right or left \n Please type R for right or L for left ")

    if "R" in side:

        try:
            table[answer].reverse()

            blockCheck=table[answer].index("B|")
            if blockCheck == 0:
                print ("you can not place a peice there because of the block")
                tryAgain()                   
        except:
            try:
                p1Check=table[answer].index("#|")
                if p1Check is 0:
                    print ("you can not place a peice there due to the opponents marker")
                    tryAgain()
            except:
                try:
                    p2Check=table[answer].index("@|")
                    if p2check is 0:
                        print ("you can not place a peice there due to the opponents marker")
                        tryAgain()
                except:
                    print('hi')
    try:
        tits=max(blockCheck,p1Check,p2Check)
        print("All three checks",tits)

    except:
        try:
            tits=max(blockCheck,p1Check)
            print("this is bc and p1c",tits)
        except:
            tits=(blockCheck)
            print("this is block check",tits)
    table[answer].reverse()
    table[answer][-tits]= (player1)
    printTable(table)
#this is my function if the user wants to go by columns
def col(answer):
    side=input("would you like to insert it from the top or bottom \nPlease type T for top or B for bottom")
    answer=int(answer)
    if "T" in side:
        try:   
            blockCheck=table[:][answer].index("B|")

            print("blockCheck ", blockCheck)
            if blockCheck == 1:
                print ("you can not place a peice there because of the block")
                tryAgain()
        except:
            try:
                p1Check=table[answer].index("#|")
                if p1Check is 1:
                    print ("you can not place a peice there due to the opponents marker")
                    tryAgain()
            except:
                try:
                    p2Check=table[answer].index("@|")
                    if p2check is 1:
                        print ("you can not place a peice there due to the opponents marker")
                        tryAgain()
                except:
                    print("whaa")       
        try:
            tits=min(blockCheck,p1Check,p2Check)
            print("All three checks",tits)

        except:
            try:
                tits=min(blockCheck,p1Check)
                print("this is bc and p1c",tits)
            except:
                try:
                    tits=(blockCheck)
                    print("this is block check",tits)
                except:
                    tits=11
        table[tits-1][answer]= (player2)
        printTable(table)
#function to restart the program to the move function
def tryagain():
    tryAgain=input('try again \nPlease type y or n ')
    if tryAgain == 'y':
        move()
    elif tryAgain =='n':
        bash





#calls the function to start the program 
block(table)

提前谢谢!在


Tags: thetoansweryounumbermoveifis
1条回答
网友
1楼 · 发布于 2024-06-26 01:55:12

毫无疑问,正如您已经注意到的那样,调试一个长串的if语句非常困难。事实上,大多数编写良好的程序很少包含像move函数那么长的内容。Linus Torvalds在他为linux内核设计的style guide中这样说:

Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80×24, as we all know), and do one thing and do that well.

换句话说,甚至(尤其是!)当你在编程像现代操作系统内核这样复杂得难以置信的东西时,你的函数不应该占用超过48行代码,他说的是c代码,这比Python要复杂得多。您在这里严重违反了这个规则;您的move函数的长度超过了100行!在

所以我的答案不是真正的答案,而是元答案。将move函数分解成几个更小的函数。对于您需要的每种输入,编写一个单独的函数来接受输入,确保它是正确的,并将其转换为程序可以使用的值。尽可能多地将上述if逻辑转换为这些函数。然后让您的move函数调用这些函数,并应用任何必要的顶层逻辑。我看到至少有三个,而且可能有五个或六个不同的功能在一个巨大的功能中聚集在一起。在

一旦你把它分开,用print语句分别测试每个函数,以确保它们做了你期望的事情。一旦您完成了这些操作,并且您确定它们的行为符合预期,您就会知道您的问题是在顶级的move函数中隔离出来的;从那里,对我们或您来说,调试应该一点都不难!在


你的编辑让事情变得更好了。但我很清楚,你对函数应该如何运作没有一个直观的感觉。考虑一下您是如何重构上述代码的。你已经写了一个函数。然后在该函数的末尾,调用另一个函数。然后在这个函数的末尾调用另一个函数。你一次又一次地链接函数。如果我在上面画一个你的代码的调用图,它看起来像这样:

block
 |
 -> move
     |
     -> row | col
         |
         -> ...keep on calling new functions...          

这不是它的工作原理。相反,您应该有一个主函数来调用其他函数并获取它们返回的值。考虑这个简单的例子:

^{pr2}$

您可以看到上面的两个函数不调用其他函数。他们只是做点什么然后回来。调用图如下所示:

main
 |
 -> get_val
  <- |
 |
 -> transform_val
  <- |
 |

在本例中,main位于程序的“顶层”,它控制着一切。重新构造代码使其看起来像那样。您应该有一个main函数来调用对您的表进行操作的其他函数。由于table是可变的,所以这些函数基本上不需要return任何东西,但它们绝对不应该以另一个函数调用结束。将其下移到main函数中:

def main():
    # define some variables here
    block(table)
    while no_winner(table):
        move(table)

这里no_winner查看表格,看某人是否赢了,或者是否不可能再走一步;它会根据另一步是否可能而做正确或错误的判断。move接受用户的输入并基于它转换表。现在循环包含了您需要的所有顶层逻辑。然后在程序的底部,执行此操作以启动主程序。(这只是在Python中调用main的标准方法;现在不要担心__name__意味着什么:

if __name__ == '__main__':
    main()

我知道我还没有回答你真正的问题,但我认为这些东西实际上比你要寻找的特定bug重要得多。不过,我现在就开始试着找到它。在

相关问题 更多 >