【问题标题】:Procedural Generation Using Classes Pygame使用类 Pygame 的程序生成
【发布时间】:2016-05-03 18:09:29
【问题描述】:

目前,我正在 pygame 中创建一个基本游戏,其中一部分是当你离开屏幕时程序性地生成新区域。作为测试,我希望通过定义其变量为每个区域生成一个对象,然后将该区域的对象保存在类中,以备日后使用。这是我目前拥有的:

#area_gen is set to "true" if you move to a new area
#swidth and sheight are set to the size of the screen
#x_area and y_area are defined as you change areas, acting as sector coordinates
#Red is defined in globals

class areas:

    def __init__(self, coords):
        self.coordinates = coords
        self.generated = False

    def gen_objects(self):
        if not self.generated:
            self.objs = []
            obj_type = "test object"
            center_x = random.randrange(105, swidth-25)
            center_y = random.randrange(25, swidth - 175) 
            self.objs.append([obj_type, center_x, center_y])
            self.generated = True

#Within The Game Loop

    if area_gen == "true":
        coords = str(str(x_area) + " " + str(y_area))
        area = areas(coords)

        area.gen_objects()

    for thing in area.objs:
        if thing[0] == "test object":
            pygame.draw.rect(screen, Red, (thing[1], thing[2], 250, 250))

    #Bottom of the Game Loop
    area_gen = "false"

我认为 self.generated 变量会做的是停止新对象的生成(如果已经存在),但这似乎不起作用。即使该区域已经被访问过,该区域仍会在新位置生成。我对课程的了解相对有限,所以我有点不知道从哪里开始。

【问题讨论】:

  • 为什么使用字符串而不是布尔值?这可能是问题的一部分......(你写的是area_gen == "true"而不是area_gen = True
  • 我的计算机编程课将 True/False 及其各自的语法排除在课程的“布尔”一章之外,所以我开始使用字符串作为替代。当我查找正确的语法时,我已经开始在这个程序中使用字符串了。无论如何,我终于弄清楚发生了什么;事实证明,我对类对象如何工作的了解并不完全准确。我将在新的回复中发布我的修复。

标签: python class pygame


【解决方案1】:

area_gen 传递给区域类的构造函数,并设置self.generated = area_gen。这行得通吗?老实说,我看不到你的代码。

【讨论】:

  • 我很抱歉,在这种情况下,试图在不占用几百行代码的情况下找出哪一段代码是相关的有点困难。每当区域发生变化(角色离开屏幕)时,area_gen 都会设置为“true”。我正在寻找的是一种方法来检查特定于 coord 变量的区域是否已经生成过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2011-03-13
  • 1970-01-01
相关资源
最近更新 更多