Some improvements towards PEP-8

small-fixes-for-0.3.3
Max Lange 8 years ago
parent 1f088f82ec
commit 84650dfc15

3
.gitignore vendored

@ -11,6 +11,9 @@
#the Ninja project file
**.nja
#The Flake8 config file
**tox.ini
#empty folders
screenshots/*
assets/sprites/player/*

@ -13,8 +13,9 @@ try:
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
# checks if font module is availible
pygame.font
#Checks for correct version
# Checks for correct version
if pygame.version.ver < "1.9.1":
raise SystemExit("Old Pygame version: " + pygame.version.ver)
if sys.version[:5] < "2.7.6":
@ -22,20 +23,20 @@ try:
if sys.version[:5] >= "3.0.0":
raise SystemExit("No support for Python3")
#Run the game
# Run the game
from src import main
main.void()
#Handeling errors
# Handeling errors
except ImportError as message:
if str(message)[len(str(message)) - 6:] == "pygame": # pygame not installed
raise SystemExit("Pygame not installed")
else:
#unknown import error
# unknown import error
print (("ERROR IMPORTING MODULES: %s" % message))
raise SystemExit(traceback.format_exc())
except AttributeError as detail:
#excuted if font module is not installed
# excuted if font module is not installed
detail = str(detail)
print(detail)
if detail[len(detail) - 5:][:4] == "font": # Basicly the name of the module
@ -45,7 +46,7 @@ except AttributeError as detail:
print("")
raise SystemExit(traceback.format_exc())
except Exception as detail:
#general errors
# general errors
print(("Unexpected error:", sys.exc_info()[0]))
print("")
raise SystemExit(traceback.format_exc())
raise SystemExit(traceback.format_exc())

@ -32,4 +32,4 @@ def read(filename, variable):
ident = line.index("<")
varname = (line[ident + 2:line.index("=") - 1]).strip()
if varname == variable:
return line[line.index("=") + 1:].strip()
return line[line.index("=") + 1:].strip()

@ -57,14 +57,14 @@ class create_menu():
if len(line) < 1 or line[0] == "/":
continue
#This checks for the identation
# This checks for the identation
ident = 0
if line[0] == "~":
ident = line[:line.index("|") - 1].count("~") # Counts identation marks
line = line[ident:] # removes identation marks for analysis
#Here are the diferent types of elements
#and comments that can be used
# Here are the diferent types of elements
# and comments that can be used
if line[0] == "&": # An import of existing variables
file2 = line[1:]
self.vars.update(create_menu(file2, {}, pygame.Rect(1, 1, 1, 1)).vars)
@ -77,9 +77,9 @@ class create_menu():
self.vars[var[1:]] = float(elem)
if var[0] == "#": # A desing variable
elems = convert2list(elem)
#this adds non-existing types
#(hoverover and klicked)
#to the desing if they are missing
# this adds non-existing types
# (hoverover and klicked)
# to the desing if they are missing
try:
elems[len(elems) - 1] = int(elems[len(elems) - 1])
if len(elems) == 2:
@ -128,15 +128,9 @@ class create_menu():
self.elems["surfs"][text] = [pygame.image.load(img[0]).convert_alpha(),
pygame.Rect(
(
(ref.w * rel_x) + abs_x,
(ref.h * rel_y) + abs_y,
),
(
0,
0
)
)]
((ref.w * rel_x) + abs_x,
(ref.h * rel_y) + abs_y,),
(0, 0))]
all_elems[elem_id] = self.elems["surfs"][text]
elem_id += 1
@ -197,9 +191,9 @@ class create_menu():
text = self.vars[text[1:]]
content = text
#Determines wether relation argument is given
# Determines wether relation argument is given
are_additional_arguments = 1 if ident > 0 else 0
#Through relation argument there might be another "|"
# Through relation argument there might be another "|"
if line.count("|") == 5 + are_additional_arguments:
imagemode = True
line = line[line.index("|") + 1:].lstrip()
@ -250,8 +244,8 @@ class create_menu():
quit()
if ident > 0:
#Reads the relation point
#(Topleft, Topright, Bottomleft, Bottomright)
# Reads the relation point
# (Topleft, Topright, Bottomleft, Bottomright)
line = line[line.index("|") + 1:].lstrip()
if line[0] == "$":
relation = self.vars[line[1: line.index("|")].strip()]
@ -263,10 +257,10 @@ class create_menu():
rel_x, abs_x = analyse_num(line[0: line.index("|")].strip(), self.vars)
line = line[line.index("|") + 1:-1].lstrip()
rel_y, abs_y = analyse_num(line, self.vars)
#If relative to another button
# If relative to another button
if ident > 0:
if type(all_elems[elem_id - 1]) != type(pygame.Surface):
#Adds absolute x and y value to current slider
# Adds absolute x and y value to current slider
if relation[:3] == "top":
abs_y += all_elems[elem_id - 1].pos.top
if relation[:6] == "bottom":
@ -275,7 +269,7 @@ class create_menu():
abs_x += all_elems[elem_id - 1].pos.left
if relation[-5:] == "right":
abs_x += all_elems[elem_id - 1].pos.right
#Ignores relative placement
# Ignores relative placement
rel_x = 0
rel_y = 0
@ -285,8 +279,8 @@ class create_menu():
typeface, size, ratio, color, design[:3]))
all_elems[elem_id] = self.elems["buttons"][-1]
elem_id += 1
#Centers non-relative buttons so their center is on the
#given x and y coordiante
# Centers non-relative buttons so their center is on the
# given x and y coordiante
if ident == 0:
self.elems["buttons"][-1].center()
@ -297,9 +291,9 @@ class create_menu():
if text[0] == "$":
text = self.vars[text[1:]]
#Determines wether relation argument is given
# Determines wether relation argument is given
additional_arguments = 1 if ident > 0 else 0
#Through relation argument there might be another "|"
# Through relation argument there might be another "|"
if line.count("|") == 10 + additional_arguments:
line = line[line.index("|") + 1:].lstrip()
if line[0] == "$":
@ -325,7 +319,6 @@ class create_menu():
options = False
line = line[line.index("|") + 1:].lstrip()
if line.strip()[0] == "$":
#print line[1: line.index("|")].strip()
default_value = float(self.vars[line[1: line.index("|")].strip()])
else:
default_value = float(line[: line.index("|")].strip())
@ -364,8 +357,8 @@ class create_menu():
quit()
if ident > 0:
#Reads the relation point
#(Topleft, Topright, Bottomleft, Bottomright)
# Reads the relation point
# (Topleft, Topright, Bottomleft, Bottomright)
line = line[line.index("|") + 1:].lstrip()
if line[0] == "$":
relation = self.vars[line[1: line.index("|")].strip()]
@ -381,7 +374,7 @@ class create_menu():
if ident > 0:
if type(all_elems[elem_id - 1]) != type(pygame.Surface):
#Adds absolute x and y value to current slider
# Adds absolute x and y value to current slider
if relation[:3] == "top":
abs_y += all_elems[elem_id - 1].pos.top
if relation[:6] == "bottom":
@ -390,7 +383,7 @@ class create_menu():
abs_x += all_elems[elem_id - 1].pos.left
if relation[-5:] == "right":
abs_x += all_elems[elem_id - 1].pos.right
#Ignores relative placement
# Ignores relative placement
rel_x = 0
rel_y = 0
@ -438,4 +431,4 @@ class create_menu():
for elem in self.elems:
if type(elem) != pygame.Surface:
if elem.name == name:
return elem
return elem

@ -6,7 +6,7 @@ import string
def modrender(typeface, size, text, antialias, color, maxsize, borderoff):
#local typeface!
# local typeface!
nofit = True
while nofit:
tmpfont = pygame.font.SysFont(typeface, size)
@ -20,7 +20,7 @@ def modrender(typeface, size, text, antialias, color, maxsize, borderoff):
def getmaxsize(typeface, size, text, antialias, color, maxsize, borderoff):
#local typeface!
# local typeface!
nofit = True
while nofit:
tmpfont = pygame.font.SysFont(typeface, size)
@ -38,46 +38,46 @@ class button():
def __init__(self, name, rel_x, x, rel_y, y, ref, content_in, typeface,
size, ratio, color, button_designs):
"""Initalises with x and y as center point"""
#basic font and then everything should be clear
#three different instances of create_outline!
#this way three images can be generated
# basic font and then everything should be clear
# three different instances of create_outline!
# this way three images can be generated
#This prepares button for either to contain text or an image
# This prepares button for either to contain text or an image
self.isimage = False
if content_in != name: # True = Image
if type(content_in) == pygame.Surface: # Surf already exists
content = content_in
contentpos = content.get_rect()
self.isimage = True
elif type(content_in) == str: # Only string is provided, image needs loading
elif type(content_in) == str: # Only string is provided image needs loading
content = pygame.image.load(content_in).convert_alpha()
contentpos = content.get_rect()
self.isimage = True
else: # False = Font/Text
#Loads the font
# Loads the font
self.font = pygame.font.SysFont(typeface, int(size))
#renders the text and creates a rect
# renders the text and creates a rect
content = self.font.render(name, True, color)
contentpos = content.get_rect()
#creating emtpy surface that is the size of the desired button
# creating emtpy surface that is the size of the desired button
tmp_centertext_image = pygame.Surface((contentpos.h * ratio,
contentpos.h)).convert_alpha()
tmp_centertext_image.fill((0, 0, 0, 0))
tmp_center_pos = tmp_centertext_image.get_rect()
#blitting the text onto the surface
# bliting the text onto the surface
contentpos.center = tmp_center_pos.center
tmp_centertext_image.blit(content, contentpos)
#Adding image to interface
# Adding image to interface
content = tmp_centertext_image
contentpos = content.get_rect()
#saving typeface for later use
# saving typeface for later use
self.typeface = typeface
#creating ouline templates
# creating ouline templates
normal = create_outline(button_designs[0])
hover = create_outline(button_designs[0])
klick = create_outline(button_designs[0])
@ -85,20 +85,20 @@ class button():
self.state = 0
self.name = name
self.klicked = False
#calcualte absolute position
#and define rect
# calcualte absolute position
# and define rect
x = x + rel_x * float(ref.w)
y = y + rel_y * float(ref.h)
self.pos = pygame.Rect((x, y), contentpos.size)
self.move(x, y)
#move buttons and create images
#also adds content inside button
# move buttons and create images
# also adds content inside button
for num in range(len(self.buttons)):
self.buttons[num].create_box(num, self.pos)
#defines position in the middle of button
# defines position in the middle of button
contentpos.centerx = self.buttons[num].pos.centerx - self.buttons[num].pos.x
contentpos.centery = self.buttons[num].pos.centery - self.buttons[num].pos.y
#blits content centered in button
# blits content centered in button
self.buttons[num].box.blit(content, contentpos)
self.pos.size = self.buttons[0].pos.size
@ -109,17 +109,17 @@ class button():
def changetext(self, text, color):
"""Changes the text inside the button"""
#renders the text and creates a rect
# renders the text and creates a rect
content = self.font.render(text, True, color)
contentpos = content.get_rect()
#creating emtpy surface that is the size of the desired button
# creating emtpy surface that is the size of the desired button
tmp_centertext_image = pygame.Surface((contentpos.h * ratio,
contentpos.h)).convert_alpha()
tmp_centertext_image.fill((0, 0, 0, 0))
tmp_center_pos = tmp_centertext_image.get_rect()
#blitting the text onto the surface
# bliting the text onto the surface
contentpos.center = tmp_center_pos.center
tmp_centertext_image.blit(content, contentpos)
content = tmp_centertext_image
@ -134,8 +134,8 @@ class button():
self.pos = self.pos.move(x, y)
def update(self, events):
#changes image when hovered over or being clicked
#also posts a menu event to show that a button has been clicked
# changes image when hovered over or being clicked
# also posts a menu event to show that a button has been clicked
if self.pos.collidepoint(pygame.mouse.get_pos()) and not self.klicked:
self.state = 1
for event in events:
@ -283,13 +283,13 @@ class slider():
self.knob_pos.left = self.pos.left + tmp
if type(self.options_list) == bool:
#adding a "." to the end to ensure at least one is included
# adding a "." to the end to ensure at least one is included
text = str(self.value * 100)[:3] + "."
#removes "." and everything behind it
# removes "." and everything behind it
text = text[:text.index(".")]
#Adds the description and the % at the end
# Adds the description and the % at the end
text = self.name + ": " + text + "%"
#Turns text into a pygame.Surface
# Turns text into a pygame.Surface
self.render_text = self.typeface.render(text, True, self.color)
self.is_defined_list = False
else:
@ -339,7 +339,7 @@ class create_outline():
design = pygame.image.load(design)
self.color = None
#gets selected background color
# gets selected background color
if "inner_color" in self.resources:
color = convert2list(self.resources["inner_color"])
if len(color) == 3:
@ -351,18 +351,18 @@ class create_outline():
design_rect = design.get_rect()
size = design_rect.h
#extract the selected collum
# extract the selected collum
line_string = pygame.Surface((1, size))
line_string.blit(design, (0, 0), pygame.Rect(pos, 0, 1, size))
design = line_string
design_rect = design.get_rect()
self.pixels = {}
#create the final surface to blit pattern to
# create the final surface to blit pattern to
self.pattern = pygame.Surface((1, size))
#set the pixel colors for the pattern
# set the pixel colors for the pattern
for a in range(size):
self.pattern.set_at((0, a), design.get_at((0, a)))
#transforms linear pattern into a corner
# transforms linear pattern into a corner
corner = pygame.Surface((size, size))
for a in range(size):
for x in range(size):
@ -380,24 +380,24 @@ class create_outline():
width += border * 2
height += border * 2
self.top = pygame.Surface((width, border))
#creating top frame line
# creating top frame line
for pos in range(width):
self.top.blit(self.modes[mode][0], pygame.Rect(pos, 0, 0, 0))
#blit left top corner
# blit left top corner
self.top.blit(self.modes[mode][1], pygame.Rect(0, 0, 0, 0))
#blit right top corner
# blit right top corner
self.top.blit(pygame.transform.flip(self.modes[mode][1], True, False),
pygame.Rect(width - border, 0, 0, 0))
#create bottom line
# create bottom line
self.bottom = pygame.transform.flip(self.top, False, True)
#create left frame line
# create left frame line
self.left = pygame.Surface((border, height))
tmp_line = pygame.transform.rotate(self.modes[mode][0], 90)
for pos in range(height):
self.left.blit(tmp_line, pygame.Rect(0, pos, 0, 0))
#create right frame line
# create right frame line
self.right = pygame.transform.flip(self.left, True, False)
#Merge all together
# Merge all together
final = pygame.Surface((width, height), pygame.SRCALPHA)
final.fill(self.color)
final.blit(self.left, pygame.Rect(0, 0, 0, 0))
@ -408,4 +408,4 @@ class create_outline():
self.pos = self.box.get_rect()
self.pos.x = posx - border
self.pos.y = posy - border
return (self.pos, self.box)
return (self.pos, self.box)

@ -91,16 +91,16 @@ self._timeplayed (dict)
def get_music(self):
"""Return all files with given conditions."""
#Look up tygamusic.CreateQueue.__init__.__doc__ for more info
# Look up tygamusic.CreateQueue.__init__.__doc__ for more info
files = []
#Runs through all files and checks for filetype
# Runs through all files and checks for filetype
for filename in os.listdir(self._path):
supportedmusic = [
filename.endswith(".ogg") or filename.endswith(".mp3")
or filename.endswith(".mid") or filename.endswith(".midi")
or filename.endswith(".wav")]
#Adds file if it is supported format
# Adds file if it is supported format
# and doesn't begin with specified beinning
if (supportedmusic[0] and
filename[0:len(self.__exception)] != self.__exception):
@ -124,21 +124,20 @@ shouldplaynextsong (bool)
if music has ended
"""
#print self.volume
#Adjust volume to its own volume.
# Adjust volume to its own volume.
pygame.mixer.music.set_volume(self.volume)
#Adds a random song to playlist
# Adds a random song to playlist
# if it is smaller than the amount of music provided
if len(self.playlist) < len(self.files) - 1 and self.files != [None]:
self.add_random("end")
#If no events are specified pygame.event.get()
# If no events are specified pygame.event.get()
# will be called.
if type(events) == bool:
if events:
events = pygame.event.get()
else:
return
#Playes next song if the last one has ended.
# Playes next song if the last one has ended.
if self.__endevent in events and shouldplaynextsong:
self.playlist.pop(0)
self._playing = False
@ -157,41 +156,41 @@ Operations:
"unpause"
"stop"
Look up individual options's comments in sourcecode for an in depth explanation.
Look up individual options's comments below for an in depth explanation.
"""
options = list(options)
if options[0] == "play" and len(self.playlist) != 0:
#first song of playlist is played if none is playing
# first song of playlist is played if none is playing
if len(options) == 1:
options.append(0)
if len(options) == 2:
#Playes new song or loads it, if neccessary.
# Playes new song or loads it, if neccessary.
if not self._playing:
pygame.mixer.music.load(self._path + self.playlist[0])
pygame.mixer.music.play(options[1], 0)
#Add new song to dict
# Add new song to dict
self._timeplayed[self.playlist[0]] = 0
if self._playing:
pygame.mixer.music.play(options[1], 0)
self._playing = True
if options[0] == "next":
#remove old song
# remove old song
self._timeplayed[self.playlist[0]] = 0
self.playlist.pop(0)
self._playing = False
#add second option if not given
# add second option if not given
if len(options) == 1:
options.append(0)
self.play("play", options[1])
if options[0] == "pause" and len(self.playlist) != 0:
#Pauses current music and saves its position.
#The -1000 makes it more natural because resuming
# Pauses current music and saves its position.
# The -1000 makes it more natural because resuming
# can only be done in whole seconds
# and makes it easier to recognize position.
currentpos = int(pygame.mixer.music.get_pos() / 1000.0 - 1000)
#When song just started negative results may possible.
# When song just started negative results may possible.
if currentpos <= 0:
currentpos += 1000
try: # try is cheaper than if
@ -203,8 +202,8 @@ Look up individual options's comments in sourcecode for an in depth explanation.
pygame.mixer.music.pause()
if options[0] == "unpause" and len(self.playlist) != 0:
#Restarts music and removes previous music if it hasnt been paused yet.
#the check is needed if someone unpauses more than pauses
# Restarts music and removes previous music if it hasnt been paused yet.
# the check is needed if someone unpauses more than pauses
if self._pauselevel > 0:
self._pauselevel -= 1
while self._timeplayed[self.playlist[0]] == 0 and len(self.playlist) > 1:
@ -214,13 +213,13 @@ Look up individual options's comments in sourcecode for an in depth explanation.
self._playing = True
if options[0] == "stop":
#Stops current song.
# Stops current song.
pygame.mixer.music.stop()
self._timeplayed[self.playlist[0]] = 0
self._playing = False
if options[0] == "loop":
#Playes current song in a loop.
# Playes current song in a loop.
self._timeplayed[self.playlist[0]] = 0
pygame.mixer.music.load(self._path + self.playlist[0])
self.play("play", -1)
@ -234,16 +233,16 @@ pos (int)
Alternativly "end" can be passed too
to add a song to the end.
"""
#Makes it easier to add song at end by using "end" as pos.
# Makes it easier to add song at end by using "end" as pos.
if type(pos) is str:
if pos == "end" and len(self.playlist) != 0:
pos = len(self.playlist)
else:
pos = 0
#Ensures that we actually have songs to load.
# Ensures that we actually have songs to load.
if self.files != [None]:
#Selects a new song and ensures that never two songs are directly
# Selects a new song and ensures that never two songs are directly
# after each other.
newsong = self.files[random.randint(0, len(self.files) - 1)]
result = False
@ -251,33 +250,33 @@ pos (int)
while not result:
newsong = self.files[random.randint(0, len(self.files) - 1)]
try:
#checks right neighbor is diffrent
# checks right neighbor is diffrent
right = not (newsong == self.playlist[pos + 1])
except:
#if has no neighbor, left decides
#(if left is true then end result is true
# if left is false then end result is false)
# if has no neighbor, left decides
# (if left is true then end result is true
# if left is false then end result is false)
right = True
try:
#checks left neighbor if diffrent and decides
#if one of both partner is diffrent as newsong
# checks left neighbor if diffrent and decides
# if one of both partner is diffrent as newsong
result = right and not (newsong == self.playlist[pos])
except:
#if no left neighbor right decides
# if no left neighbor right decides
result = right
else:
#If it is only song, there are no neighbours to check.
# If it is only song, there are no neighbours to check.
newsong = self.files[random.randint(0, len(self.files) - 1)]
#Adds song at pos to playlist.
# Adds song at pos to playlist.
self.queue(newsong, pos)
def remove_dublicates(self):
"""Removes dublicate songs whilst preserving order."""
#These three lines werent done by me
#and only slightly modified
#Thanks to http://www.peterbe.com/plog/uniqifiers-benchmark
#for creating them (i think he did it but im not sure)
# These three lines werent done by me
# and only slightly modified
# Thanks to http://www.peterbe.com/plog/uniqifiers-benchmark
# for creating them (i think he did it but im not sure)
seen = set()
seen_add = seen.add
self.playlist = [x for x in self.playlist if not (x in seen or seen_add(x))]
@ -291,12 +290,12 @@ pos (int)
Alternativly "end" can be passed too
to add a song to the end.
"""
#makes it easier to add song at end by using "end" as pos
# makes it easier to add song at end by using "end" as pos
if type(pos) is str:
if pos == "end":
pos = len(self.playlist)
else:
pos = 0
#adds song at pos to playlist
self.playlist.insert(pos, song)
# adds song at pos to playlist
self.playlist.insert(pos, song)

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from . import interface
"""Useless module atm"""
#maybe implemented some next version
# maybe implemented some next version
def getinput(oldinput):

@ -11,7 +11,7 @@ from pygame.locals import *
def init():
"""Some variable initializing"""
#nothing to explain here
# nothing to explain here
global fullscreenold
global playerup
global alpha
@ -25,7 +25,7 @@ def init():
no16to9 = False
show = 0
if settings.aspect_ratio != 16.0 / 9:
#makes a black stripe if not 16 to 9
# makes a black stripe if not 16 to 9
no16to9 = True
delta_screeny = settings.screeny - settings.screeny_current
correcture = pygame.Surface((settings.screenx, delta_screeny))
@ -36,7 +36,7 @@ def init():
def ingame():
"""Draws everything while game runs"""
#nothing to explain here i guess
# nothing to explain here i guess
screen = settings.screen
@ -60,7 +60,7 @@ def ingame():
def debug():
"""shows debug info on screen"""
#nothing to explain here too?
# nothing to explain here too?
debugscreen = settings.debugscreen
rot_dest = settings.player.rot_dest
@ -153,9 +153,9 @@ def drawsongname():
show = 40 * 8
font = pygame.font.SysFont(typeface, 15)
song = sounds.music.playlist[0].replace("_", " ")[:-4]
#To all of you:
#USE BACKGROUND COLOR
#cant apply alpha otherwise (took hours to figure out)
# To all of you:
# USE BACKGROUND COLOR
# cant apply alpha otherwise (took hours to figure out)
songname = font.render(song, True, settings.color, (0, 0, 5))
font_pos = songname.get_rect()
font_pos.right = screenx - 10
@ -169,7 +169,7 @@ def drawsongname():
songname.set_alpha(int(alpha))
except:
pass
#Timing error is not important
# Timing error is not important
if pygame.mixer.music.get_volume() != 0.0 and show != 0:
screen.blit(songname, font_pos)
@ -186,7 +186,7 @@ def drawworldname():
def adjustscreen():
"""Changes to fullscreen and back"""
#changes resolution and so on when fullscreen is toggled
# changes resolution and so on when fullscreen is toggled
global fullscreenold
screenx = settings.screenx
@ -206,8 +206,8 @@ def status():
xsize = int(settings.screenx_current * 0.05)
ysize = int(settings.screeny_current * 0.3) + 10
bar = pygame.Surface((xsize, ysize)).convert_alpha()
border = pygame.transform.scale(
settings.border1, (xsize, ysize)).convert_alpha()
border = pygame.transform.scale(settings.border1, (xsize, ysize)
).convert_alpha()
border.set_alpha(0)
borderpos = border.get_rect()
borderpos.bottomright = (settings.screenx_current,
@ -216,4 +216,4 @@ def status():
pos.right = settings.screenx_current
pos.top = settings.screeny_current - (pos.h / 100.0) * specials.energy
settings.screen.blit(bar, pos)
settings.screen.blit(border, borderpos)
settings.screen.blit(border, borderpos)

@ -19,8 +19,8 @@ def init():
def handle():
#handles user input
#i think nothing to explain here
# handles user input
# i think nothing to explain here
midi_in.do()
@ -63,10 +63,10 @@ def handle():
settings.left = True
if key == "d" or key == "right":
settings.right = True
if key == "o" and settings.player.pos.x >= 0.9 \
and settings.player.pos.y >= 0.9:
pygame.mixer.music.load("./assets/music/$not$ard_tatort.ogg")
pygame.mixer.music.play(1, 0.0)
if key == "o":
if settings.player.pos.x >= 0.9 and settings.player.pos.y >= 0.9:
pygame.mixer.music.load("./assets/music/$not$ard_tatort.ogg")
pygame.mixer.music.play(1, 0.0)
if key == "f" or key == "space":
tmp = objects.bullet(settings.player.rotation, settings.player.pos)
settings.bullets.append(tmp)
@ -89,7 +89,7 @@ def handle():
settings.dstars, settings.dtargets)
if key == "h":
for target in settings.world.targets:
print target.pos
print((target.pos))
if len(key) == 3 and settings.debugmode:
if key[0] == "[" and key[2] == "]":
num = int(key[1])

@ -15,10 +15,10 @@ from . import specials
from . import sounds
from pygame.locals import *
#Starts timer/clock for the movement, so it stays constant
# Starts timer/clock for the movement, so it stays constant
pygame.time.set_timer(USEREVENT + 1, 25)
#initialize all variables for the modules
# initialize all variables for the modules
settings.init()
interface.init()
draw.init()
@ -33,43 +33,43 @@ if not settings.skip:
print(("Loading time:" + str(settings.loading_time / 1000.0)))
print(("Your seed is:" + str(settings.seed)))
#start clock for checking time how long has been played
# start clock for checking time how long has been played
global clock
clock = settings.clock
#start the missions
# start the missions
missions.init()
def main():
while settings.run:
#get events/user-input
# get events/user-input
settings.upd("get_events")
sounds.music.update(settings.events)
sounds.music.volume = settings.volume
#handle the user input
# handle the user input
interface.handle()
#handles the movement every 25 milliseconds
# handles the movement every 25 milliseconds
for event in settings.events:
if event.type == USEREVENT + 1:
movement.handle()
#makes a clock tick (pygame internal stuff)
# makes a clock tick (pygame internal stuff)
clock.tick()
#display everything
# display everything
draw.ingame()
#check if missions have been fulfilled
# check if missions have been fulfilled
missions.handle("ingame")
while True:
#basic cycle: Start game, when won show main menu
# basic cycle: Start game, when won show main menu
main()
settings.run = True
settings.reset()
menu.main()
menu.main()

@ -41,7 +41,7 @@ class menu_template():
variables, externals):
"""main menu"""
#import variables
# import variables
self.screenx = settings.screenx_current
self.screeny = settings.screeny_current
self.screen = settings.screen
@ -52,15 +52,15 @@ class menu_template():
self.menu_name = menu_name
self.fade_step2 = fade_step2
#set mouse visible
# set mouse visible
pygame.mouse.set_visible(True)
#create menu
# create menu
self.menu = menu.create_menu(
"./assets/templates/" + self.menu_name + ".menu",
self.variables, pygame.Rect((0, 0), (self.screenx, self.screeny)))
#create fade effect
# create fade effect
fade = fade_screen(self.fade_step, self.fade_step2, self.fade_max,
self.screenx, self.screeny)
self.menu.elems["externals"] = [fade]
@ -143,7 +143,7 @@ class menu_template():
def main():
"""main menu"""
#create the planets animation
# create the planets animation
class create_planet():
def __init__(self, screenx, screeny):
@ -166,23 +166,23 @@ def main():
self.__init__(screenx, screeny)
planet = create_planet(settings.screenx_current, settings.screeny_current)
#Load menu
# Load menu
main_menu = menu_template("main", 70, 1, 100, {}, [planet])
#inserts menu music
# inserts menu music
sounds.music.queue("$not$menue.ogg", 0)
sounds.music.play("stop")
sounds.music.play("play", -1)
#Define loading time on first call
# Define loading time on first call
if settings.loading_time == 0:
settings.loading_time = pygame.time.get_ticks()
run = True
#Menu loop
# Menu loop
while run:
#Calling events and checking through events
# Calling events and checking through events
events = main_menu.run()
for event in events:
if event == "event.CONTINUE":
@ -309,8 +309,8 @@ def choose_world():
def inputpopup(x, y, header):
"""Method for having an inputfield or selecting savegame"""
#as said takes and input and returns a string or returns
#savegame if header is saying so
# as said takes and input and returns a string or returns
# savegame if header is saying so
screen = settings.screen
fade = settings.fade
@ -350,12 +350,12 @@ def inputpopup(x, y, header):
def savegames():
"""Menu to select a saved game."""
#Loads in values
# Loads in values
list_of_saves = settings.saves
D_saves = len(list_of_saves)
currently_selected = 0
#Defines Menu
# Defines Menu
settings_menu = menu_template("load", 0, 255, 255,
{"savename": list_of_saves[currently_selected]},
[])
@ -363,39 +363,39 @@ def savegames():
run = True
while run:
#Get all events and handle them
# Get all events and handle them
events = settings_menu.run()
for event in events:
#Exits savegame menu
# Exits savegame menu
if event in ["event.EXIT", "event.QUIT", "Return"]:
run = False
return None
#Sets the current selected savegame to load
# Sets the current selected savegame to load
if event == "Load":
return list_of_saves[currently_selected]
#Shows next savegame
# Shows next savegame
if event == "Next":
#Points to an later save
# Points to an later save
currently_selected += 1
#Wraps to the beginning to create a not ending loop
# Wraps to the beginning to create a not ending loop
if currently_selected + 1 > D_saves:
currently_selected = currently_selected - D_saves
settings_menu = menu_template("load", 0, 255, 255,
{"savename": list_of_saves[currently_selected]},
[])
#Lets the button last longer in klicked mode
# Lets the button last longer in klicked mode
pygame.time.delay(50)
#Shows previous savegame
# Shows previous savegame
if event == "Previous":
#Points to an earlier save
# Points to an earlier save
currently_selected -= 1
#Wraps to the end to create a not ending loop
# Wraps to the end to create a not ending loop
if currently_selected < 0:
currently_selected = D_saves + currently_selected
settings_menu = menu_template("load", 0, 255, 255,
{"savename": list_of_saves[currently_selected]},
[])
#Lets the button last longer in klicked mode
# Lets the button last longer in klicked mode
pygame.time.delay(50)
pygame.display.flip()
@ -405,9 +405,9 @@ def options():
"""The settings menu"""
button_size = menu.IO.read("./assets/templates/default.vars", "size")
#a conversion method between selector
#and actual text size
#found by trial and error
# a conversion method between selector
# and actual text size
# found by trial and error
button_size = int(float(button_size) - 10) / 5
settings_menu = menu_template("settings", 0, 0, 255,
@ -436,18 +436,18 @@ def options():
settings.fullscreen = bool(event)
if event == "Button Size":
button_size = int(event)
#a conversion method between selector
#and actual text size
#found by trial and error
# a conversion method between selector
# and actual text size
# found by trial and error
menu.IO.write("./assets/templates/default.vars", "size",
10 + (5 * button_size))
sounds.music.update(False, False)
pygame.display.flip()
#explanation of the 10 + (5 * …) is written in
#the Button Size handler in events loop
# explanation of the 10 + (5 * …) is written in
# the Button Size handler in events loop
menu.IO.write("./assets/templates/default.vars", "size",
10 + (5 * button_size))
menu.IO.write("./assets/templates/default.vars", "ratio", 1100)
settings.upd("adjust_screen")
settings.upd("adjust_screen")

@ -78,7 +78,7 @@ def quit():
try:
del device
except:
#I know, no device connected…
# I know, no device connected…
pass
@ -86,4 +86,4 @@ def do():
global connected
if settings.debugmode and connected:
get_input()
get_input()

@ -68,4 +68,4 @@ def handle(usage):
screen.blit(fade, fade_pos)
screen.blit(texttime, textrect)
screen.blit(texttt, textrectpertarget)
pygame.display.flip()
pygame.display.flip()

@ -19,4 +19,4 @@ def handle():
"""Handle movement"""
settings.world.move()
settings.player.move()
settings.player.move()

@ -26,9 +26,9 @@ def run():
settings.upd("screenvalues")
#load the credits.txt and assign place
# load the credits.txt and assign place
with open("./assets/lang/credits.txt") as credits_file:
#find the longest line to optimize font size
# find the longest line to optimize font size
biggest = 1000
for line in credits_file:
line = line[:-1]
@ -45,13 +45,13 @@ def run():
line, True, color,
screen.get_rect().size, 0)
line_pos = line.get_rect()
#Distance from line to line is 5 pixel more than height
# Distance from line to line is 5 pixel more than height
line_pos.top = ((line_pos.h + 5) * itera) + settings.screeny_current
line_pos.left = (settings.screenx_current / 2) - (line_pos.w / 2.0)
lines.append(line)
lines_pos.append(line_pos)
#diplays content of credits.txt
# diplays content of credits.txt
while not lines_pos[len(lines_pos) - 1].top <= -80:
settings.upd("get_events")
for event in settings.events:
@ -72,4 +72,4 @@ def run():
for credit in range(len(lines)):
lines_pos[credit].top -= 2
pygame.mouse.set_visible(True)
pygame.mouse.set_visible(True)

@ -20,11 +20,11 @@ class stars():
self.image = pygame.image.load("./assets/sprites/star1.tif")
imgsize = self.image.get_width()
#random size between 0 and 100 %
# random size between 0 and 100 %
self.size = random.randint(0, 100) / 100.0
minimum = 0.15
maximum = 0.70
#determing the depth of the star
# determing the depth of the star
self.depth = (self.size * (maximum - minimum)
) + minimum # value mapped between .15 and .70
self.image = pygame.transform.smoothscale(self.image,
@ -33,15 +33,15 @@ class stars():
self.pos = self.image.get_rect()
self.screenx = screenx - self.pos.w
self.screeny = screeny - self.pos.h
#gives a percentage where star is located
# gives a percentage where star is located
self.relative_x = random.randint(-100, int(100 * (self.depth))) / 100.0
self.relative_y = random.randint(-100, int(100 * (self.depth))) / 100.0
self.update(screenx / 1920.0)
def move(self, x, y):
"""Moves the star according to player position"""
#note: x and y are the player position
#and that screenx and screeny are not actual screen width and height
# note: x and y are the player position
# and that screenx and screeny are not actual screen width and height
self.pos.left = ((self.screenx - x) * self.depth) - self.pointx
self.pos.top = ((self.screeny - y) * self.depth) - self.pointy
@ -89,16 +89,16 @@ class bullet():
def move(self, player_pos):
"""Moves the bullet"""
#movement to adjust to player position
# movement to adjust to player position
tmpx = self.start[0] + (self.start[0] - player_pos[0]) - (self.pos.w / 2.0)
tmpy = self.start[1] + (self.start[1] - player_pos[1]) - (self.pos.h / 2.0)
#movement by acceleration
# movement by acceleration
self.distance[0] += self.move_x
self.distance[1] += self.move_y
#overall position
# overall position
self.pos.center = (self.distance[0] + tmpx, self.distance[1] + tmpy)
#inscreen detection
# inscreen detection
if not self.pos.colliderect(settings.screen.get_rect()):
self.inscreen = False
@ -175,17 +175,17 @@ class target():
def blit(self):
"""Blits target and explosion"""
if self.gothit:
#blit explosion
# blit explosion
has_finished = self.explosion.state in ["stopped", "paused"]
if self.explosion.isFinished() or has_finished:
#signal to kill entity
# signal to kill entity
self.kill_entity = True
elif not self.kill_entity:
#otherwise show explosion
# otherwise show explosion
self.explosion.blit(settings.screen, self.pos)
return True
else:
#show target if inscreen
# show target if inscreen
if self.inscreen:
settings.screen.blit(self.image, self.pos)
return True
@ -235,7 +235,7 @@ class warp_station():
test = test or testpoint(playerpos.bottomright)
return test
if test_collide():
#Warps to the selected world and gets a bit pushed off the station
# Warps to the selected world and gets a bit pushed off the station
selected_num = menu.choose_world()
if selected_num >= 0:
settings.world = settings.localmap[selected_num]
@ -260,4 +260,4 @@ class warp_station():
playerpos = settings.player.pos
def blit(self):
self.screen.blit(self.img, self.pos)
self.screen.blit(self.img, self.pos)

@ -9,8 +9,6 @@ class player():
def __init__(self):
global settings
from . import settings # lint:ok
self.img = pygame.surface.Surface # Ship image (redunant
#see self.new_ship()
self.speed = 15 # Speed of player (redunant see self.new_ship())
self.rotation = 0 # Current player rotation
@ -35,7 +33,7 @@ class player():
name + "_up", name + "_upri", name + "_ri", name + "_dori",
name + "_do", name + "_dole", name + "_le", name + "_uple"]
#generates new images in ./assets/sprites/player
# generates new images in ./assets/sprites/player
for nameoffile in names:
self.playerup = pygame.image.load("./assets/sprites/ships/" +
name + ".tif")
@ -43,7 +41,7 @@ class player():
nameoffile = folder + nameoffile + ".png"
pygame.image.save(pygame.transform.rotate(self.playerup, angle), nameoffile)
#loads images into ram
# loads images into ram
self.playerupri = pygame.image.load(folder + name + "_upri.png")
self.playerri = pygame.image.load(folder + name + "_ri.png")
self.playerdori = pygame.image.load(folder + name + "_dori.png")
@ -93,7 +91,7 @@ class player():
if self.rotation < 0:
self.rotation += 360
#handles rotation and gives signal to update player image/surface
# handles rotation and gives signal to update player image/surface
if self.rotation != self.rot_dest:
self.update = True
if self.rot_dest > self.rotation:
@ -107,14 +105,14 @@ class player():
if (self.rot_dest - self.rotation) <= -180:
self.rotation += 5.625
#this part is responsible for the movement of the player
#this calculates speed in y and x direction
# this part is responsible for the movement of the player
# this calculates speed in y and x direction
self.move_x = self.speedboost * konstspeed * math.degrees(math.sin(
(math.radians(self.rotation))))
self.move_y = self.speedboost * -konstspeed * math.degrees(math.cos(
(math.radians(self.rotation))))
#this actually moves the rect and ensures that you stay in screen
# this actually moves the rect and ensures that you stay in screen
if self.should_move:
self.rel_x += float(self.move_x * self.speed) / (windowwidth)
self.rel_y += float(self.move_y * self.speed) / (windowheight)
@ -131,15 +129,15 @@ class player():
self.pos.top = int(self.rel_y * windowheight)
self.pos.left = int(self.rel_x * windowwidth)
#lint:disable
#Somehow a double check is needed…
#lint:disable
# Somehow a double check is needed…
if self.pos.bottom >= settings.screeny_current:
self.pos.bottom += settings.screeny_current - self.pos.bottom
if self.pos.right >= settings.screenx_current: