【问题标题】:random.randint() generating a consistent patternrandom.randint() 生成一致的模式
【发布时间】:2021-09-20 08:46:05
【问题描述】:

我一直在使用pygame 开发基于网格的应用程序,但遇到了一个奇怪的问题。

我正在生成一个list 的瓷砖,每个瓷砖可以有 3 种随机颜色中的 1 种。不过,每次我运行程序时,我都会得到一个相当一致的模式。

所有这些测试都紧随其后,并且在测试之前的所有运行中都有相似的结果,右下角有一个巨大的单色斑点。

这是我的磁贴代码

from enum import Enum


class Colour(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3


class Tile():

    def __init__(self, _map, x : int, y : int, colour = 1):
        self.x = x
        self.y = y
        self.map = _map
        self.colour = Colour(colour)

    def PrintInfo(self):
        print("x: " + str(self.x) + "\ny: " + str(self.y) + "\nCol: " + str(self.colour.name))

这是制作瓦片数组的地方,(生成随机数的地方)

from Tile import Tile
from random import randint
"""Map class creates a 2d array of tiles, and allows individual tiles, or
groups of tiles to be returned."""


class Map:
    def __init__(self, width : int, height : int):
        self.map = []

        #Create a 2d array of tiles.
        self.map = [[Tile(self, i, j, randint(1, 3)) for i in range(width)] for j in range(height)]



    def PrintInfo(self):
        #Print the info of each tile. use GetTile(x, y).PrintInfo() tp get
        #individual tile into
        for t in self.map:
            t.PrintInfo()

    def GetTile(self, x: int, y: int):
        #Get tile from coords
        return self.map[x][y]

这是根据随机数制作视觉组件的地方

def Main(self):
    #Create an array of data objects
    self.map = Map(8, 8)
    #Create dictionary to connect data object to display object
    self.tileToObjDict = {}

    for i in range(8):#change these from constants after testing
        for j in range(8):
            t = self.map.GetTile(i, j)#get tile at current position in loop
            #t.PrintInfo()
            bobj = BoxObject(self.win, t.x*self.gridSpacing, t.y*self.gridSpacing, t.x*self.gridSpacing+self.gridSpacing,
                             t.y*self.gridSpacing+self.gridSpacing, str(t.colour.name).lower())#Create onject based on info
            self.objects.append(bobj)#add display object to render list
            self.tileToObjDict[t] = bobj#connect tile to display obj in dictionary

不需要,组装可视化组件的代码

#Basic Object

    class BoxObject(Object):
        def __init__(self, surface, x1 = 0, y1 = 0, x2 = 0, y2 = 0, colour = 'grey', hitbox = Hitbox(EventManager())):#Take a surface, 4 coords, a colour, and an optional hitbox to manage events
            super().__init__(Box(surface, Rectangle(x1,y1,x2,y2).GetCorners(),ColourManager().GetColour(colour)),
                hitbox)
            
            #draw the object for 1 frame to reference
            self.drawn = draw.rect(self.graphic.surface, self.graphic.colour,(self.graphic.coord1, self.graphic.coord2))
    
        def Update(self):
            if self.visible:#Draw the object
                draw.rect(self.graphic.surface, self.graphic.colour,(self.graphic.coord1, self.graphic.coord2))
                if Hitbox == None:
                    return
                if len(self.hitbox.eventM.eventList) > 0:#If the hitbox has any events to manage, manage them
                    for e in self.hitbox.eventM.eventList:
                        e()

色彩模块

from pygame import Color

class ColourManager:
    colourDict : {}#holds custom colours

    def __init__(self, defaultColours = True):
        self.colourDict = {}

        if defaultColours:
            self.AddBasicColours()

    def AddColour(self, name : str, _r : int, _g : int, _b : int, _a : int = 255):
        self.colourDict[name] = Color(_r, _g, _b, _a)
    
    def GetColour(self, name : str) -> Color:
        return self.colourDict.get(name)

    def PrintColours(self):
        for key in self.colourDict.keys():
            print(key)

    def AddBasicColours(self):
        self.AddColour('red', 255, 0, 0)
        self.AddColour('green', 0, 255, 0)
        self.AddColour('blue', 0, 0, 255)

        self.AddColour('grey', 100, 100, 100)

    def LoadColourSheet():
        """TODO: Allow many colours to be loaded at once from txt file"""

感谢任何帮助,无论是有效的替代随机化方法,还是可能导致此问题的代码问题。

【问题讨论】:

  • 所有伪随机生成器(无论多么复杂)最终都会重复自己。在任何情况下尝试使用另一个 PRNG,甚至是自定义的
  • @NikosM。最终,是的,但这需要很长时间。不是 OP 看到的。
  • 您仅从 3 个数字中选择了一个随机数,您会看到 3 种不同的模式。我没有发现问题。
  • 正是 OP 的随机选择非常有限,所以模式很容易形成或重复。
  • 有太多的代码称这是一个实用的最小示例,但可以猜测:颜色是随机的,但图案绝对不是。这行,BoxObject(self.win, t.x*self.gridSpacing, t.y*self.gridSpacing, t.x*self.gridSpacing+self.gridSpacing, t.y*self.gridSpacing+self.gridSpacing, str(t.colour.name).lower())#Create onject based on info,设置了一个非常固定的模式,self.map = [[Tile(self, i, j, randint(1, 3)) for i in range(width)] for j in range(height)] 间接定义了t.xt.y,也是固定值。

标签: python random pygame


【解决方案1】:

9769953 关于它是模式而不是随机化是正确的。我忘记了 pygame 是如何渲染形状的,同样的模式是因为单个块比它们应该的要大得多。 我不得不改变 x2 和 y2。

        #Box object: screen to draw it to, x1, y1, x2, y2, colour (x1, y1) = top left corner  of box, x2 = width, y2 = height
        bobj = BoxObject(self.win, t.x*self.gridSpacing, t.y*self.gridSpacing, self.gridSpacing, self.gridSpacing, str(t.colour.name).lower())#Create object based on info

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 2017-08-11
    • 2016-05-24
    • 1970-01-01
    • 2021-07-11
    • 2011-02-01
    • 2018-09-08
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多