Python + Pygame Project 2 (Zero)
I've been working on this for a few days now and so far so good!
I've got a single module that contains "Graphics", "Mouse", "Keyboard", and "Sound".
Given the names, you should understand what each does. 
For surfaces/image, you can have an unlimited amount. Love python array "append" and "pop" functions xD.
Also I have were you can draw text, you just specify the font name, bold, italic, anti, and size. ^.^
*Tired...*
Anyways, here is the code:
run.py:
Code:
'''
Created on Aug 18, 2010
@author: Kyle
'''
import os, sys, main, map
if __name__ == '__main__':
tiles = []
#for x in range(0, 25):
# tiles.append([])
# for y in range(0, 15):
# tiles[x].append([])
# tiles[x][y].append([]) #Add layer array
# tiles[x][y].append([]) #Add type array
# for layers in range(0, 5):
# tiles[x][y][0].append((x * 2) + (y + layers))
# for types in range(0, 4):
# tiles[x][y][1].append((x * 2) + (y + types))
#
#tiles[0][0][0][1] = 4
#print(str(len(tiles)))
#sys.exit()
mapsize = (800, 800)
curtile = 0
g = main.Graphics("Zero", 640, 480, False)
m = main.Mouse()
k = main.Keyboard()
s = main.Sound()
mp = map.Main(mapsize[0], mapsize[1])
g.addSurface(os.path.join('Data', 'GFX', 'Tiles', 'Set1.png'), -1)
g.addFont('Arial', 18, True, True)
g.addFont('Comic Sans MS', 20, True, False)
s.add(os.path.join('Data', 'Sounds', 'Boom.wav'))
s.setVolume(0, 100)
s.play(0)
while 1:
g.begin()
if k.getKey(27):
g.quit()
elif k.getKey(273): #Up arrow
print("Up arrow.")
curtile = curtile + 1
elif k.getKey(274):
print("Down arrow.")
if curtile < 0:
curtile = 0
else:
curtile = curtile - 1
elif k.getKey(275):
print("Right arrow")
elif k.getKey(276):
print("Left arrow.")
if m.buttonLeft():
mp.setTileLayer((int(m.getX() / 32)), (int(m.getY() / 32)), 0, 5)
g.setSurfaceAlpha(0, 50)
elif m.buttonRight():
mp.setTileLayer((int(m.getX() / 32)), (int(m.getY() / 32)), 0, 0)
g.setSurfaceAlpha(0)
g.draw(0, (int(m.getX() / 32) * 32), (int(m.getY() / 32) * 32), 64, 32, 32, 32)
#g.draw(0, (m.getX() - 16), (m.getY() - 16), 32, 32, 32, 32)
g.drawText(0, ("X: " + str(m.getX()) + " | Y: " + str(m.getY())), 16, 16, True)
g.drawText(1, ("Current selected tile: " + str(curtile)), 16, 32, True)
g.drawText(1, ("X: " + str(m.getX()) + " | Y: " + str(m.getY())), 16, 64, True)
for x in range(0, (int(mapsize[0] / 32)) - 1):
for y in range(0, (int(mapsize[1] / 32)) - 1):
for layer in range(0, mp.max_layers):
if mp.getTileLayer(x, y, layer) > 0:
temp = (32, 0)
#print(temp)
g.draw(0, x * 32, y * 32, temp[0], temp[1], 32, 32)
g.end()
main.py:
Code:
'''
Created on Aug 18, 2010
@author: Kyle
'''
import os, sys, pygame #@UnusedImport
from pygame.locals import * #@UnusedWildImport
class Graphics:
window = None
screen = None
screen_color = (0, 125, 125)
flags = None
caption = ""
width = None
height = None
clock = None
max_FPS = 60
surfaces = []
fonts = []
def __init__(self, caption, width, height, fullscreen):
(self.caption, self.width, self.height) = (caption, width, height)
if fullscreen:
self.flags = HWSURFACE | DOUBLEBUF | FULLSCREEN
else:
self.flags = HWSURFACE | DOUBLEBUF
print("Setting values...")
if pygame.init() == -1:
raise Exception("Failed to initialize pygame.")
print("Initialized pygame...")
if pygame.display.mode_ok((width, height), self.flags):
self.window = pygame.display.set_mode((width, height), self.flags)
print("Set the main window...")
else:
raise Exception("Failed to set display mode.")
pygame.display.set_caption(caption)
self.screen = pygame.display.get_surface()
print("Set the screen surface...")
self.clock = pygame.time.Clock()
print("Initialized the clock...")
def addSurface(self, image, colorkey = None):
try:
if os.path.exists(image):
img = pygame.image.load(image)
if not img.get_alpha() is None:
img = img.convert_alpha()
else:
img = img.convert()
if not colorkey is None:
if colorkey is -1:
colorkey = img.get_at((0,0))
img.set_colorkey(colorkey, RLEACCEL)
self.surfaces.append(img)
print("Surface " + str(image) + " successfully added.")
else:
print(image + " doesn't exists!")
except pygame.error:
print("Error trying to load image: " + str(image) + ".")
def removeSurface(self, id):
if id < len(self.surfaces) and id > -1:
self.surfaces.pop(id)
print("Surface #" + str(id) + " was removed.")
else:
print("Invalid surface id, '" + str(id) + "'.")
def getSurfaceAlpha(self, id):
if id < len(self.surfaces) and id > -1:
return self.surfaces[id].get_alpha()
else:
print("Invalid surface id, '" + str(id) + "'.")
def setSurfaceAlpha(self, id, alpha = None):
if id < len(self.surfaces) and id > -1:
self.surfaces[id].set_alpha(alpha)
else:
print("Invalid surface id, '" + str(id) + "'.")
def addFont(self, name = None, size = 12, bold = False, italic = False):
self.fonts.append(pygame.font.SysFont(name, size, bold, italic))
if not name is None:
print("Font successfully added as #" + str(len(self.fonts) - 1) + ".")
def removeFont(self, id):
if id < len(self.fonts) and id > -1:
self.fonts.pop(id)
print("Font #" + str(id) + " was removed.")
else:
print("Invalid font id, '" + str(id) + "'.")
def begin(self):
self.clock.tick(self.max_FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.quit()
self.screen.fill(self.screen_color)
def draw(self, id, x1, y1, x2, y2, width, height):
if id < len(self.surfaces) and id > -1:
self.screen.blit(self.surfaces[id], (x1, y1), (x2, y2, width, height))
else:
print("Invalid surface id, '" + str(id) + "'.")
def drawText(self, id, text, x, y, antialias, color = (255, 255, 255)):
if id < len(self.fonts) and id > -1:
self.screen.blit(self.fonts[id].render(text, antialias, color), (x, y))
else:
print("Invalid font id, '" + str(id) + "'.")
#def flip(self, id, xflip, yflip):
# if id < len(self.surfaces) and id > -1:
# self.surfaces[id] = pygame.transform.flip(self.surfaces[id], xflip, yflip)
# else:
# print("Invalid surface id, '" + str(id) + "'.")
def end(self):
pygame.display.set_caption(self.caption + " | FPS: " + str(int(self.clock.get_fps())))
pygame.display.flip()
def quit(self):
pygame.quit()
sys.exit()
class Mouse:
def getX(self):
return pygame.mouse.get_pos()[0]
def getMovementX(self):
return pygame.mouse.get_rel()[0]
def getY(self):
return pygame.mouse.get_pos()[1]
def getMovementY(self):
return pygame.mouse.get_rel()[1]
def setPos(self, x, y):
pygame.mouse.set_pos([x, y])
def visible(self, state):
pygame.mouse.set_visible(state)
def buttonLeft(self):
return pygame.mouse.get_pressed()[0]
def buttonMiddle(self):
return pygame.mouse.get_pressed()[1]
def buttonRight(self):
return pygame.mouse.get_pressed()[2]
def hasFocus(self):
return pygame.mouse.get_focused()
class Keyboard:
def getKey(self, key):
return pygame.key.get_pressed()[key]
def getModKey(self, key):
return pygame.key.get_mods()[key]
def getKeyName(self, key):
return pygame.key.name(key)
def getRepeated(self):
return pygame.key.get_repeat()
def setModKey(self, key):
pygame.key.set_mods(key)
def setRepeated(self, delay, interval):
pygame.key.set_repeat(delay, interval)
def hasFocus(self):
return pygame.key.get_focused()
class Sound:
sounds = []
def __init__(self, frequency = 22050, size = -16, channels = 2, buffer = 4096):
pygame.mixer.init(frequency, size, channels, buffer)
def add(self, file):
if os.path.exists(file):
self.sounds.append(pygame.mixer.Sound(file))
print(file + " successfully added.")
else:
print(file + " doesn't exists!")
def remove(self, id):
if id < len(self.sounds) and id > -1:
self.sounds.pop(id)
print("Sound #" + str(id) + " was removed.")
else:
print("Invalid sound id, '" + str(id) + "'.")
def play(self, id, loops = 0, maxtime = 0, fade = 0):
if id < len(self.sounds) and id > -1:
self.sounds[id].play(loops, maxtime, fade)
print("Playing sound #" + str(id) + ".")
else:
print("Invalid sound id, '" + str(id) + "'.")
def stop(self, id):
if id < len(self.sounds) and id > -1:
self.sounds[id].stop()
print("Sound #" + str(id) + " was stopped.")
else:
print("Invalid sound id, '" + str(id) + "'.")
def fadeout(self, id, time):
if id < len(self.sounds) and id > -1:
self.sounds[id].fadeout(time)
else:
print("Invalid sound id, '" + str(id) + "'.")
def length(self, id):
if id < len(self.sounds) and id > -1:
return self.sounds[id].get_length()
else:
print("Invalid sound id, '" + str(id) + "'.")
def setVolume(self, id, volume):
if id < len(self.sounds) and id > -1:
self.sounds[id].set_volume(volume / 100)
print("Sound #" + str(id) + " volume is now " + str(volume) + ".")
else:
print("Invalid sound id, '" + str(id) + "'.")
def getVolume(self, id):
if id < len(self.sounds) and id > -1:
return (self.sounds[id].get_volume() * 100)
else:
print("Invalid sound id, '" + str(id) + "'.")
def getChannels(self, id):
if id < len(self.sounds) and id > -1:
return self.sounds[id].get_num_channels()
else:
print("Invalid sound id, '" + str(id) + "'.")
map.py:
Code:
'''
Created on Aug 22, 2010
@author: Kyle
'''
class Main:
width = None
height = None
tile = [] #[x][y][layer or type, 0 or 1][layer or type value]
max_layers = 4
max_types = 5
tilesinset = 7
tilesize = (224, 448)
def __init__(self, width, height):
(self.width, self.height) = (width, height)
for x in range(0, int((width / 32)) - 1):
self.tile.append([])
for y in range(0, int((height / 32)) - 1):
self.tile[x].append([])
self.tile[x][y].append([])
self.tile[x][y].append([])
for layers in range(0, self.max_layers): #Four layers: None, Blocked, Heal, Damage
self.tile[x][y][0].append(0)
for types in range(0, self.max_types): #Five types: Ground, Mask1, Mask2, Fringe1, Fringe2
self.tile[x][y][1].append(0)
def setTileLayer(self, x, y, layer, value):
if x < len(self.tile) and x > -1 and y < len(self.tile[0]) and y > -1 and layer < self.max_layers and layer > -1:
self.tile[x][y][0][layer] = value
def getTileLayer(self, x, y, layer):
if x < len(self.tile) and x > -1 and y < len(self.tile[0]) and y > -1 and layer < self.max_layers and layer > -1:
return self.tile[x][y][0][layer]
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
I absolutely love the way I did the tiles xD.
Code:
[x][y][layer or type, 0 or 1][layer or type value]
Unique and amazing harhar. ^.^
|