view gamelib/main.py @ 48:a2980cc9a060

Factor out some constants
author Neil Muller <drnlmuller@gmail.com>
date Mon, 07 May 2012 21:23:54 +0200
parents d35a3762edda
children ac637e84f8f8
line wrap: on
line source

'''Game main module.

Contains the entry point used by the run_game.py script.

Feel free to put all your game code here, or in other modules in this "gamelib"
package.
'''
import pygame
from pygame.locals import MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION, QUIT
from pygame.time import Clock

from gamelib.gui_base import Window
from gamelib.gui import BigButton
from gamelib.constants import WIDTH, HEIGHT, SCREEN, FPS


pygame.init()

GAME_IS_RUNNING = True

WINDOW_STACK = []

# input variables
MOUSE_DOWN = False


class ExitGameButton(BigButton):

    def __init__(self):
        super(ExitGameButton, self).__init__(((WIDTH - 128), 10), 'Exit')

    def on_click(self):
        WINDOW_STACK.pop()


class GameWindow(Window):
    """Main window for the game"""

    def __init__(self, screen):
        super(GameWindow, self).__init__(screen)
        exit = ExitGameButton()
        self.add_child(exit)


class StartButton(BigButton):

    def __init__(self, screen):
        super(StartButton, self).__init__(((WIDTH - 128) / 2, HEIGHT / 2),
                'Start')
        self.screen = screen

    def on_click(self):
        game_window = GameWindow(self.screen)
        WINDOW_STACK.append(game_window)


class QuitButton(BigButton):

    def __init__(self):
        super(QuitButton, self).__init__(((WIDTH - 128) / 2,
            HEIGHT / 2 + 100), 'Quit')

    def on_click(self):
        pygame.event.post(pygame.event.Event(pygame.QUIT))


def main():
    clock = Clock()
    screen = pygame.display.set_mode(SCREEN)
    window = Window(screen)
    window.background_colour = (0, 0, 0)
    button1 = StartButton(screen)
    window.add_child(button1)
    button2 = QuitButton()
    window.add_child(button2)
    WINDOW_STACK.append(window)
    while GAME_IS_RUNNING:
        process_input()
        draw(screen)
        clock.tick(FPS)


def draw(screen):
    for view in WINDOW_STACK:
        view.draw(screen)
    pygame.display.flip()


def process_input():
    global MOUSE_DOWN
    global GAME_IS_RUNNING
    for event in pygame.event.get():
        if MOUSE_DOWN:
            if event.type == MOUSEBUTTONUP:
                MOUSE_DOWN = False
                WINDOW_STACK[-1].on_mouse_up(event.pos)
            elif event.type == MOUSEMOTION:
                WINDOW_STACK[-1].on_mouse_move(event.pos)
        elif not MOUSE_DOWN and event.type == MOUSEBUTTONDOWN:
            MOUSE_DOWN = True
            WINDOW_STACK[-1].on_mouse_down(event.pos)
        elif event.type == QUIT:
            GAME_IS_RUNNING = False