【发布时间】: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 及其各自的语法排除在课程的“布尔”一章之外,所以我开始使用字符串作为替代。当我查找正确的语法时,我已经开始在这个程序中使用字符串了。无论如何,我终于弄清楚发生了什么;事实证明,我对类对象如何工作的了解并不完全准确。我将在新的回复中发布我的修复。