【问题标题】:Skip duplicated dots based generated by randint() function跳过由 randint() 函数生成的重复点
【发布时间】:2023-01-16 18:28:23
【问题描述】:

我仍在学习 Python 编程,目前正在努力实现一个目标。我有一个类 Dot 用于创建坐标并稍后比较它们。另外,我得到了一个类 Player 和另外两个从父类继承的子类。

class Dot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __repr__(self):
        return {self.x, self.y}


class Player:
    def __init__(self, board, enemy):
        self.board = board
        self.enemy = enemy

    def ask(self):
        raise NotImplementedError()

    def turn(self):
        while True:
            try:
                target = self.ask()
                repeat = self.enemy.shoot(target)
                return repeat
            except BoardExceptionError as e:
                print(e)


class Viki(Player):
    def ask(self):
        answer = Dot(randint(0, 5), randint(0, 5))
        time.sleep(3)
        print(f'Turn of Viki: {answer.x} {answer.y}')
        return answer


class Human(Player):
    def ask(self):
        while True:
            h = input('Your turn: ').split()
            if len(h) != 2:
                print('Add 2 coordinates...')
                continue
            x, y = h
            if not (x.isdigit()) or not (y.isdigit()):
                print('Add numbers from 0 to 6...')
                continue
            x, y = int(x), int(y)
            return Dot(x - 1, y - 1)

我希望的是类“Viki(Player)”是一种 AI,迫使它不使用之前已经使用(生成)的相同坐标(点)。所以,每次它都应该使用板上没有使用过的单元格。

我知道在这种情况下它可能有助于逻辑运算符或计数函数。例如,

示例 1:

a = Dot(1, 2)
b = Dot(1, 3)
c = Dot(1, 4)
abc_list = [Dot(1, 2), Dot(2, 2), Dot(2, 3)]
print(a in abc_list)
Output
True

示例 2:

print(abc_list.count(a))
Output
1

我尝试同时使用这两个选项,但是当我尝试使用循环和块时出现不同类型的错误。我知道这里的瓶颈是我的知识:)如果有人能帮我解决这个问题,我将不胜感激。提前致谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    这是一个随机生成所有点的生成器(无重复):

    from itertools import product
    from random import shuffle
    
    def random_dots():
        dots = [Dot(*p) for p in product(range(6), repeat=2)]
        shuffle(dots)
        yield from dots
    
    rd = random_dots()
    

    现在,您可以在代码中使用它:

    dot = next(rd)
    

    如果因为点太多而无法预先生成所有点,则可以使用以下内存/时间更轻的方法:

    dots = set()
    
    def random_dot():
        while (tpl := (randint(0, 5), randint(0, 5))) in dots:
            pass
        dots.add(tpl)
        return Dot(*tpl)
    

    并像这样使用:

    dot = random_dot()
    

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 2021-01-28
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2021-01-29
      相关资源
      最近更新 更多