如何比较单个列表和一系列列表?

时间:2017-12-20 03:01:15

标签: python-3.x list if-statement random tuples

来自随机导入randint

def apple(player):

    """Returns a new unoccupied position (tuple). Used to spawn a new `apple` at
    that position.  Microbit LED 5x5"""

    Args:
        player (list of tuples): List of player coordinates

    Returns:
        A new unoccupied position (tuple)

    """
    apple = list((0,0))

    # loop to get each tuple, as list
    for i in range(0, len(player)):
        p = list(player[i])

    dot[0] = randint(0,4)
    dot[1] = randint(0,4)
    x= list (apple)

    if x!= p:
        return tuple((dot))

如果我用

运行该功能
player = [(0,0), (1,0), (2,0), (3,0), (4,0),
          (0,1), (1,1), (2,1), (3,1), (4,1),
          (0,2), (1,2), (2,2), (3,2), (4,2),
          (0,3), (1,3), (2,3), (3,3), (4,3),
          (0,4), (1,4), (2,4), (3,4),]

它应该给我(4,4),但它可以做到。 整个功能忽略了我不平等的陈述:(

1 个答案:

答案 0 :(得分:0)

如果我理解正确,播放器是“你的游戏地图,其中包含当前物品的坐标”,你想要找到一个可以种植苹果的空白点。如果有几个可能的点你想随机选择一个

如果这是真的,那么这个脚本会这样做:

from operator import itemgetter
import random

def apple(player):
    max_x = max(player, key=itemgetter(0))[0]
    max_y = max(player, key=itemgetter(1))[1]
    candidates = []
    for x in range(max_x + 1):
        for y in range(max_y + 1):
            if (x, y) not in player:
                candidates.append((x,y))
    return random.choice(candidates)

该脚本假定最小坐标为(0,0)并搜索最大坐标(如果您事先知道这一点,则可以向max_x添加两个参数max_yapple()然后它只是迭代所有可能的坐标,看是否有空点并收集candidates中所有可能的坐标。然后它随机选择一个坐标并返回。