pygame 代码组织
我开始学习用Python和pygame制作游戏,虽然在pygame中快速制作一个可运行的游戏很简单,但没有真正的教程教你怎么合理地组织代码。
在pygame的教程页面上,我发现了三种组织代码的方法。
1- 对于小项目,不使用类。
2- 类似于MVC(模型-视图-控制器)这种结构,但没有rails框架,这样会导致代码变得复杂且难以理解(即使你有面向对象编程和rails的知识)。
3- 像C++那样的结构,虽然干净直观,但可能不太像Python的风格。
import pygame
from pygame.locals import *
class MyGame:
def __init__(self):
self._running = True
self._surf_display = None
self.size = self.width, self.height = 150, 150
def on_init(self):
pygame.init()
self._display_surf = pygame.display.set_mode(self.size)
pygame.display.set_caption('MyGame')
#some more actions
pygame.display.flip()
self._running = True
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self._running = False
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
print event.pos
def on_loop(self):
pass
def on_render(self):
pass
def on_cleanup(self):
pygame.quit()
def on_execute(self):
if self.on_init() == False:
self._running = False
while( self._running ):
for event in pygame.event.get():
self.on_event(event)
self.on_loop()
self.on_render()
self.on_cleanup()
if __name__ == "__main__" :
mygame = MyGame()
mygame.on_execute()
我习惯用C++制作SDL游戏,并且使用这种结构,但我在想这种结构是否适合小项目和大项目,或者在pygame中有没有更简洁的方法。
例如,我找到一个这样组织的游戏:
imports
def functionx
def functiony
class MyGameObject:
class AnotherObject:
class Game: #pygame init, event handler, win, lose...etc
while True: #event loop
display update
这个结构看起来也很有条理,容易理解。
我应该在所有项目中一致使用哪种结构,以便在小型和大型游戏中都能保持代码的整洁?
2 个回答
2
做你能理解的事情。如果你能看懂你发的代码,那就用这个。如果其他的结构让你觉得更自然,那就用那个。
4
我建议你可以考虑使用注释来划分你的工作,虽然一开始看起来有点乏味。比如说:
import pygame, random, math
## CLASSES ----------------------------------------------
class Ball():
def __init__(self, (x,y), size):
"""Setting up the new instance"""
self.x = x
self.y = y
self.size = size
## FUNCTIONS --------------------------------------------
def addVectors((angle1, length1), (angle2, length2)):
"""Take two vectors and find the resultant"""
x = math.sin(angle1) * length1 + math.sin(angle2) * length2
y = math.cos(angle1) * length1 + math.cos(angle2) * length2
## INIT -------------------------------------------------
width = 600
height = 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("S-kuru")
接下来可以继续这样做。
另外一个可以考虑的选项是,你有没有想过使用子模块?子模块就是其他的Python文件(.py),你可以把常用的函数放在里面。
def showText(passedVariable):
print passedVariable
return
这个新文件就像你引入数学库或随机库一样使用,函数也可以这样调用:
import mySubModule
mySubModule.showText("Hello!")
不过这只是我个人的工作方式。你应该遵循你能理解的方式,不仅是现在,也包括下周或明年。