2017-10-12 15:29:55 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# main.py - main module, starts game and main loop
|
|
|
|
# This file is part of brutalmaze
|
|
|
|
#
|
|
|
|
# brutalmaze is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# brutalmaze is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with brutalmaze. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
#
|
|
|
|
# Copyright (C) 2017 Nguyễn Gia Phong
|
|
|
|
|
2018-02-18 19:01:14 +01:00
|
|
|
__version__ = '0.5.3'
|
2018-02-13 14:51:41 +01:00
|
|
|
|
2018-02-08 14:41:08 +01:00
|
|
|
import re
|
2018-02-14 16:26:52 +01:00
|
|
|
from argparse import ArgumentParser, FileType, RawTextHelpFormatter
|
2017-10-19 10:24:56 +02:00
|
|
|
from collections import deque
|
2018-02-08 14:41:08 +01:00
|
|
|
try: # Python 3
|
2018-02-16 14:25:32 +01:00
|
|
|
from configparser import ConfigParser
|
2018-02-08 14:41:08 +01:00
|
|
|
except ImportError: # Python 2
|
2018-02-16 14:25:32 +01:00
|
|
|
from ConfigParser import ConfigParser
|
2018-02-13 14:51:41 +01:00
|
|
|
from os.path import join, pathsep
|
2018-02-14 16:26:52 +01:00
|
|
|
from sys import stdout
|
2018-02-13 14:51:41 +01:00
|
|
|
|
2017-10-19 10:24:56 +02:00
|
|
|
|
2017-10-12 15:29:55 +02:00
|
|
|
import pygame
|
2018-02-08 14:41:08 +01:00
|
|
|
from pygame import DOUBLEBUF, KEYDOWN, OPENGL, QUIT, RESIZABLE, VIDEORESIZE
|
2018-02-16 14:25:32 +01:00
|
|
|
from pygame.time import Clock, get_ticks
|
2018-02-13 14:51:41 +01:00
|
|
|
from appdirs import AppDirs
|
2017-10-12 15:29:55 +02:00
|
|
|
|
2018-02-19 10:55:55 +01:00
|
|
|
from .constants import SETTINGS, ICON, MUSIC, HERO_SPEED
|
2017-10-12 15:29:55 +02:00
|
|
|
from .maze import Maze
|
2018-02-16 14:25:32 +01:00
|
|
|
from .misc import sign
|
2018-02-08 14:41:08 +01:00
|
|
|
|
|
|
|
|
2018-02-13 14:51:41 +01:00
|
|
|
class ConfigReader:
|
|
|
|
"""Object reading and processing INI configuration file for
|
|
|
|
Brutal Maze.
|
2018-02-08 14:41:08 +01:00
|
|
|
"""
|
2018-02-19 10:55:55 +01:00
|
|
|
CONTROL_ALIASES = (('New game', 'new'), ('Toggle pause', 'pause'),
|
|
|
|
('Toggle mute', 'mute'),
|
2018-02-16 14:25:32 +01:00
|
|
|
('Move left', 'left'), ('Move right', 'right'),
|
|
|
|
('Move up', 'up'), ('Move down', 'down'),
|
|
|
|
('Long-range attack', 'shot'),
|
|
|
|
('Close-range attack', 'slash'))
|
2018-02-13 14:51:41 +01:00
|
|
|
WEIRD_MOUSE_ERR = '{}: Mouse is not a suitable control'
|
|
|
|
INVALID_CONTROL_ERR = '{}: {} is not recognized as a valid control key'
|
|
|
|
|
|
|
|
def __init__(self, filenames):
|
|
|
|
self.config = ConfigParser()
|
2018-02-14 16:26:52 +01:00
|
|
|
self.config.read(SETTINGS) # default configuration
|
2018-02-13 14:51:41 +01:00
|
|
|
self.config.read(filenames)
|
|
|
|
|
2018-02-19 10:55:55 +01:00
|
|
|
def parse_output(self):
|
|
|
|
"""Parse graphics and sound configurations."""
|
2018-02-14 16:26:52 +01:00
|
|
|
self.size = (self.config.getint('Graphics', 'Screen width'),
|
|
|
|
self.config.getint('Graphics', 'Screen height'))
|
|
|
|
self.opengl = self.config.getboolean('Graphics', 'OpenGL')
|
2018-02-18 19:01:14 +01:00
|
|
|
self.max_fps = self.config.getint('Graphics', 'Maximum FPS')
|
2018-02-19 10:55:55 +01:00
|
|
|
self.muted = self.config.getboolean('Sound', 'Muted')
|
|
|
|
self.musicvol = self.config.getfloat('Sound', 'Music volume')
|
2018-02-13 14:51:41 +01:00
|
|
|
|
|
|
|
def parse_control(self):
|
|
|
|
"""Parse control configurations."""
|
|
|
|
self.key, self.mouse = {}, {}
|
2018-02-14 16:26:52 +01:00
|
|
|
for cmd, alias in self.CONTROL_ALIASES:
|
|
|
|
i = self.config.get('Control', cmd)
|
|
|
|
if re.match('mouse[1-3]$', i.lower()):
|
2018-02-13 14:51:41 +01:00
|
|
|
if alias not in ('shot', 'slash'):
|
|
|
|
raise ValueError(self.WEIRD_MOUSE_ERR.format(cmd))
|
|
|
|
self.mouse[alias] = int(i[-1]) - 1
|
|
|
|
continue
|
|
|
|
if len(i) == 1:
|
2018-02-14 16:26:52 +01:00
|
|
|
self.key[alias] = ord(i.lower())
|
2018-02-13 14:51:41 +01:00
|
|
|
continue
|
|
|
|
try:
|
|
|
|
self.key[alias] = getattr(pygame, 'K_{}'.format(i.upper()))
|
|
|
|
except AttributeError:
|
|
|
|
raise ValueError(self.INVALID_CONTROL_ERR.format(cmd, i))
|
|
|
|
|
|
|
|
def read_args(self, arguments):
|
|
|
|
"""Read and parse a ArgumentParser.Namespace."""
|
2018-02-19 10:55:55 +01:00
|
|
|
for option in 'size', 'opengl', 'max_fps', 'muted', 'musicvol':
|
|
|
|
value = getattr(arguments, option)
|
|
|
|
if value is not None: setattr(self, option, value)
|
2017-10-12 15:29:55 +02:00
|
|
|
|
|
|
|
|
2018-02-16 14:25:32 +01:00
|
|
|
class Game:
|
|
|
|
"""Object handling main loop and IO."""
|
2018-02-19 10:55:55 +01:00
|
|
|
def __init__(self, size, scrtype, max_fps, muted, musicvol, key, mouse):
|
2018-02-16 14:25:32 +01:00
|
|
|
pygame.mixer.pre_init(frequency=44100)
|
|
|
|
pygame.init()
|
2018-02-19 10:55:55 +01:00
|
|
|
if muted:
|
|
|
|
pygame.mixer.quit()
|
|
|
|
else:
|
|
|
|
pygame.mixer.music.load(MUSIC)
|
|
|
|
pygame.mixer.music.set_volume(musicvol)
|
|
|
|
pygame.mixer.music.play(-1)
|
2018-02-16 14:25:32 +01:00
|
|
|
pygame.display.set_icon(ICON)
|
|
|
|
pygame.fastevent.init()
|
2018-02-18 19:01:14 +01:00
|
|
|
# self.fps is a float to make sure floordiv won't be used in Python 2
|
|
|
|
self.max_fps, self.fps = max_fps, float(max_fps)
|
2018-02-19 10:55:55 +01:00
|
|
|
self.musicvol = musicvol
|
2018-02-18 19:01:14 +01:00
|
|
|
self.key, self.mouse = key, mouse
|
2018-02-16 14:25:32 +01:00
|
|
|
self.maze = Maze(max_fps, size, scrtype)
|
|
|
|
self.hero = self.maze.hero
|
2018-02-19 10:55:55 +01:00
|
|
|
self.clock, self.paused = Clock(), False
|
2018-02-16 14:25:32 +01:00
|
|
|
|
|
|
|
def __enter__(self): return self
|
|
|
|
|
|
|
|
def move(self, x, y):
|
|
|
|
"""Command the hero to move faster in the given direction."""
|
|
|
|
stunned = pygame.time.get_ticks() < self.maze.next_move
|
|
|
|
velocity = self.maze.distance * HERO_SPEED / self.fps
|
|
|
|
accel = velocity * HERO_SPEED / self.fps
|
|
|
|
|
|
|
|
if stunned or not x:
|
|
|
|
self.maze.vx -= sign(self.maze.vx) * accel
|
|
|
|
if abs(self.maze.vx) < accel * 2: self.maze.vx = 0.0
|
|
|
|
elif x * self.maze.vx < 0:
|
|
|
|
self.maze.vx += x * 2 * accel
|
|
|
|
else:
|
|
|
|
self.maze.vx += x * accel
|
|
|
|
if abs(self.maze.vx) > velocity: self.maze.vx = x * velocity
|
|
|
|
|
|
|
|
if stunned or not y:
|
|
|
|
self.maze.vy -= sign(self.maze.vy) * accel
|
|
|
|
if abs(self.maze.vy) < accel * 2: self.maze.vy = 0.0
|
|
|
|
elif y * self.maze.vy < 0:
|
|
|
|
self.maze.vy += y * 2 * accel
|
|
|
|
else:
|
|
|
|
self.maze.vy += y * accel
|
|
|
|
if abs(self.maze.vy) > velocity: self.maze.vy = y * velocity
|
|
|
|
|
|
|
|
def loop(self):
|
|
|
|
"""Start and handle main loop."""
|
|
|
|
events = pygame.fastevent.get()
|
|
|
|
for event in events:
|
|
|
|
if event.type == QUIT:
|
|
|
|
return False
|
|
|
|
elif event.type == VIDEORESIZE:
|
|
|
|
self.maze.resize((event.w, event.h))
|
|
|
|
elif event.type == KEYDOWN:
|
|
|
|
if event.key == self.key['new']:
|
|
|
|
self.maze.__init__(self.fps)
|
|
|
|
elif event.key == self.key['pause'] and not self.hero.dead:
|
|
|
|
self.paused ^= True
|
2018-02-19 10:55:55 +01:00
|
|
|
elif event.key == self.key['mute']:
|
|
|
|
if pygame.mixer.get_init() is None:
|
|
|
|
pygame.mixer.init(frequency=44100)
|
|
|
|
pygame.mixer.music.load(MUSIC)
|
|
|
|
pygame.mixer.music.set_volume(self.musicvol)
|
|
|
|
pygame.mixer.music.play(-1)
|
|
|
|
else:
|
|
|
|
pygame.mixer.quit()
|
2018-02-16 14:25:32 +01:00
|
|
|
|
|
|
|
if not self.hero.dead:
|
|
|
|
keys = pygame.key.get_pressed()
|
|
|
|
self.move(keys[self.key['left']] - keys[self.key['right']],
|
|
|
|
keys[self.key['up']] - keys[self.key['down']])
|
|
|
|
buttons = pygame.mouse.get_pressed()
|
|
|
|
try:
|
|
|
|
self.hero.firing = keys[self.key['shot']]
|
|
|
|
except KeyError:
|
|
|
|
self.hero.firing = buttons[self.mouse['shot']]
|
|
|
|
try:
|
|
|
|
self.hero.slashing = keys[self.key['slash']]
|
|
|
|
except KeyError:
|
|
|
|
self.hero.slashing = buttons[self.mouse['slash']]
|
|
|
|
|
2018-02-18 19:01:14 +01:00
|
|
|
# Compare current FPS with the average of the last 10 frames
|
|
|
|
new_fps = self.clock.get_fps()
|
|
|
|
if new_fps < self.fps:
|
|
|
|
self.fps -= 1
|
|
|
|
elif self.fps < self.max_fps and not self.paused:
|
|
|
|
self.fps += 5
|
2018-02-16 14:25:32 +01:00
|
|
|
if not self.paused: self.maze.update(self.fps)
|
|
|
|
self.clock.tick(self.fps)
|
|
|
|
return True
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback): pygame.quit()
|
|
|
|
|
|
|
|
|
2017-10-12 15:29:55 +02:00
|
|
|
def main():
|
2017-10-16 17:12:32 +02:00
|
|
|
"""Start game and main loop."""
|
2018-02-02 17:33:22 +01:00
|
|
|
# Read configuration file
|
2018-02-13 14:51:41 +01:00
|
|
|
dirs = AppDirs(appname='brutalmaze', appauthor=False, multipath=True)
|
|
|
|
parents = dirs.site_config_dir.split(pathsep)
|
|
|
|
parents.append(dirs.user_config_dir)
|
|
|
|
filenames = [join(parent, 'settings.ini') for parent in parents]
|
|
|
|
config = ConfigReader(filenames)
|
2018-02-19 10:55:55 +01:00
|
|
|
config.parse_output()
|
2018-02-13 14:51:41 +01:00
|
|
|
|
2018-02-13 16:17:04 +01:00
|
|
|
# Parse command-line arguments
|
2018-02-13 14:51:41 +01:00
|
|
|
parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
|
|
|
|
parser.add_argument('-v', '--version', action='version',
|
|
|
|
version='Brutal Maze {}'.format(__version__))
|
2018-02-14 16:26:52 +01:00
|
|
|
parser.add_argument(
|
|
|
|
'--write-config', nargs='?', const=stdout, type=FileType('w'),
|
|
|
|
metavar='PATH', dest='defaultcfg',
|
|
|
|
help='write default config and exit, if PATH not specified use stdout')
|
2018-02-13 14:51:41 +01:00
|
|
|
parser.add_argument(
|
|
|
|
'-c', '--config', metavar='PATH',
|
|
|
|
help='location of the configuration file (fallback: {})'.format(
|
|
|
|
pathsep.join(filenames)))
|
|
|
|
parser.add_argument(
|
|
|
|
'-s', '--size', type=int, nargs=2, metavar=('X', 'Y'),
|
2018-02-14 16:26:52 +01:00
|
|
|
help='the desired screen size (fallback: {}x{})'.format(*config.size))
|
2018-02-13 14:51:41 +01:00
|
|
|
parser.add_argument(
|
|
|
|
'--opengl', action='store_true', default=None,
|
|
|
|
help='enable OpenGL (fallback: {})'.format(config.opengl))
|
|
|
|
parser.add_argument('--no-opengl', action='store_false', dest='opengl',
|
|
|
|
help='disable OpenGL')
|
|
|
|
parser.add_argument(
|
2018-02-18 19:01:14 +01:00
|
|
|
'-f', '--max-fps', type=int, metavar='FPS',
|
2018-02-13 14:51:41 +01:00
|
|
|
help='the desired maximum FPS (fallback: {})'.format(config.max_fps))
|
2018-02-19 10:55:55 +01:00
|
|
|
parser.add_argument(
|
|
|
|
'--mute', '-m', action='store_true', default=None,
|
|
|
|
help='mute all sounds (fallback: {})'.format(config.muted))
|
|
|
|
parser.add_argument('--unmute', action='store_false', dest='muted',
|
|
|
|
help='unmute sound')
|
|
|
|
parser.add_argument(
|
|
|
|
'--music-volume', type=float, metavar='VOL', dest='musicvol',
|
|
|
|
help='between 0.0 and 1.0 (fallback: {})'.format(config.musicvol))
|
2018-02-13 14:51:41 +01:00
|
|
|
args = parser.parse_args()
|
2018-02-14 16:26:52 +01:00
|
|
|
if args.defaultcfg is not None:
|
|
|
|
with open(SETTINGS) as settings: args.defaultcfg.write(settings.read())
|
|
|
|
args.defaultcfg.close()
|
|
|
|
exit()
|
2018-02-13 14:51:41 +01:00
|
|
|
|
|
|
|
# Manipulate config
|
|
|
|
if args.config: config.config.read(args.config)
|
|
|
|
config.read_args(args)
|
2018-02-19 10:55:55 +01:00
|
|
|
config.parse_output()
|
2018-02-13 14:51:41 +01:00
|
|
|
config.parse_control()
|
2018-02-02 17:33:22 +01:00
|
|
|
|
|
|
|
# Main loop
|
2018-02-16 14:25:32 +01:00
|
|
|
scrtype = (config.opengl and DOUBLEBUF|OPENGL) | RESIZABLE
|
2018-02-19 10:55:55 +01:00
|
|
|
with Game(config.size, scrtype, config.max_fps, config.muted,
|
|
|
|
config.musicvol, config.key, config.mouse) as game:
|
2018-02-16 14:25:32 +01:00
|
|
|
while game.loop(): pass
|