首页 > 解决方案 > 如何重置索引计数器?

问题描述

我正在实现一个游戏(连接四个)。玩家通过选择一个列号来放置他们的检查器来移动,当该列为空时,检查器放置在行索引(-1),如果不是我将索引减少-1。我在重置行索引时遇到问题,因此在两个玩家玩同一列之后,非空列中的下一步应该跟随最后一个索引,而不是在最后一个递减索引上继续。[在这张图片中,第三步(红色)和第四步(绿色)播放第 2 列,绿色检查器应该在第 5 行(索引-2),但它从第二步中的最后一个递减索引继续(绿色 [索引 -2] 列(1)] [1] .

这是我的代码。这些移动从第 41 行开始执行。

`import sys
from termcolor import colored, cprint

#Drawing the 7columns x 6 rows playing field

rows = [] #Empty list to store row numbers

def playing_field(field):
    for row in range(11):
        rows.append(row) #Storing the row numbers in a list
        if row % 2 == 0:
            height = int(row/2)
            for column in range(13):
                if column % 2 == 0:
                    width = int(column/2)
                    if column != 12:
                        print(field[height][width], end="")
                    else:
                        print(field[height][width])
                else:
                    print("|", end="")
        else:
            print("______________")
    return True


#Defining the players variable
player = 1
index = -1

# Defining a 7 columns by 6 rows list of lists
curr_field = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "]]

# Draw the field by calling the playing field function
playing_field(curr_field)

x = colored(u'\u2B24', 'red')
y = colored(u'\u2B24', 'green')

#Loop to initiate play as long condition is true
while (True):
    print("PLAYER: ", player)
    moveCol = int(input("Choose column:\n")) - 1
     
        #Player one's turn
    if player == 1:
        if curr_field[-1][moveCol] == " ":
            curr_field[-1][moveCol] = x
            player = 2
        else:
            index += (-1)
            curr_field[index][moveCol] = x
            #Take turn to player two
            player = 2
            
    #Player two's turn
    else:
        if curr_field[-1][moveCol] == " ":
            curr_field[-1][moveCol] = y
            #Take turn to player 1
            player = 1
        else:
            index += (-1)
            curr_field[index][moveCol] = y
            #Take turn to player two
            player = 1
                     
    #calling function
    playing_field(curr_field)

` [1]:https ://i.stack.imgur.com/qT9HV.png

标签: pythonloops

解决方案


与其操纵索引号,不如将移动附加到矩阵中。使用字典可能是最简单的。

moves={}
moves[colnum] = moves.get(colnum,[]) + [playernum]

如果没有人移入一列,则该.get()函数返回一个空列表,然后将值附加(添加)到该列表中。

一段时间后,您的字典将如下所示:

{2: [1,2], 3: [2, 1, 2]}

在列中显示每个位置(自下而上)的球员编号。

这样,列表中每一列的条目都是正确的长度,并使用可用于为playing_field()函数中的列表提取颜色的索引。


推荐阅读