Source

pymissile / menu.py

import pygame

from resource import render_cached
from scene import Scene
from constants import *
from sound import play_dark

class Menu(Scene):
  
  key = 'Menu'
  
  def __init__(self, game):
    super(Menu, self).__init__(game)
    self._menu = {'New Game': lambda: self._game.navigate('battle'),
                  'Options': lambda: None,
                  'Highscore': lambda: None,
                  'Exit': lambda: None}
                  
    self._event_handler = {pygame.MOUSEMOTION: self._highlight_menu_item,
                           pygame.MOUSEBUTTONUP: self._handle_menu_click}

    self._highlight = -1
    self._rects = {}
    self._back_step = 20
    self._back_timer = 3
    self._background_org = pygame.transform.scale(pygame.image.load('back.jpg'), (SCREEN_WIDTH, SCREEN_HEIGHT)).convert()
    self._next_back_step()

  def enter(self, **kwargs):
    play_dark()

  def _next_back_step(self):
    if self._back_step <= 1: return
    self._back_step -= 1
    self._background = pygame.transform.smoothscale(self._background_org, (SCREEN_WIDTH/self._back_step, SCREEN_HEIGHT/self._back_step))
    self._background = pygame.transform.smoothscale(self._background, (SCREEN_WIDTH, SCREEN_HEIGHT))

  def _handle_menu_click(self, event):
    if self._highlight == -1:
      return

    self._menu.items()[self._highlight][1]()

  def _highlight_menu_item(self, event):
    self._highlight = -1
    pos = pygame.mouse.get_pos()
    try: self._highlight = next(i for (i, r) in self._rects.items() if r.collidepoint(pos))
    except StopIteration: pass

  def update_state(self):
    self._back_timer -= 1
    if not self._back_timer:
      self._back_timer = 3
      self._next_back_step()
    
  def draw_state(self, screen):
    super(Menu, self).draw_state(screen)
    self._rects = {}
    for i, text in enumerate(self._menu):
      pos = (50, 100 + i * 40)
      color = GREYGREEN if i == self._highlight else DINGLEY
      surf = render_cached('big', text, color)
      self._rects[i] = pygame.rect.Rect(pos[0], pos[1], surf.get_width(), surf.get_height())
      screen.blit(surf, pos)