Source

gallox / gallox / ui / game.py

# game ui
import os
import math

import pygame

from gallox.utils import load_image
from gallox.settings import *

def draw_line(surf, color, start, stop, width):
    x1, y1 = start
    x2, y2 = stop
    w = width / 2.
    if x1 == x2:
        points = [(x1-w, y1), (x1+w, y1), (x1+w, y2), (x1-w, y2)]
    elif y1 == y2:
        points = [(x1, y1-w), (x1, y1+w), (x2, y1+w), (x2, y1-w)]
    else:
        orig_m = float(y2-y1) / float(x2-x1)
        m = - 1. / orig_m
        l = math.sqrt(1+m*m)
        n = width/ (2.*l)
        points = [(x+n*i, y+n*m*i) for (x, y), i in (((x1, y1), 1), 
                  ((x2, y2), 1), ((x2, y2), -1), ((x1, y1), -1))]
        
    return pygame.draw.polygon(surf, color, points)

class StatusOverlay(object):
    def __init__(self, pos, size, world):
        self.world = world
        self.player = world.map.ship
        self.rect = pygame.Rect((0,0), size)
        self.bg = pygame.Surface(size, pygame.SRCALPHA)
        self.bg.fill((0,0,0,0)) 
        fuel,r = load_image(os.path.join(PROJECT_DIR, "data", "ui", "fuel.png"),
                          alpha=True)
        self.bg.blit(fuel, fuel.get_rect(bottomright=self.rect.bottomright))
        
        
        self.rect.topleft = pos
        
    def update(self, events):
        return events
    
    def draw(self, screen):
        screen.blit(self.bg, self.rect)
        
        # draw fuel gauge
        fuel_angle = math.radians(90 * self.player.fuel / 100.)
        start = self.rect.right - 4, self.rect.bottom - 4
        r = 30
        stop1 = (start[0] - math.cos(fuel_angle) * r,
                start[1] - math.sin(fuel_angle) * r)
        r += 10
        stop2 = (start[0] - math.cos(fuel_angle) * r,
                start[1] - math.sin(fuel_angle) * r)
        # get missing points for the arrow head
        x1,y1 = start
        x2,y2 = stop1
        # avoid zero division errors
        if x1==x2:
            x2 -= 0.0001
        if y1==y2:
            y2 -= 0.0001
        width = 5
        orig_m = float(y2-y1) / float(x2-x1)
        m = - 1. / orig_m
        l = math.sqrt(1+m*m)
        n = width/ (2.*l)

        p1,p2 = [(x+n*i, y+n*m*i) for (x, y), i in (((x2, y2), 1), ((x2, y2), -1))]
        # draw the line
        pygame.draw.aaline(screen, (0,0,0), start, stop1, 1)
        # draw the arrow head
        for a,b in ((p1,p2), (p2,stop2), (stop2,p1)):
            pygame.draw.aaline(screen, (0,0,0), a, b, 1)