Mercurial > sypikslang
view gamelib/mainmenu.py @ 228:3955d126ca26
merge
author | Rizmari Versfeld <rizziepit@gmail.com> |
---|---|
date | Sat, 12 May 2012 23:09:33 +0200 |
parents | ebb62654f61f |
children | 64ec8ff87c6e |
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__((400, 100), '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__((400, 170), 'Resume Game') self.parent = parent def on_click(self): self.parent.resume_game() class QuitButton(MainMenuButton): def __init__(self): super(QuitButton, self).__init__((400, 240), '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/main_background.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() try: self.game_window = LabWindow(self.screen, game_data) if game_data: self.add_resume() except Exception, e: print 'Error loading autosave (%r) - ignoring' % (e,) # 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)