Source

sample_pygame_project_organization / data / states / eightdir.py

Full commit
import pygame as pg
from .. import setup as su,tools

DIRECTDICT = {pg.K_LEFT  : (-1, 0),
              pg.K_RIGHT : ( 1, 0),
              pg.K_UP    : ( 0,-1),
              pg.K_DOWN  : ( 0, 1)}

class Player(object):
    def __init__(self,rect,speed):
        self.rect = pg.Rect(rect)
        self.speed = speed
        self.movement = [0,0]
        self.make_image()
    def make_image(self):
        self.image = pg.Surface((self.rect.size)).convert_alpha()
        self.image.fill((0,0,0,0))
        pg.draw.ellipse(self.image,(0,0,0),(1,1,self.rect.size[0]-2,self.rect.size[1]-2))
        pg.draw.ellipse(self.image,(255,0,0),(6,6,self.rect.size[0]-12,self.rect.size[1]-12))
    def update(self,Surf,keys):
        self.movement = [0,0]
        for key in DIRECTDICT:
            if keys[key]:
                for i in (0,1):
                    self.movement[i] += DIRECTDICT[key][i]*self.speed
        self.rect.move_ip(self.movement)
        self.draw(Surf)
    def draw(self,Surf):
        Surf.blit(self.image,self.rect)

class EightDir(tools._State):
    def __init__(self):
        tools._State.__init__(self)
        self.Player = Player((250,250,100,100),5)
        self.title = self.render_font("Fixedsys500c",40,"8-Direction Movement",(0,255,255))
        self.title_rect = self.title.get_rect(center=(su.SCREEN_RECT.centerx,75))
        self.escape_txt = (self.render_font("Fixedsys500c",20,
                            "[Press ESCAPE to return to menu]",(255,255,0)))
        self.escape_txt_rect = self.escape_txt.get_rect(center=(su.SCREEN_RECT.centerx,500))
        self.blink = False
        self.timer = 0.0
    def render_font(self,font,size,msg,color=(255,255,255)):
        RenderFont = pg.font.Font(su.FONTS[font],size)
        return RenderFont.render(msg,1,color)
    def get_event(self,event):
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                self.next = "MENU"
                self.done = True
    def cleanup(self):
        self.persist["location"] = self.Player.rect.center
        return tools._State.cleanup(self)
    def startup(self,persistant):
        tools._State.startup(self,persistant)
        if "location" in self.persist:
            self.Player.rect.center = self.persist["location"]
    def update(self,Surf,keys,mouse):
        Surf.fill((50,100,50))
        self.Player.update(Surf,keys)
        Surf.blit(self.title,self.title_rect)
        if pg.time.get_ticks() - self.timer > 1000/5.0:
            self.blink = not self.blink
            self.timer = pg.time.get_ticks()
        if self.blink:
            Surf.blit(self.escape_txt,self.escape_txt_rect)