python - 如何判断一个元素是否已经在列表中的某个位置?

标签 python arrays python-3.x

我制作了一个 5x5 矩阵游戏,由 25 个 0 组成。玩家 1 可以将任意 0 更改为 1,玩家 2 可以将任意 0 更改为 2。

我只是无法弄清楚如何验证板上的位置,以便如果玩家已经放置了他们的号码,他们需要输入一个尚未占用空间的不同号码。

例如:

Player 1 | Please enter a number between 1-25: 3
0 0 3 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Player 2 | Please enter a number between 1-25: 3
This position is already taken! Please enter a different position:

此外,我将如何对游戏进行编程以确定棋盘上是否不再有任何 0?因为接下来将是平局。

代码:

def player1_turn():
    player1_option = int(input("Player 1 | Please enter a number between 1-25: "))
    if player1_option <= 0:
        print("You can only enter a number between 1 and 25")
        player1_turn()
    elif player1_option > 25:
        print("You can only enter a number between 1 and 25")
        player1_turn()

    player1 = (player1_option - 1) #Counter-acts the elements from starting at 0
    grid[int(player1) // 5][int(player1) % 5] = 1 #places a 1 in inputted position
    for row in grid: #for each row in the grid
        print(*row, sep=" ")
    print()

    for y in range(0,4):
        for x in range(0,4):
            if grid[y][x] == grid[y][x+1] == grid[y+1][x] == grid[y+1][x+1] >0: #if there is a 2x2 of same number in grid:
                print("Player",grid[y][x],"has won!")
                exit()

最佳答案

你只需要在更新之前检查你要更新的位置是否为0

def player1_turn():
    player1_option = int(input("Player 1 | Please enter a number between 1-25: "))
    if player1_option <= 0:
        print("You can only enter a number between 1 and 25")
        player1_turn()
    elif player1_option > 25:
        print("You can only enter a number between 1 and 25")
        player1_turn()

    player1 = (player1_option - 1) #Counter-acts the elements from starting at 0

    #You must check if the position is a 0

    if (grid[int(player1) // 5][int(player1) % 5] == 0):
        grid[int(player1) // 5][int(player1) % 5] = 1 #places a 1 in inputted position

    else:
        #Do something else here instead of updating it 


    for row in grid: #for each row in the grid
        print(*row, sep=" ")
    print()

对于填充的棋盘,您可以使用常见的方式(双for循环)或更直观的方式使用列表理解来检查它

def board_filled():
    for i in grid:
        for j in i:
            if j == 0:
                return False
    return True

def board_filled():
    return (sum([0 in i for i in grid]) == 0)

关于python - 如何判断一个元素是否已经在列表中的某个位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53727617/

相关文章:

python - 如何将 Pandas 数据框从基于字符串的分类列转换为数字表示

javascript - 仅针对某些键从数组映射数据(未过滤)

python - Django 规则重用谓词

PHP - 检查数组索引是否存在或为空

python-3.x - 在geopandas中溶解后删除多边形的内线

python - 如何确定数据类中的字段是否具有默认值或是否已显式设置?

python - 大数的质因数

python - 防止 matplotlib 有状态

python - 逐项搜索Python列表中的元素,并根据条件语句创建新列表

javascript - IE7 Javascript 和使用字符串作为数组