view gamelib/main.py @ 43:2bdac178ec6f

Play with the gui stuff a bit
author Neil Muller <drnlmuller@gmail.com>
date Mon, 07 May 2012 16:51:52 +0200
parents d82d3e54a4ef
children d35a3762edda
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


pygame.init()

FPS = 30

GAME_IS_RUNNING = True

WINDOW_STACK = []

# input variables
MOUSE_DOWN = False


class ExitGameButton(BigButton):

    def __init__(self):
        super(ExitGameButton, self).__init__(((800 - 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__(((800 - 128) / 2, 200), '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__(((800 - 128) / 2, 300), 'Quit')

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


def main():
    clock = Clock()
    screen = pygame.display.set_mode((800, 600))
    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[len(WINDOW_STACK) - 1].on_mouse_up(event.pos)
            elif event.type == MOUSEMOTION:
                WINDOW_STACK[len(WINDOW_STACK) - 1].on_mouse_move(event.pos)
        elif not MOUSE_DOWN and event.type == MOUSEBUTTONDOWN:
            MOUSE_DOWN = True
            WINDOW_STACK[len(WINDOW_STACK) - 1].on_mouse_down(event.pos)
        elif event.type == QUIT:
            GAME_IS_RUNNING = False