gameobjects.py 2.18 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
import pygame
from subpixelsurface import *

class AppGame:

    RESOLUTION = [640, 480]
    FRAMERATE = 60

    background_color = (0, 0, 0)

    def on_setup(self):
        pass

    def on_gameloop(self):
        pass

    def on_keydown_event(self, event):
        if event.key == pygame.K_ESCAPE:
            self.quit()

    def run(self):
        pygame.init()
        self.screen = pygame.display.set_mode(self.RESOLUTION)
        self.clock = pygame.time.Clock()
        self.on_setup()
        while True:
            self.dt = self.clock.tick(self.FRAMERATE) / 1000.0
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.quit()
                elif event.type == pygame.KEYDOWN:
                    self.on_keydown_event(event)
            self.on_gameloop()
            pygame.display.update()


    def quit(self):
        pygame.quit()
        raise SystemExit(0)


class Sprite:
    running = True

    def __init__(self, app, size, color, pos=(0, 0), vel=(0, 0)):
        self.app = app
        self.surface = pygame.Surface(size)
        self.surface.fill(color)
        self.surface.convert()

        self.subpixel_surf = SubPixelSurface(self.surface)

        self.pos, self.vel, self.size = list(pos), list(vel), tuple(size)

    @property
    def w(self):
        return self.size[0]

    @property
    def h(self):
        return self.size[1]

    @property
    def x(self):
        return self.pos[0]

    @x.setter
    def x(self, value):
        self.pos[0] = value

    @property
    def y(self):
        return self.pos[1]

    @y.setter
    def y(self, value):
        self.pos[1] = value

    def run(self, dt):
        # if not self.running: return
        self.pos[0] += dt * self.vel[0]
        self.pos[1] += dt * self.vel[1]

    def draw(self, surface):
        surface.blit(self.surface, self.pos)

    # def draw(self, surface):
    #     surface.blit(self.subpixel_surf.at(self.x, self.y), self.pos)

    def rectcollide_with(self, sprite):
        return (self.x < sprite.x + sprite.w and
                self.x + self.w > sprite.x   and
                self.y < sprite.y + sprite.h and
                self.y + self.h > sprite.y)