你可以有一个简单的建筑类:
class Building:
def __init__(self, x, y, w, h, color):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
def draw(self):
// code for drawing the rect at self.x,self.y
// which is self.w wide and self.h high with self.color here
关于窗户,您可以在列表中为每个建筑物指定每个窗口,如 [(x, y, w, h)] 或简单地创建一个如下所示的建筑类:
class Building:
def __init__(self, x, y, w, h, color, wx, wy):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
self.wx = wx
self.wy = wy
def draw(self):
// code for drawing the rect at self.x,self.y
// which is w wide and h high with self.color here
// Draw wx windows horizontally and wy windows vertically
for y in range(0, self.wy):
for x in range(0, self.wx):
// draw Window code here
另一种方法是您将建筑物“预渲染”为图像,然后再显示(如果您有很多建筑物,这也可能更快)。
然后你的游戏循环可能看起来像这样
buildingList = [Building(0, 0, 15, 50, RED), Building(0, 0, 40, 30, BLUE)]
while gameIsRunning:
// Clear screen code here
// Show Building
for b in buildingList:
b.draw()
// More stuff
这几乎是绘制任何东西的最基本方法,您可以用这种方式绘制角色,键甚至应该在角色上方的图块,例如像Tuff这样的平台游戏中的水图块。这里的树也在一个大列表中(实际上,出于性能原因,我维护了一个较小的列表,其中包含 1 1/2 环绕屏幕上的树。有超过 1500 棵“树”)。
编辑:在不同窗口颜色的情况下,有两种可能的解决方案。
每个建筑物使用不同的窗户颜色:
class Building:
def __init__(self, x, y, w, h, color, wx, wy, windowColor):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
self.wx = wx
self.wy = wy
self.windowColor = windowColor
def draw(self):
// code for drawing the rect at self.x,self.y
// which is self.w wide and self.h high with self.color here
// Draw wx windows horizontally and wy windows vertically
for y in range(0, self.wy):
for x in range(0, self.wx):
// draw Window code here using self.windowColor
可能性 2,每个窗口使用不同的颜色:
class Building:
def __init__(self, x, y, w, h, color, windows):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
self.wx = wx
self.wy = wy
self.windows = windows
def draw(self):
// code for drawing the rect at self.x,self.y
// which is self.w wide and self.h high with self.color here
// Draw all windows
for w in windows:
// draw Window at w[0] as x, w[1] as y with w[2] as color
// Create a building at 0,0 that is 20 wide and 80 high with GRAY color and two windows, one at 2,2 which is yellow and one at 4, 4 that's DARKBLUE.
b = Building(0, 0, 20, 80, GRAY, [(2, 2, YELLOW), (4, 4, DARKBLUE)])