Mercurial > sypikslang
view gamelib/mainmenu.py @ 131:31ab0af26bb5
Load milestone as well
author | Neil Muller <drnlmuller@gmail.com> |
---|---|
date | Thu, 10 May 2012 16:50:09 +0200 |
parents | e386ec5d179b |
children | 1a648d07d67e |
line wrap: on
line source
# -*- coding: utf-8 -*- # vim:fileencoding=utf-8 ai ts=4 sts=4 et sw=4 """The main menu""" import pygame import os from pygame import image try: import simplejson json = simplejson except ImportError: import json from gamelib import data from gamelib.gui_base import Window from gamelib.gui import BigButton from gamelib.engine import AddWindow from gamelib.gamegui import LabWindow from gamelib.constants import WIDTH, HEIGHT from gamelib.game_base import get_save_filename class MainMenuButton(BigButton): WIDTH = 276 HEIGHT = 75 BG_IMAGE_NORMAL = image.load(data.filepath('images/main_normal.png')) BG_IMAGE_DOWN = image.load(data.filepath('images/main_down.png')) class NewGameButton(MainMenuButton): def __init__(self, parent): super(NewGameButton, self).__init__(((WIDTH - self.WIDTH) / 2, (HEIGHT - self.HEIGHT) / 2 - self.HEIGHT), 'Start New Game') self.parent = parent def on_click(self): self.parent.start_new_game() class ResumeGameButton(MainMenuButton): def __init__(self, parent): super(ResumeGameButton, self).__init__(((WIDTH - self.WIDTH) / 2, (HEIGHT - self.HEIGHT) / 2), 'Resume Game') self.parent = parent def on_click(self): self.parent.resume_game() class QuitButton(MainMenuButton): def __init__(self): super(QuitButton, self).__init__(((WIDTH - self.WIDTH) / 2, (HEIGHT - self.HEIGHT) / 2 + self.HEIGHT), 'Quit') def on_click(self): pygame.event.post(pygame.event.Event(pygame.QUIT)) class MainMenu(Window): def __init__(self, screen, savefile): super(MainMenu, self).__init__(screen) self.game_window = None self.resume = None self.screen = screen self.background_colour = (0, 0, 0) self.background_image = image.load(data.filepath('images/temp.jpg')) button1 = NewGameButton(self) self.add_child(button1) button2 = QuitButton() self.add_child(button2) if savefile: self.load_game(savefile) else: # See if we have an autosave file savefile = get_save_filename() if os.path.exists(savefile): self.load_game(savefile) def start_new_game(self): self.game_window = LabWindow(self.screen, None) self.add_resume() AddWindow.post(self.game_window) def load_game(self, savefile): if os.access(savefile, os.R_OK): f = open(savefile, 'r') try: game_data = json.load(f) except json.JSONDecodeError: print 'Unable to load the autosave file - skipping' game_data = None f.close() self.game_window = LabWindow(self.screen, game_data) if game_data: self.add_resume() # We stay at the main menu, so the user can can to continue or not def add_resume(self): if not self.resume: # Add the resume button self.resume = ResumeGameButton(self) self.add_child(self.resume) def game_over(self): if self.resume: self.remove_child(self.resume) self.resume = None def resume_game(self): AddWindow.post(self.game_window)