停止功能更改原始列表

时间:2020-03-02 20:27:52

标签: python pygame

使用pygame制作具有挑战性的宾果游戏... 事情是我有一个函数“ challengeGeneretor”和带有35个项目的len的原始挑战列表,在我使用该函数后,它从原始列表中删除,而不是从我在函数中创建的列表中删除(我之前没有尝试过),我尝试为宾果游戏产生新的随机挑战时会出错。 (适用于第一个生成器)

这是函数:

    def challengesGeneretor(self, challenges, board):
        challenges1 = challenges
        for n, i in enumerate(board):
            for j in range(len(i)):
                x = random.randint(0, len(challenges1) - 1)
                board[n][j] = challenges1[x]
                challenges1.remove(challenges1[x])
        challenges1 = challenges      # just me trying things
        return board

和事件功能...不知道是否是问题的一部分

    def playing_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                selected = self.mouseOnGrid()
                buttonClick = self.mouseOnButton()
                if selected:
                    self.selected.add(selected)
                if buttonClick:
                    self.selected = set()
                    self.grid = testboard     # "testboard" = empty board
                    self.grid = self.challengesGeneretor(challenges, testboard)

此处错误:

Traceback (most recent call last):
  File "/main.py", line 5, in <module>
    app.run()
  File "\app_class.py", line 25, in run
    self.playing_events()
  File "\pygames\app_class.py", line 47, in playing_events
    self.grid = self.challengesGeneretor(challenges, testboard)
  File "\app_class.py", line 146, in challengesGeneretor
    x = random.randint(0, len(challenges1) - 1)
  File "\random.py", line 222, in randint
    return self.randrange(a, b+1)
  File "\random.py", line 200, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)

任何帮助将非常感谢,谢谢!

2 个答案:

答案 0 :(得分:3)

我认为您需要了解浅表复制的原理。 ref

您可能会问自己是否真的想处理副本,因为当列表很大时,性能可能会成为问题。

答案 1 :(得分:3)

challenges1 = challenges不会在内存中创建新数组,而是将内存地址传递给新变量(检查指针)。它适用于复杂的数据结构(例如数组)。

如果要复制原始列表,请创建一个创建空列表的函数,然后将原始列表的元素复制到新创建的列表中。