Skip to content

Instantly share code, notes, and snippets.

@iamgreaser
Created July 30, 2011 00:36
Show Gist options
  • Save iamgreaser/1115030 to your computer and use it in GitHub Desktop.
Save iamgreaser/1115030 to your computer and use it in GitHub Desktop.
making games with "yield" - an idea [rev 3]
import pygame
pygame.init()
def gen_timer(delay):
t_target = pygame.time.get_ticks()
while True:
t_current = pygame.time.get_ticks()
if t_current > t_target:
yield False
t_target += delay
else:
yield True
t_new = pygame.time.get_ticks()
if t_new < t_target:
pygame.time.wait(t_target-t_new+5)
def f_game_tempmenu(renderer):
# TODO: render screen, then make it dimmed out,
# and use that as the backdrop
backdrop = screen.copy()
backdrop.lock()
w = backdrop.get_width()
h = backdrop.get_height()
for i in xrange(0,w+h,2):
pygame.draw.line(backdrop, (128,128,128), (0,i), (w,w+i), 1)
pygame.draw.line(backdrop, (128,128,128), (i,0), (i+w,w), 1)
fontpause = pygame.font.Font(None, 100)
pygame.draw.rect(backdrop, (0,85,170), (w/2-150,h/2-60,300,120), 0)
spause = "PUASE"
fw, fh = fontpause.size(spause)
fpause = fontpause.render(spause, True, (255,255,0))
ppause = ((w-fw)/2,(h-fh)/2)
backdrop.unlock()
backdrop.blit(fpause, ppause)
def _f1_render(surface):
print "menu render tick"
surface.blit(backdrop,(0,0))
for i in xrange(25):
print "menu logic tick"
yield _f1_render
class GameObject:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
def draw(self, surface):
pygame.draw.rect(surface, self.color, pygame.Rect(self.x-5,self.y-5,11,11))
def gen_init(self):
while True:
yield
def next(self):
return
def move_to(self, x, y):
self.x, self.y = x, y
def move_by(self, x, y):
self.x += x
self.y += y
class Player(GameObject):
def __init__(self, x, y):
GameObject.__init__(self, x, y, (255,0,0))
self.next = self.gen_init().next
def gen_init(self):
for i in xrange(55):
self.move_by(4, 0)
yield
for i in xrange(20):
yield
while True:
self.move_by(0, -4)
yield
def f_game_logic():
player = Player(10, 320)
def _f1_render(surface):
print "game render tick"
surface.lock()
surface.fill((0,0,85))
player.draw(surface)
surface.unlock()
for i in xrange(25*4):
print "game logic tick"
player.next()
yield _f1_render
if i == 40:
f = f_game_tempmenu(_f1_render)
for r in f:
yield r
global screen
screen = pygame.display.set_mode((640,480), 0, 32)
timer = gen_timer(1000/25)
f_logic = f_game_logic()
for f_render in f_logic:
while timer.next():
f_render(screen) # TODO: give it the screen
pygame.display.flip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment