diff --git a/.gitignore b/.gitignore index d39ce24..5e67d61 100644 --- a/.gitignore +++ b/.gitignore @@ -5,11 +5,8 @@ **.pyo **.pyc -#custom pattern to make ignored files without addig new rule -**IGNORE*.* - -#the Ninja project file -**.nja +#Custom ignored files +**~.* #empty folders screenshots/* diff --git a/README.html b/README.html index 9f8fbed..5d2bec8 100644 --- a/README.html +++ b/README.html @@ -16,46 +16,46 @@ -

main_picture

+

Logo

Project Interstellar is a 2d space-adventure game

-

developed in and with : Python, Pygame, subversion and Ninja-IDE. Currently pre-alpha status.

+

developed in and with : Python, Pygame, Git/Github and Ninja-IDE. Currently pre-alpha status.

-

Version 0.3.x

+

Version 0.3.3

How to Run the Game


This is just a developement version so you need -the programming language Python version 2.x:
-https://www.python.org/downloads/ -
And the physics and graphics engine pygame:
-http://www.pygame.org/download.shtml +the programming language Python version 2.x .
+
And the physics and graphics engine Pygame.

Both have a good guide how to install them otherwise google is your friend.

Windows:
In normal case double clicking Run.py should start it. If this does not work google for "How to start a .py file".

Debian based systems:
-Double click on Run.sh. If this does not work make sure it has its executable bit set. Do this by opening a treminal in this folder or navigating there with a "normal" terminal and then copy-paste this command: chmod u+x ./Run.sh +Double click on Run.sh. If this does not work make sure it has its executable bit set. Do this by opening a terminal in this folder or navigating there with a "normal" terminal and then copy-paste this command: chmod u+x ./Run.sh

Other:
Google for: "how to run python files in" and add you OS

How to play

-

To play, simply run the "Run.py" file located in the base directory

+


Use WASD for movement (arrowkeys work too)
+
F or space will shoot a bullet
+
When on full power use C to shoot in eight directions
+
Pressing Y makes you faster while X slower
+
Use escape to pause the game
+
Can you get below my 295294ms?
+

Features

Custom music

Simply paste your music into the ./assets/music folder to be included in the game. "_" will be replaced with spaces " ". For best support use .ogg but .mp3 will work too.

File / Code information

-

(Codelines ver:0.3.2.7)

+

(Codelines ver:0.3.3)

@@ -73,88 +73,118 @@ Google for: "how to run python files in" and add you OS - + + + + + + + + + + + + + + + + + + + - + - - - - + + + + - - + + - + - - - - + + + + - - - - + + + + - - - - + + + + - - + + - + + + + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - + - - + + + + + + + + - - - - + + + + @@ -164,26 +194,26 @@ Google for: "how to run python files in" and add you OS - - - + + +
53
tygamusic.pylibs/menu/creator.py35184435
libs/menu/disp_elem.py32488412
libs/menu/IO.py30636
libs/tygamusic/tygamusic.py 218 80 298
chat.pysrc/chat.py 4 5 9
draw.py22255277src/draw.py16042202
interface.py93src/interface.py108 17110125
main.py443478src/main.py463076
menu.py28768355src/menu.py317116487
midi_in.py571370src/midi_in.py711990
missions.py52src/missions.py55 197174
src/movement.py14923
movement.py13929168src/namings.py742498
namings.py571673src/objects.py21451265
objects.py28754341src/player.py15345198
settings.py38178459src/settings.py31717394
sounds.pysrc/sounds.py 7411512
src/specials.py671481
specials.py701585src/worlds.py10132133
Total2220501272127237303462

Top3 code only:

+
  • libs/menu/creator.py 351
  • +
  • libs/menu/disp_elem.py 324
  • +
  • src/menu.py & src/settings.py 317
  • Top3 Commented or empty lines:

    +
  • menu.py 116
  • +
  • libs/menu/disp_elem.py 88
  • +
  • libs/menu/creator.py 84
  • Top3 Total:

    +
  • src/menu.py 487
  • +
  • libs/menu/creator.py 435
  • +
  • libs/menu/disp_elem.py 412
  • Contact Information

    -

    You can contact me on the homepage: http://www.pygame.org/project-Project+Interstellar-2943-.html +

    You can contact me on the homepage or via email: max12354678910@gmail.com (subject: Project_interstellar)

    Licences

    diff --git a/README.md b/README.md index 3b1f18f..aa9b6a0 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,21 @@ -![main_picture](https://lh3.googleusercontent.com/-ZjA1FSivXNw/VSaOqy8nSRI/AAAAAAAAAB4/_nW122LgHr0/s701-no/all.tiff) +![Logo](https://lh3.googleusercontent.com/-ZjA1FSivXNw/VSaOqy8nSRI/AAAAAAAAAB4/_nW122LgHr0/s701-no/all.tiff "Logo")

    Project Interstellar is a 2d space-adventure game

    -

    developed in and with : Python, Pygame, subversion and Ninja-IDE. Currently pre-alpha status.

    +

    developed in and with : Python, Pygame, Git/Github and Ninja-IDE. Currently pre-alpha status.

    -Version 0.3.x +Version 0.3.3 How to Run the Game -------------------
    This is just a developement version so you need -the programming language Python version 2.x:
    -https://www.python.org/downloads/ -
    And the physics and graphics engine pygame:
    -http://www.pygame.org/download.shtml +the programming language [Python version 2.x .](https://www.python.org/downloads/release/python-2710/)
    +
    And the physics and graphics engine [Pygame.](http://www.pygame.org/download.shtml)

    Both have a good guide how to install them otherwise google is your friend.
    Windows:
    In normal case double clicking Run.py should start it. If this does not work google for "How to start a .py file".

    Debian based systems:
    -Double click on Run.sh. If this does not work make sure it has its executable bit set. Do this by opening a treminal in this folder or navigating there with a "normal" terminal and then copy-paste this command: chmod u+x ./Run.sh +Double click on Run.sh. If this does not work make sure it has its executable bit set. Do this by opening a terminal in this folder or navigating there with a "normal" terminal and then copy-paste this command: chmod u+x ./Run.sh

    Other:
    Google for: "how to run python files in" and add you OS @@ -25,18 +23,20 @@ Google for: "how to run python files in" and add you OS How to play ----------- -To play, simply run the "Run.py" file located in the base directory +
    Use WASD for movement (arrowkeys work too)
    +
    F or space will shoot a bullet
    +
    When on full power use C to shoot in eight directions
    +
    Pressing Y makes you faster while X slower
    +
    Use escape to pause the game
    +
    Can you get below my 295294ms?
    +

    Features -------- @@ -47,46 +47,51 @@ Simply paste your music into the ./assets/music folder to be included in the gam File / Code information ----------------------- -(Codelines ver:0.3.2.7) +(Codelines ver:0.3.3) -| File | Code | Non-code | Total | -| ---: | :--: | :---------------------: | :---: | -| Run.py | 39 | 14 | 53 | -| tygamusic.py | 218 | 80 | 298 | -| chat.py | 4 | 5 | 9 | -| draw.py | 222 | 55 | 277 | -| interface.py | 93 | 17 | 110 | -| main.py | 44 | 34 | 78 | -| menu.py | 287 | 68 | 355 | -| midi_in.py | 57 | 13 | 70 | -| missions.py | 52 | 19 | 71 | -| movement.py | 139 | 29 | 168 | -| namings.py | 57 | 16 | 73 | -| objects.py | 287 | 54 | 341 | -| settings.py | 381 | 78 | 459 | -| sounds.py | 7 | 4 | 11 | -| specials.py | 70 | 15 | 85 | +| File | Code | Non-code | Total | +| --------------------------: | :-: | :-: | :-: | +| Run.py | 39 | 14 | 53 | +| libs/menu/creator.py | 351 | 84 | 435 | +| libs/menu/disp_elem.py | 324 | 88 | 412 | +| libs/menu/IO.py | 30 | 6 | 36 | +| libs/tygamusic/tygamusic.py | 218 | 80 | 298 | +| src/chat.py | 4 | 5 | 9 | +| src/draw.py | 160 | 42 | 202 | +| src/interface.py | 108 | 17 | 125 | +| src/main.py | 46 | 30 | 76 | +| src/menu.py | 317 | 116 | 487 | +| src/midi_in.py | 71 | 19 | 90 | +| src/missions.py | 55 | 19 | 74 | +| src/movement.py | 14 | 9 | 23 | +| src/namings.py | 74 | 24 | 98 | +| src/objects.py | 214 | 51 | 265 | +| src/player.py | 153 | 45 | 198 | +| src/settings.py | 317 | 17 | 394 | +| src/sounds.py | 7 | 5 | 12 | +| src/specials.py | 67 | 14 | 81 | +| src/worlds.py | 101 | 32 | 133 | | | | | -| Total | 2220 | 501 | 2721 | +| Total | 2723 | 730 | 3462 | Top3 code only: +
  • libs/menu/creator.py 351
  • +
  • libs/menu/disp_elem.py 324
  • +
  • src/menu.py & src/settings.py 317
  • Top3 Commented or empty lines: +
  • menu.py 116
  • +
  • libs/menu/disp_elem.py 88
  • +
  • libs/menu/creator.py 84
  • Top3 Total: +
  • src/menu.py 487
  • +
  • libs/menu/creator.py 435
  • +
  • libs/menu/disp_elem.py 412
  • Contact Information ------------------- -You can contact me on the homepage: http://www.pygame.org/project-Project+Interstellar-2943-.html +You can contact me on the [homepage](http://www.pygame.org/project-Project+Interstellar-2943-.html) or via email: max12354678910@gmail.com (subject: Project_interstellar) diff --git a/Run.py b/Run.py index 47f0743..09d0007 100644 --- a/Run.py +++ b/Run.py @@ -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()) \ No newline at end of file + raise SystemExit(traceback.format_exc()) diff --git a/assets/lang/credits.txt b/assets/lang/credits.txt index 12ca504..b8b4a39 100644 --- a/assets/lang/credits.txt +++ b/assets/lang/credits.txt @@ -40,4 +40,4 @@ check the README for further information -I am NCO +I am Pixdigit diff --git a/assets/sprites/Button1.tif b/assets/sprites/Button1.tif deleted file mode 100644 index 679b78d..0000000 Binary files a/assets/sprites/Button1.tif and /dev/null differ diff --git a/assets/sprites/Button2.tif b/assets/sprites/Button2.tif deleted file mode 100644 index 97d6896..0000000 Binary files a/assets/sprites/Button2.tif and /dev/null differ diff --git a/assets/sprites/Button3.tif b/assets/sprites/Button3.tif deleted file mode 100644 index 535b1ad..0000000 Binary files a/assets/sprites/Button3.tif and /dev/null differ diff --git a/assets/sprites/inputbox2.tif b/assets/sprites/inputbox2.tif deleted file mode 100644 index 5599e6a..0000000 Binary files a/assets/sprites/inputbox2.tif and /dev/null differ diff --git a/assets/sprites/logo.tif b/assets/sprites/logo.tif deleted file mode 100644 index 43e0691..0000000 Binary files a/assets/sprites/logo.tif and /dev/null differ diff --git a/assets/sprites/planet1.tif b/assets/sprites/planet1.tif deleted file mode 100644 index 4cf6309..0000000 Binary files a/assets/sprites/planet1.tif and /dev/null differ diff --git a/assets/sprites/star1.tif b/assets/sprites/star1.tif index a4bebfe..f25b7b4 100644 Binary files a/assets/sprites/star1.tif and b/assets/sprites/star1.tif differ diff --git a/assets/sprites/star2.bmp b/assets/sprites/star2.bmp deleted file mode 100644 index 442f839..0000000 Binary files a/assets/sprites/star2.bmp and /dev/null differ diff --git a/assets/sprites/star3.bmp b/assets/sprites/star3.bmp deleted file mode 100644 index ea22dba..0000000 Binary files a/assets/sprites/star3.bmp and /dev/null differ diff --git a/assets/sprites/star4.bmp b/assets/sprites/star4.bmp deleted file mode 100644 index 5cb5e1b..0000000 Binary files a/assets/sprites/star4.bmp and /dev/null differ diff --git a/assets/sprites/star5.bmp b/assets/sprites/star5.bmp deleted file mode 100644 index 1220fe7..0000000 Binary files a/assets/sprites/star5.bmp and /dev/null differ diff --git a/assets/templates/default.vars b/assets/templates/default.vars index a82f5f8..e85dff0 100644 --- a/assets/templates/default.vars +++ b/assets/templates/default.vars @@ -1,7 +1,7 @@ <#box1 = (./assets/templates/nr1.design,6) <#box2 = (./assets/templates/nr1.design,./assets/sprites/knob1.tif,6) <%ratio = 1100 -<~size = 25 +<~size = 20 <"typeface = monospace <*color = (255,255,10) <%half = 50 diff --git a/assets/templates/load.menu b/assets/templates/load.menu new file mode 100644 index 0000000..7ab28a9 --- /dev/null +++ b/assets/templates/load.menu @@ -0,0 +1,8 @@ +&./assets/templates/default.vars +*|Load saved game|30 |$typeface|$color |$half + 0|%10 + 0| +*|$savename |20 |$typeface|$color |$half + 0|%20 + 0| +@|Return |$size|5|$typeface|$color|$box1|%80 + 0|%30 + 0| +/add project stats here +@|Previous |$size|5|$typeface|$color|$box1|%20 + 0|%90 + 0| +@|Load |$size|5|$typeface|$color|$box1|%50 + 0|%90 + 0| +@|Next |$size|5|$typeface|$color|$box1|%80 + 0|%90 + 0| diff --git a/assets/templates/main.menu b/assets/templates/main.menu index d23ff2f..8489578 100644 --- a/assets/templates/main.menu +++ b/assets/templates/main.menu @@ -4,6 +4,7 @@ *|Project Interstellar|40 |$typeface|$color |$half + 0|%10 + 0| *|Main Menu |30 |$typeface|$color |$half + 0|$qrt + 0| @|Start |$size|$ratio|$typeface|$color|$box1|$half + 0|%40 + 0| -~@|Settings |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| -~~@|Credits |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| -~~~@|Exit |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| +~@|Load Game |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| +~~@|Settings |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| +~~~@|Credits |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| +~~~~@|Exit |$size|$ratio|$typeface|$color|$box1|BottomLeft|%0 + 0|%0 + 10| diff --git a/assets/templates/nr1.design b/assets/templates/nr1.design index ef87f49..9744af5 100644 --- a/assets/templates/nr1.design +++ b/assets/templates/nr1.design @@ -1,10 +1,6 @@ -type = button -#corner = ./assets/sprites/design1.tif -line = ./assets/sprites/design1.tif -#line_orientation = vertical or horiontal -#inner_color = (255,128,128,100) -#Can create templates if line xor corner is missing -#line_orientation determines wether the given template is for the left or the top -# default is for the top +design = ./assets/sprites/design1.tif +#loads a design image +# consisting of stripes with the pattern +inner_color = (0,0,50,20) #inner_color sets the color inside the button -# default is trancparency \ No newline at end of file +# default is trancparency diff --git a/assets/templates/pause.menu b/assets/templates/pause.menu index a54a28b..23fd150 100644 --- a/assets/templates/pause.menu +++ b/assets/templates/pause.menu @@ -1,4 +1,5 @@ &./assets/templates/default.vars +<#background = (./assets/sprites/Background1.tif) *|Pause |35 |$typeface|$color |$half + 0|%12 + 0| @|Continue |$size|$ratio|$typeface|$color|$box1|$half + 0|%40 + 0| diff --git a/assets/templates/savescreen.menu b/assets/templates/savescreen.menu deleted file mode 100644 index 5d2cf87..0000000 --- a/assets/templates/savescreen.menu +++ /dev/null @@ -1,7 +0,0 @@ -&./assets/templates/default.vars -/#TODO halp -*|Load saved game|30 |$typeface|$color |$half + 0|%10 + 0| -*|$savename |20 |$typeface|$color |$half + 0|%20 + 0| -/add project stats here -@|Previous |$size|$ratio|$typeface|$color|$box1|%30 + 0|%90 + 0| -@|Next |$size|$ratio|$typeface|$color|$box1|%70 + 0|%90 + 0| diff --git a/assets/templates/settings.menu b/assets/templates/settings.menu index c500e36..032f9f1 100644 --- a/assets/templates/settings.menu +++ b/assets/templates/settings.menu @@ -2,6 +2,7 @@ <[sizes = (Very Small, Small, Medium, Big, Very Big) <#background = (./assets/sprites/Background1.tif) +*|Settings |30 |$typeface|$color |$half + 0|$qrt + 0| -|Volume |$volume |$size|$ratio|$typeface|$color|$box2 |$half + 0|%40 + 10| ~-|Button Size|$sizes|$button size|$size|$ratio|$typeface|$color|$box2|BottomLeft|%0 + 0|%0 + 10| ~~-|Fullscreen |$offon|$fullscreen |$size|$ratio|$typeface|$color|$box2|BottomLeft|%0 + 0|%0 + 10| diff --git a/libs/__init__.py b/libs/__init__.py index e69de29..40a96af 100644 --- a/libs/__init__.py +++ b/libs/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/libs/menu/IO.py b/libs/menu/IO.py index a213003..f0d785c 100644 --- a/libs/menu/IO.py +++ b/libs/menu/IO.py @@ -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() \ No newline at end of file + return line[line.index("=") + 1:].strip() diff --git a/libs/menu/creator.py b/libs/menu/creator.py index 2bc8cbf..2dd8664 100644 --- a/libs/menu/creator.py +++ b/libs/menu/creator.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import pygame -import disp_elem +from . import disp_elem def convert2list(string): @@ -48,6 +48,8 @@ class create_menu(): self.elems = {"buttons": [], "sliders": [], "surfs": {}} ident = 0 + all_elems = {} + elem_id = 1 with open(filename) as conf_file: for line in conf_file: @@ -55,15 +57,14 @@ class create_menu(): if len(line) < 1 or line[0] == "/": continue - #This checks for the identation - old_ident = ident + # 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) @@ -76,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: @@ -127,15 +128,11 @@ 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 if line[0] == "*": # A title is defined in language line = line[2:] @@ -183,6 +180,8 @@ class create_menu(): pos = pygame.Rect((xpos, ypos), (0, 0)) self.elems["surfs"][text] = [img, pos] + all_elems[elem_id] = self.elems["surfs"][text] + elem_id += 1 if line[0] == "@": # A button is defined in language line = line[2:] @@ -192,10 +191,10 @@ class create_menu(): text = self.vars[text[1:]] content = text - #Determines wether relation argument is given - additional_arguments = 1 if ident > 0 else 0 - #Through relation argument there might be another "|" - if line.count("|") == 5 + additional_arguments: + # Determines wether relation argument is given + are_additional_arguments = 1 if ident > 0 else 0 + # Through relation argument there might be another "|" + if line.count("|") == 5 + are_additional_arguments: imagemode = True line = line[line.index("|") + 1:].lstrip() if line.strip()[0] == "$": @@ -245,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()] @@ -258,28 +257,30 @@ 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: - #Adds absolute x and y value to current button - #TODO: the referring element to is not always a button - if relation[:3] == "top": - abs_y += self.elems["buttons"][-1 * (ident - old_ident)].pos.top - if relation[:6] == "bottom": - abs_y += self.elems["buttons"][-1 * (ident - old_ident)].pos.bottom - if relation[-4:] == "left": - abs_x += self.elems["buttons"][-1 * (ident - old_ident)].pos.left - if relation[-5:] == "right": - abs_x += self.elems["buttons"][-1 * (ident - old_ident)].pos.right - #Ignores relative placement - rel_x = 0 - rel_y = 0 + if type(all_elems[elem_id - 1]) != type(pygame.Surface): + # 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": + abs_y += all_elems[elem_id - 1].pos.bottom + if relation[-4:] == "left": + 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 + rel_x = 0 + rel_y = 0 self.elems["buttons"].append(disp_elem.button(text, rel_x, abs_x, rel_y, abs_y, ref, content, typeface, size, ratio, color, design[:3])) - #Centers non-relative buttons so their center is on the - #given x and y coordiante + 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 if ident == 0: self.elems["buttons"][-1].center() @@ -290,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] == "$": @@ -318,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()) @@ -357,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()] @@ -373,22 +373,25 @@ class create_menu(): rel_y, abs_y = analyse_num(line, self.vars) if ident > 0: - #Adds absolute x and y value to current button - if relation[:3] == "top": - abs_y += self.elems["sliders"][-1 * (ident - old_ident)].pos.top - if relation[:6] == "bottom": - abs_y += self.elems["sliders"][-1 * (ident - old_ident)].pos.bottom - if relation[-4:] == "left": - abs_x += self.elems["sliders"][-1 * (ident - old_ident)].pos.left - if relation[-5:] == "right": - abs_x += self.elems["sliders"][-1 * (ident - old_ident)].pos.right - #Ignores relative placement - rel_x = 0 - rel_y = 0 + if type(all_elems[elem_id - 1]) != type(pygame.Surface): + # 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": + abs_y += all_elems[elem_id - 1].pos.bottom + if relation[-4:] == "left": + 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 + rel_x = 0 + rel_y = 0 self.elems["sliders"].append(disp_elem.slider(text, default_value, size, ratio, typeface, color, img, rel_x, abs_x, rel_y, abs_y, ref, options)) + all_elems[elem_id] = self.elems["sliders"][-1] + elem_id += 1 if ident == 0: self.elems["sliders"][-1].center() @@ -396,6 +399,8 @@ class create_menu(): self.elems["surfs"]["background"] = [pygame.transform.smoothscale( pygame.image.load(self.vars["background"][0]).convert(), ref.size), pygame.Rect(0, 0, 0, 0)] + all_elems[elem_id] = self.elems["surfs"]["background"] + elem_id += 1 def blit(self, screen, events): try: @@ -426,4 +431,4 @@ class create_menu(): for elem in self.elems: if type(elem) != pygame.Surface: if elem.name == name: - return elem \ No newline at end of file + return elem diff --git a/libs/menu/disp_elem.py b/libs/menu/disp_elem.py index 9810cc6..206093d 100644 --- a/libs/menu/disp_elem.py +++ b/libs/menu/disp_elem.py @@ -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,8 +283,13 @@ class slider(): self.knob_pos.left = self.pos.left + tmp if type(self.options_list) == bool: - text = self.name + ": " + str(self.value * 100)[:3] + "%" - text = text.replace("0.0", "0").replace(".", "") + # adding a "." to the end to ensure at least one is included + text = str(self.value * 100)[:3] + "." + # removes "." and everything behind it + text = text[:text.index(".")] + # Adds the description and the % at the end + text = self.name + ": " + text + "%" + # Turns text into a pygame.Surface self.render_text = self.typeface.render(text, True, self.color) self.is_defined_list = False else: @@ -329,16 +334,12 @@ class create_outline(): self.resources[option] = var def create_template(self, pos): - corner = None - line = None - line_orient = None + from .creator import convert2list + design = self.resources["design"] + design = pygame.image.load(design) self.color = None - if "corner" in self.resources: - corner = pygame.image.load(self.resources["corner"]) - if "line" in self.resources: - line = pygame.image.load(self.resources["line"]) - if "line_orientation" in self.resources: - line_orient = pygame.image.load(self.resources["line_orientation"]) + + # gets selected background color if "inner_color" in self.resources: color = convert2list(self.resources["inner_color"]) if len(color) == 3: @@ -347,36 +348,28 @@ class create_outline(): self.color = (int(color[0]), int(color[1]), int(color[2]), int(color[3])) else: self.color = (0, 0, 0, 0) - if corner is None: - if line is None: - print("No image given to create design.") - else: - if line_orient == "vertical": - line = pygame.transform.rotate(line, -90) - line_rect = line.get_rect() - size = line_rect.h - #crop the line to the wished string - line_string = pygame.Surface((1, size)) - line_string.blit(line, (0, 0), pygame.Rect(pos, 0, 1, size)) - line = line_string - line_rect = line.get_rect() - self.pixels = {} - self.pattern = pygame.Surface((1, size)) - for a in range(size): - self.pattern.set_at((0, a), line.get_at((0, a))) - corner = pygame.Surface((size, size)) - for a in range(size): - for x in range(size): - for y in range(size): - if x >= a and y >= a: - corner.set_at((x, y), self.pattern.get_at((0, a))) - else: - if line is None: - size = corner.get_height() - self.line = pygame.Surface((1, size)) - for a in range(size): - self.line.set_at((0, a), corner.get_at((size - 1, a))) - return [line, corner] + + design_rect = design.get_rect() + size = design_rect.h + # 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 + self.pattern = pygame.Surface((1, size)) + # 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 + corner = pygame.Surface((size, size)) + for a in range(size): + for x in range(size): + for y in range(size): + if x >= a and y >= a: + corner.set_at((x, y), self.pattern.get_at((0, a))) + return [self.pattern, corner] def create_box(self, mode, rect): posx = rect.x @@ -387,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)) @@ -415,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) \ No newline at end of file + return (self.pos, self.box) diff --git a/libs/tygamusic/tygamusic.py b/libs/tygamusic/tygamusic.py index 879bfe0..c60cdd8 100644 --- a/libs/tygamusic/tygamusic.py +++ b/libs/tygamusic/tygamusic.py @@ -19,7 +19,7 @@ class CreateQueue(): """Initizalize a new Playlist-like object. usage: -object = CreateQueue(self, path, exceptbegin, endevent=USEREVENT+100) +object = CreateQueue(path, exceptbegin, endevent=USEREVENT+100) path (string) is the path tygamusic should search for availible music. @@ -44,27 +44,23 @@ self.files (list) A list of all files for possible playback. self.playlist (list) A list containing the filenames of the songs. - If self.update() is called without its shouldplaynextsong option - explicitly set to False the next song of this list will be played - if music has ended. self.volume (float) A value from 0 to 1 for playback volume. Volume gets updated if self.update is called. -These are +These are internal values that should not be modified unless + you are 100% sure what you do. self._endeventnum (int) An int used for defining the event when music playback has stopped. Changing this after creating the object has no effect. self._path (str) - This contains the path to from where music should be loaded - Changing this in an created object may cause errors - except you know what you're doing exactly. + This contains the path to from where music should be loaded. self._pauselevel (int) - An int representing how many songs have ben paused + An int representing how many songs have been paused while an other song was already paused. self._playing (bool) - Determines wether a song currently loaded (aka "playing") + Determines wether a song is currently loaded (aka "playing") self._timeplayed (dict) A dictionary with entrys looking like this: self._timeplayed[filename] = current_playing_pos @@ -91,16 +87,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 +120,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 previous one has ended. if self.__endevent in events and shouldplaynextsong: self.playlist.pop(0) self._playing = False @@ -150,48 +145,48 @@ shouldplaynextsong (bool) Usage: self.play(operation, *options) Operations: -"play" (needs amount of replays additionally) -"next" (needs amount of replays additionally) +"play" (amount of replays can be defined optionally) +"next" (amount of replays can be defined optionally) "loop" "pause" "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 +198,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 +209,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 +229,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 +246,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 +286,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) \ No newline at end of file + # adds song at pos to playlist + self.playlist.insert(pos, song) diff --git a/saves/Test.ini b/saves/Test.ini deleted file mode 100644 index e613c04..0000000 --- a/saves/Test.ini +++ /dev/null @@ -1,11 +0,0 @@ -[main] -fullscreen = False -screenx_current = 960 -screeny_current = 540 -debugscreen = False -debugmode = False -skip = True -posx = 564 -posy = 206 -volume = 0.5 - diff --git a/saves/default.ini b/saves/default.ini index 0989f3c..5809a0e 100644 --- a/saves/default.ini +++ b/saves/default.ini @@ -1,12 +1,11 @@ [main] -fullscreen = True -screenx_current = 1920 -screeny_current = 1080 -debug = False -skip = False -posx = 0 -posy = 0 +fullscreen = False +screenx_current = 960 +screeny_current = 540 +debug = True +skip = True +posx = 283 +posy = 497 volume = 0.5 debugscreen = False debugmode = False - diff --git a/src/__init__.py b/src/__init__.py index 2f36b23..e23e066 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -2,15 +2,19 @@ from chat import getinput from draw import init from draw import ingame from draw import debug +from draw import drawtargetsum from draw import drawsongname -from draw import adjustscreen +from draw import drawworldname from draw import status from interface import init from interface import handle from interface import getall from main import main +from menu import fade_screen +from menu import menu_template from menu import main from menu import pause +from menu import choose_world from menu import inputpopup from menu import savegames from menu import options @@ -25,11 +29,9 @@ from movement import init from movement import handle from namings import run from objects import stars -from objects import button -from objects import inputfield -from objects import sliders from objects import bullet from objects import target +from objects import warp_station from player import player from settings import init from settings import reset diff --git a/src/chat.py b/src/chat.py index e86f595..540530f 100644 --- a/src/chat.py +++ b/src/chat.py @@ -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): diff --git a/src/draw.py b/src/draw.py index 21ef717..5c9c9a5 100644 --- a/src/draw.py +++ b/src/draw.py @@ -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,42 +25,42 @@ 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)) + delta_screeny = (settings.screeny_current + - (settings.screenx_current * 9.0 / 16)) + correcture = pygame.Surface((settings.screenx_current, delta_screeny) + ).convert_alpha() correcture_pos = correcture.fill((0, 0, 0)) correcture.set_alpha(255) - correcture_pos.bottomleft = (0, settings.screeny) + correcture_pos.topleft = (0, (settings.screenx_current * 9.0 / 16)) + else: + correcture_pos = pygame.Rect(0, settings.screeny_current, 0, 0) def ingame(): """Draws everything while game runs""" - #nothing to explain here i guess - - screen = settings.screen - - adjustscreen() + # nothing to explain here i guess settings.world.blit() status() - settings.player.blit(screen) + settings.player.blit(settings.screen) debug() drawsongname() drawtargetsum() drawworldname() if no16to9: - screen.blit(correcture, correcture_pos) + settings.screen.blit(correcture, correcture_pos) pygame.display.flip() 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) @@ -184,34 +184,21 @@ def drawworldname(): settings.screen.blit(name, pos) -def adjustscreen(): - """Changes to fullscreen and back""" - #changes resolution and so on when fullscreen is toggled - global fullscreenold - - screenx = settings.screenx - screeny = settings.screeny - fullscreen = settings.fullscreen - fullscreenold = settings.fullscreenold - - if fullscreenold != fullscreen: - if fullscreen: - pygame.display.set_mode((screenx, screeny), pygame.FULLSCREEN) - if not fullscreen: - pygame.display.set_mode((screenx / 2, screeny / 2)) - settings.fullscreenold = fullscreen - - def status(): + """Draws the ships energy in the lower right corner.""" xsize = int(settings.screenx_current * 0.05) ysize = int(settings.screeny_current * 0.3) + 10 - bar = pygame.Surface((xsize, ysize)) - border = pygame.transform.scale(settings.border1, (xsize, ysize)) + bar = pygame.Surface((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, - settings.screeny_current) - pos = bar.fill((62, 186, 23)) + settings.screeny_current - correcture_pos.h) + pos = bar.fill((62, 186, 23, 40)) pos.right = settings.screenx_current - pos.top = settings.screeny_current - (pos.h / 100.0) * specials.energy + pos.top = (settings.screeny_current + - (pos.h / 100.0) * specials.energy + - correcture_pos.h) settings.screen.blit(bar, pos) - settings.screen.blit(border, borderpos) \ No newline at end of file + settings.screen.blit(border, borderpos) diff --git a/src/interface.py b/src/interface.py index f9e5d63..1536c66 100644 --- a/src/interface.py +++ b/src/interface.py @@ -12,17 +12,19 @@ from pygame.locals import * def init(): - midi_in.init() + if settings.debugmode: + midi_in.init() """Handles user input""" def handle(): - #handles user input - #i think nothing to explain here + # handles user input + # i think nothing to explain here - midi_in.do() + if settings.debugmode: + midi_in.do() for event in settings.events: if event.type == QUIT: @@ -63,16 +65,20 @@ 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) if key == "c": specials.fire = True if settings.debugmode: + if key == "r": + settings.world.adjust_to_screen() + if key == "q": + settings.init() if key == "p": settings.psycomode = settings.toggle(settings.psycomode, True, False) if key == "q": @@ -89,7 +95,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]) diff --git a/src/main.py b/src/main.py index 7a550dc..6eef786 100644 --- a/src/main.py +++ b/src/main.py @@ -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() \ No newline at end of file + menu.main() diff --git a/src/menu.py b/src/menu.py index 9085a4c..ef05223 100644 --- a/src/menu.py +++ b/src/menu.py @@ -39,9 +39,9 @@ class menu_template(): def __init__(self, menu_name, fade_step, fade_step2, fade_max, variables, externals): - """main menu""" + """Initialize 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] @@ -115,9 +115,10 @@ class menu_template(): if key == "escape": pygame.mouse.set_visible(False) events.append("event.QUIT") - if key == "return": + if key in ["return", "enter"]: pygame.mouse.set_visible(False) events.append("event.CONTINUE") + events.append(key) if event.type == USEREVENT and event.code == "MENU": klicked = self.menu.get_klicked() for elem in klicked: @@ -143,7 +144,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 +167,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": @@ -191,6 +192,16 @@ def main(): settings.reset() sounds.music.play("next") run = False + if event == "Load Game": + savegame = savegames() + if savegame is not None: + settings.load(savegame) + sounds.music.play("next", 0) + settings.upd("get_saves") + settings.upd("adjust_screen") + run = False + else: + pygame.mouse.set_visible(True) if event == "Settings": options() main_menu.update() @@ -200,6 +211,7 @@ def main(): settings.quit() pygame.display.flip() sounds.music.play("next", 0) + pygame.mouse.set_visible(False) def pause(): @@ -208,10 +220,7 @@ def pause(): sounds.music.play("pause") pygame.mouse.set_visible(True) - background = settings.screen.copy() pause_menu = menu_template("pause", 5, 5, 150, {}, []) - pause_menu.menu.elems["surfs"]["background"] = [background, - pygame.Rect(0, 0, 0, 0)] run = True @@ -230,12 +239,17 @@ def pause(): "Save Game") if savename != "Exit": settings.save(savename) + settings.upd("get_saves") if event == "Load Game": savegame = savegames() - if savegame != "Exit": + if savegame is not None: settings.load(savegame) sounds.music.play("unpause") + settings.upd("get_saves") + settings.upd("adjust_screen") run = False + else: + pygame.mouse.set_visible(True) if event == "Settings": options() pause_menu.update() @@ -243,10 +257,11 @@ def pause(): main() run = False pygame.display.flip() + pygame.mouse.set_visible(False) def choose_world(): - """pausing menu""" + """Selecting warp to move to.""" sounds.music.play("pause") pygame.mouse.set_visible(True) @@ -293,11 +308,29 @@ def choose_world(): settings.quit() if event[0:5] == "world": selected = event[5] - pygame.time.wait(128) + if len(event) > 1: + if event[1] in ["1", "2", "3", "4", "6", "7", "8", "9"]: + #maps keys to worlds + selected = int(event[1]) + if selected == 1: + selected = 6 + elif selected == 2: + selected = 7 + elif selected == 3: + selected = 8 + elif selected == 6: + selected = 5 + elif selected == 7: + selected = 1 + elif selected == 8: + selected = 2 + elif selected == 9: + selected = 3 + selected = str(selected) for elem in world_menu.menu.elems["buttons"]: if elem.name == "world" + str(selected): - elem.state = 1 - #print elem.name + elem.state = 2 + elem.blit(settings.screen) pygame.display.flip() pygame.mouse.set_visible(False) @@ -308,12 +341,13 @@ 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 - fade_pos = settings.fade_pos + fade = pygame.Surface((settings.screenx_current, settings.screeny_current)) + fade.fill((0, 0, 0, 255)) + fade_pos = fade.get_rect() infield1 = menu.disp_elem.input_field(x, y, header, settings.typeface, settings.color, settings.field) @@ -347,75 +381,67 @@ def inputpopup(x, y, header): def savegames(): - """creates wall with savegames to select""" + """Menu to select a saved game.""" - settings.upd("get_saves") + # Loads in values + list_of_saves = settings.saves + D_saves = len(list_of_saves) + currently_selected = 0 - saves = settings.saves - screen = settings.screen - screenx = settings.screenx_current - screeny = settings.screeny_current - color = settings.color - fade = settings.fade - fade_pos = settings.fade_pos - - xaxis = [] - yaxis = [] - saves_buttons = [] - run = True + # Defines Menu + settings_menu = menu_template("load", 0, 255, 255, + {"savename": list_of_saves[currently_selected]}, + []) - fade.set_alpha(20) - - for y in range(10): - y += 1 - for x in range(5): - x += 1 - xaxis.append(screenx / 6 * x) - yaxis.append(screeny / 11 * y + 50) - - for a in range(len(saves)): - tmp = saves[a].replace("\\", "/") - #20 and 11 are values for size and ratio and - #were found trough testing which looks best - saves_buttons.append(menu.disp_elem.button(tmp, 0, xaxis[a], 0, yaxis[a], - pygame.Rect((0, 0), (screenx, screeny)), - tmp, settings.typeface, 20, 11, - color, ["./assets/templates/nr1.design"])) - - a = 0 + run = True while run: - settings.upd("get_events") - for a in range(len(saves)): - saves_buttons[a].update(settings.events) - for event in settings.events: - if event.type == QUIT: - settings.quit() - if event.type == KEYDOWN: - key = pygame.key.name(event.key) - if key == "escape": - return "Exit" - if event.type == USEREVENT and event.code == "MENU": - for a in range(len(saves)): - if saves_buttons[a].klicked: - pygame.display.flip() - pygame.time.delay(200) - return saves[a] - screen.blit(fade, fade_pos) - for a in range(len(saves)): - saves_buttons[a].blit(screen) - pygame.display.flip() + # Get all events and handle them + events = settings_menu.run() + for event in events: + # Exits savegame menu + if event in ["event.EXIT", "event.QUIT", "Return"]: + run = False + return None + # Sets the current selected savegame to load + if event == "Load": + return list_of_saves[currently_selected] + # Shows next savegame + if event == "Next": + # Points to an later save + currently_selected += 1 + # 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 + pygame.time.delay(50) + # Shows previous savegame + if event == "Previous": + # Points to an earlier save + currently_selected -= 1 + # 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 + pygame.time.delay(50) - run = True + pygame.display.flip() + pygame.mouse.set_visible(False) 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, @@ -444,18 +470,19 @@ 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") \ No newline at end of file + settings.upd("adjust_screen") + pygame.mouse.set_visible(False) diff --git a/src/midi_in.py b/src/midi_in.py index 6c65199..9ff4a0b 100644 --- a/src/midi_in.py +++ b/src/midi_in.py @@ -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() \ No newline at end of file + get_input() diff --git a/src/missions.py b/src/missions.py index 359aa1b..dfbe0d9 100644 --- a/src/missions.py +++ b/src/missions.py @@ -37,16 +37,18 @@ def handle(usage): settings.save(settings.current_game) - fade = settings.fade - fade_pos = settings.fade_pos + fade = pygame.Surface((settings.screenx_current, settings.screeny_current)) + fade.fill((0, 0, 0)) + fade.set_alpha(0) + fade_pos = fade.get_rect() font = pygame.font.SysFont(settings.typeface, 50) points = settings.player.timeplay color = settings.color - texttime = font.render("Your time: " + str(points) + "ms", 1, color) - tmp = str(points / 15.0)[:6] - texttt = font.render("You needed " + tmp + "ms per target", 1, color) + texttime = font.render("Your time: " + str(points) + "ms", True, color) + tmp = str(points / (settings.dtargets * 8.0))[:6] + texttt = font.render("You needed " + tmp + "ms per target", True, color) textrect = texttime.get_rect() textrectpertarget = texttt.get_rect() textrect.center = settings.screen.get_rect().center @@ -68,4 +70,4 @@ def handle(usage): screen.blit(fade, fade_pos) screen.blit(texttime, textrect) screen.blit(texttt, textrectpertarget) - pygame.display.flip() \ No newline at end of file + pygame.display.flip() diff --git a/src/movement.py b/src/movement.py index a013665..c2a2b0c 100644 --- a/src/movement.py +++ b/src/movement.py @@ -19,4 +19,4 @@ def handle(): """Handle movement""" settings.world.move() - settings.player.move() \ No newline at end of file + settings.player.move() diff --git a/src/namings.py b/src/namings.py index e79d373..bf291df 100644 --- a/src/namings.py +++ b/src/namings.py @@ -3,6 +3,26 @@ import pygame from pygame.locals import * +def modrender(typeface, size, text, antialias, color, maxsize, borderoff): + size = getmaxsize(typeface, size, text, maxsize, borderoff) + tmpfont = pygame.font.SysFont(typeface, size) + return tmpfont.render(text, antialias, color) + + +def getmaxsize(typeface, size, text, maxsize, borderoff): + # local typeface! + nofit = True + while nofit: + tmpfont = pygame.font.SysFont(typeface, size) + bool1 = tmpfont.size(text)[0] < maxsize[0] - (2 * borderoff) + nofit = not (bool1 and tmpfont.size(text)[1] < maxsize[1] - (2 * borderoff)) + if size <= 5: + nofit = False + else: + size -= 1 + return size + + def run(): """Displayes the credits""" from . import settings @@ -15,8 +35,10 @@ def run(): lines = [] lines_pos = [] itera = -1 - fade = settings.fade - fade_pos = settings.fade_pos + fade = pygame.Surface((settings.screenx_current, settings.screeny_current)) + fade.fill((0, 0, 0)) + fade.set_alpha(0) + fade_pos = fade.get_rect() pygame.mouse.set_visible(False) fade.set_alpha(255) @@ -26,32 +48,31 @@ 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] - size = settings.getmaxsize(settings.typeface, 50, - line, True, color, - screen.get_rect().size, 0) + size = getmaxsize(settings.typeface, 50, + line, screen.get_rect().size, 0) if biggest > size: biggest = size with open("./assets/lang/credits.txt") as credits_file: for line in credits_file: itera += 1 line = line[:-1] - line = settings.modrender(settings.typeface, biggest, + line = modrender(settings.typeface, biggest, 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 +93,4 @@ def run(): for credit in range(len(lines)): lines_pos[credit].top -= 2 - pygame.mouse.set_visible(True) \ No newline at end of file + pygame.mouse.set_visible(True) diff --git a/src/objects.py b/src/objects.py index 12578e7..d89aa0d 100644 --- a/src/objects.py +++ b/src/objects.py @@ -3,6 +3,7 @@ import pygame import random import math from . import settings +from . import menu from pygame.locals import * """Classes for creating objects""" @@ -19,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, @@ -32,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 @@ -68,59 +69,6 @@ class stars(): self.pointy = self.relative_y * self.screeny -class inputfield(): - - def __init__(self, x, y, typ, text, color): - print "used" - """Creates a new inputfield""" - self.font = pygame.font.SysFont(settings.typeface, 30) - self.header = text - if typ == 1: - self.field = settings.field - elif typ == 2: - self.field = settings.field1 - self.pos = settings.field.get_rect() - self.pos = self.pos.move(x - (self.pos.w / 2.0), y - (self.pos.h / 2.0)) - self.text = "" - self.render_text = settings.modrender(settings.typeface, 30, self.text, - True, color, - self.pos.size, 9) - self.textpos = self.render_text.get_rect() - self.textpos.center = self.pos.center - self.render_header = settings.modrender(settings.typeface, 30, self.header, - True, color, - settings.screen.get_rect().size, 0) - self.headerpos = self.render_header.get_rect() - self.headerpos.center = self.pos.center - self.headerpos.y -= 50 - - def gettext(self): - """Returns text if return is pressed or removes one if return is pressed""" - from . import interface - key = interface.getall(False) - if key is not None and self.textpos.width < self.pos.width - 18: - self.text = self.text + key - if key is None: - key = interface.getall(True) - if key == "return": - return self.text - if key == "backspace": - self.text = self.text[:len(self.text) - 1] - - def blit(self): - """Blits the inputfield""" - color = settings.color - screen = settings.screen - self.render_text = settings.modrender(settings.typeface, 30, self.text, - True, color, - self.pos.size, 9) - self.textpos = self.render_text.get_rect() - self.textpos.center = self.pos.center - screen.blit(self.render_header, self.headerpos) - screen.blit(self.field, self.pos) - screen.blit(self.render_text, self.textpos) - - class bullet(): def __init__(self, angle, reference): @@ -141,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 @@ -194,13 +142,8 @@ class target(): def update(self): """Adjusts position according to screen size""" - self.pos_x = self.pos_xper * float(settings.world.background_pos.w - - 20 - self.pos.w) + 10 + self.pos.w / 2.0 - self.pos_y = self.pos_yper * float(settings.world.background_pos.h - - 20 - self.pos.h) + 10 + self.pos.h / 2.0 - self.pos_x = self.pos_xper * float(settings.world.background_pos.w - - 20 - self.pos.w) + 10 + self.pos.w / 2.0 - self.pos_y = self.pos_yper * ((settings.screeny_current - self.pos.h) * 2.0) + self.pos_x = self.pos_xper * 2 * float(settings.screenx_current - self.pos.w) + self.pos_y = self.pos_yper * 2 * float(settings.screeny_current - self.pos.h) def move(self, x, y): """Moves rect according to playerposition""" @@ -232,18 +175,90 @@ 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 - return False \ No newline at end of file + return False + + +class warp_station(): + + def __init__(self): + self.x_pos = random.random() + self.y_pos = random.random() + self.screen = settings.screen + self.update() + + def update(self): + """Adjusts to screen size""" + self.img = pygame.image.load("./assets/sprites/station1.tif") + self.img = pygame.transform.smoothscale(self.img, + (int(settings.screenx_current * 0.1), + int(settings.screenx_current * 0.1) + )) + self.pos = self.img.get_rect() + self.pos.x = self.x_pos * 2 * float(settings.screenx_current - self.pos.w) + self.pos.y = self.y_pos * 2 * float(settings.screeny_current - self.pos.h) + self.anchorx, self.anchory = self.pos.topleft + + def move(self, playerpos): + self.pos.left = self.anchorx - playerpos.x + self.pos.top = self.anchory - playerpos.y + + def test(self, playerpos): + def testpoint(point): + x_sqr = ((point[0] * point[0]) + - (2.0 * self.pos.centerx * point[0]) + + (self.pos.centerx * self.pos.centerx)) + y_sqr = ((point[1] * point[1]) + - (2.0 * self.pos.centery * point[1]) + + (self.pos.centery * self.pos.centery)) + if math.sqrt(x_sqr + y_sqr) < self.pos.w / 2.0: + return True + else: + return False + + def test_collide(): + test = testpoint(playerpos.topleft) + test = test or testpoint(playerpos.bottomleft) + test = test or testpoint(playerpos.topright) + test = test or testpoint(playerpos.bottomright) + return test + if test_collide(): + # 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] + settings.world.adjust_to_screen() + settings.player.up = False + settings.player.down = False + settings.player.left = False + settings.player.right = False + settings.up = False + settings.down = False + settings.left = False + settings.right = False + while test_collide(): + if settings.player.pos.center[0] < self.pos.center[0]: + settings.player.move_ip(-20, 0) + else: + settings.player.move_ip(20, 0) + if settings.player.pos.center[1] < self.pos.center[1]: + settings.player.move_ip(0, -20) + else: + settings.player.move_ip(0, 20) + playerpos = settings.player.pos + + def blit(self): + self.screen.blit(self.img, self.pos) diff --git a/src/player.py b/src/player.py index f463e4d..472779a 100644 --- a/src/player.py +++ b/src/player.py @@ -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: self.pos.right += settings.screenx_current - self.pos.right -#lint:enable + #lint:enable - #updates player image if neccesary + # updates player image if neccesary if self.update: self.update = False self.select_picture() @@ -147,9 +145,9 @@ class player(): def select_angle(self, up, down, left, right): self.should_move = False - #sets the direction depending of input + # sets the direction depending of input if not (up == down and left == right): - #diagonal moves + # diagonal moves if up and left and not down and not right: self.should_move = True self.rot_dest = 315 @@ -162,7 +160,7 @@ class player(): if down and right and not up and not left: self.should_move = True self.rot_dest = 135 - #moving in y != x + # moving in y != x if up and not down: if left == right: self.should_move = True @@ -196,4 +194,4 @@ class player(): self.rot_dest = 0 self.rotation = 0 self.speedboost = 1 - self.pos = self.img.get_rect() \ No newline at end of file + self.pos = self.img.get_rect() diff --git a/src/settings.py b/src/settings.py index d6235ec..417876c 100644 --- a/src/settings.py +++ b/src/settings.py @@ -28,21 +28,14 @@ def init(): global aspect_ratio # aspect ratio global screenx_current # current x pixels global screeny_current # current y pixels - global fade # a black surface - global fade_pos # position of the black surface - global fake_size # the ratio of screenx_current and the size of the background + global fake_size # the ratio of screenx_current and size of the background global bullets # list of all bullets global dstars # amount of stars global debugscreen # determines wether to show debug info global debugmode # Enables debugmode global isnear # easteregg - global button # image for the button - global buttonover # = when hovered over - global buttonclick # = when clicked + global background # background image global field # image for the inputfield - global field1 # other image for inputfield - global knob # knob image - global box # button image global bullet_img # image for the bullet global targeton_img # surf for target whenlight turned on global targetoff_img # surf for target when turned off @@ -60,25 +53,23 @@ def init(): global explosions_disp # list of showing explosions global run # boolean for main loop global dtargets # amount of targets - global include_music - global morevents - global infinitevents - global musicend - global border1 + global morevents # custom event logger + global infinitevents # A event logger which retriggers as long as condition + global musicend # custom event number to show that music ended + global border1 # A box to hold the status information about energy level global world # a placeholder for the world class global objects_on_screen # entitys currently blitted to screen global player # abstract player class global localmap # A dict of the local worlds global loading_time # time until first blit global seed # the environments seed - global button_ratio # The ratio from height to length of buttons - #for this operation os.urandom is used + # for this operation os.urandom is used seed_size = 16 seed = random.randint(10 ** (seed_size - 1), (10 ** seed_size) - 1) random.seed(seed) - #set up screen + # set up screen pygame.event.set_grab(False) pygame.mouse.set_visible(False) @@ -87,21 +78,17 @@ def init(): pygame.display.set_mode((1, 1)) aspect_ratio = screenx / float(screeny) screenx_current = screenx - screeny_current = int(screenx_current * 9.0 / 16.0) + screeny_current = screeny - #create empty folders if needed + # create empty folders if needed if not os.path.exists("./assets/sprites/player/"): os.makedirs("./assets/sprites/player/") if not os.path.exists("./screenshots/"): os.makedirs("./screenshots/") - #load images and convert them to the fatest blittable format + # load images and convert them to the fatest blittable format background = pygame.image.load("./assets/sprites/Background2.tif").convert() - fade = pygame.Surface((screenx, screeny)) - #TODO remove use of button - button = pygame.image.load("./assets/sprites/Button1.tif").convert_alpha() field = pygame.image.load("./assets/sprites/inputbox1.tif").convert_alpha() - field1 = pygame.image.load("./assets/sprites/inputbox2.tif").convert_alpha() bullet_img = pygame.image.load("./assets/sprites/Bullet.tif").convert_alpha() targeton_img = pygame.image.load("./assets/sprites/mine_on.tif" ).convert_alpha() @@ -109,23 +96,20 @@ def init(): ).convert_alpha() border1 = pygame.image.load("./assets/sprites/bar1.tif").convert_alpha() - fade_pos = fade.get_rect() # lint:ok - - #define some konstants or default values + # define some konstants or default values clock = pygame.time.Clock() typeface = "monospace" stdfont = pygame.font.SysFont(typeface, 15) - version = "0.3.2.8 dev" + version = "0.3.3" up = False down = False left = False right = False konstspeed = 0.0025 - button_ratio = 7.0 fullscreen = False debugscreen = False - debugmode = True + debugmode = False dstars = 500 isnear = "False" code = "" @@ -139,7 +123,6 @@ def init(): current_game = "default" run = True dtargets = 5 - include_music = False morevents = [] bullets = [] infinitevents = {"fire1": False, "roundfire": False} @@ -153,11 +136,11 @@ def init(): pygame.display.set_caption("Project Interstellar " + version) pygame.display.set_icon(pygame.image.load("./assets/sprites/logo.png")) - #more complex default settings like creation of stars and targets and so on + # more complex default settings like creation of stars and targets and so on if debugmode: - #Add custom handler here for when debugmode is activated + # Add custom handler here for when debugmode is activated volume = 0.0 - #fullscreen = False + # fullscreen = False pass def get_anim_source(num, quantity): @@ -183,7 +166,7 @@ def init(): saves = [] for filename in os.listdir("./saves"): if filename.endswith(".ini"): - filename = unicode(filename[:-4]) + filename = filename[:-4].decode("utf-8") saves.append(filename) if fullscreen: @@ -205,6 +188,16 @@ def init(): world = localmap["1"] upd("adjust_screen") + #scales images so they fill screen especially when not 16/9 ar + if aspect_ratio > 16.0 / 9: + ratio = screenx_current / float(background.get_size()[1]) + pygame.transform.smoothscale(background, + (screenx_current, screeny_current * ratio)) + elif aspect_ratio < 16.0 / 9: + ratio = screeny_current / float(background.get_size()[0]) + pygame.transform.smoothscale(background, + (screenx_current * ratio, screeny_current)) + def reset(): @@ -216,7 +209,6 @@ def reset(): pygame.mouse.set_visible(False) player.reset() - fade_pos = fade.get_rect() # lint:ok konstspeed = 0.0025 color = (255, 255, 10) @@ -240,8 +232,10 @@ def upd(level): if level == "screenvalues": global screenx_current global screeny_current + global aspect_ratio screenx_current = pygame.display.Info().current_w - screeny_current = int(screenx_current * 9.0 / 16.0) + screeny_current = pygame.display.Info().current_h + aspect_ratio = screenx_current / float(screeny_current) return if level == "get_saves": global saves @@ -249,30 +243,47 @@ def upd(level): for filename in os.listdir("./saves"): if filename.endswith(".ini"): filename = filename[:-4] - if not filename in ("default"): + if filename not in ("default"): saves.append(filename) return if level == "adjust_screen": - from . import draw global background global background_pos global konstspeed - global no16to9 + global fullscreenold + global fullscreen + + if fullscreenold != fullscreen: + if fullscreen: + pygame.display.set_mode((screenx, screeny), pygame.FULLSCREEN) + if not fullscreen: + pygame.display.set_mode((screenx / 2, screeny / 2)) + fullscreenold = fullscreen - draw.adjustscreen() upd("screenvalues") konstspeed = 0.0025 konstspeed = konstspeed * (screenx_current / 1920.0) world.adjust_to_screen() + + #scales images so they fill screen especially when not 16/9 ar + if aspect_ratio > 16.0 / 9: + ratio = screenx_current / float(background.get_size()[1]) + pygame.transform.smoothscale(background, + (screenx_current, int(screeny_current * ratio))) + elif aspect_ratio < 16.0 / 9: + ratio = screeny_current / float(background.get_size()[0]) + pygame.transform.smoothscale(background, + (int(screenx_current * ratio), screeny_current)) + return print("Something went wrong here") raise Exception def toggle(var, option1, option2): - #toggles between option1 and 2 and retunr var, saves some space + # toggles between option1 and 2 and retunr var, saves some space if var == option1: var = "yep" if var == option2: @@ -282,34 +293,6 @@ def toggle(var, option1, option2): return var -def modrender(typeface, size, text, antialias, color, maxsize, borderoff): - #local typeface! - nofit = True - while nofit: - tmpfont = pygame.font.SysFont(typeface, size) - bool1 = tmpfont.size(text)[0] < maxsize[0] - (2 * borderoff) - nofit = not (bool1 and tmpfont.size(text)[1] < maxsize[1] - (2 * borderoff)) - if size <= 5: - nofit = False - else: - size -= 1 - return tmpfont.render(text, antialias, color) - - -def getmaxsize(typeface, size, text, antialias, color, maxsize, borderoff): - #local typeface! - nofit = True - while nofit: - tmpfont = pygame.font.SysFont(typeface, size) - bool1 = tmpfont.size(text)[0] < maxsize[0] - (2 * borderoff) - nofit = not (bool1 and tmpfont.size(text)[1] < maxsize[1] - (2 * borderoff)) - if size <= 5: - nofit = False - else: - size -= 1 - return size - - class save(): def __init__(self, name): @@ -325,7 +308,7 @@ class save(): if len(saves) >= 50: return False - #removes invalid characters + # removes invalid characters if "/" in name: name = name.replace("/", "\\") if "%" in name: @@ -333,13 +316,13 @@ class save(): current_game = name - #handles the configparser object + # handles the configparser object self.config = SafeConfigParser() self.config.read("./saves/" + name + ".ini") if not os.path.isfile("./saves/" + name + ".ini"): self.config.add_section("main") - #sets values + # sets values self.config.set("main", "fullscreen", str(fullscreen)) self.config.set("main", "screenx_current", str(screenx_current)) self.config.set("main", "screeny_current", str(screeny_current)) @@ -349,7 +332,7 @@ class save(): self.config.set("main", "posx", str(player.pos.x)) self.config.set("main", "posy", str(player.pos.y)) self.config.set("main", "volume", str(volume)) - #and writes them + # and writes them with open("./saves/" + name + ".ini", "w") as tmp: self.config.write(tmp) @@ -377,9 +360,9 @@ def load(name): config.read("./saves/" + a + ".ini") if not (saves == []): - #tries to load and returns values in terminal that couldnt be loaded + # tries to load and returns values in terminal that couldnt be loaded + import ConfigParser try: - #from ConfigParser import * from . import sounds #lint:disable fullscreen = config.getboolean("main", "fullscreen") @@ -392,7 +375,7 @@ def load(name): pos_y = config.getfloat("main", "posx") sounds.music.volume = config.getfloat("main", "volume") #lint:enable - except SafeConfigParser.NoOptionError as test: + except ConfigParser.NoOptionError as test: print(("Saved game couldn't be loaded completly: " + str(test))) except Exception: print(("Unexpected error:", sys.exc_info()[0])) @@ -407,4 +390,4 @@ def quit(): midi_in.quit() pygame.quit() shutil.rmtree('./assets/sprites/player') - sys.exit() \ No newline at end of file + sys.exit() diff --git a/src/sounds.py b/src/sounds.py index 565b0bf..a261d37 100644 --- a/src/sounds.py +++ b/src/sounds.py @@ -8,4 +8,4 @@ def init(): music = tygamusic.CreateQueue("./assets/music/", "$not$", settings.musicend) music.update(False, False) - music.volume = settings.volume \ No newline at end of file + music.volume = settings.volume diff --git a/src/specials.py b/src/specials.py index 6f485e4..17da69b 100644 --- a/src/specials.py +++ b/src/specials.py @@ -34,7 +34,7 @@ def update(): tmp = objects.bullet(tmpangle, settings.player.pos) settings.bullets.append(tmp) - #shoots in 8 direction and the one youre looking constantly + # shoots in 8 direction and the one youre looking constantly if settings.psycomode: tmp = objects.bullet(settings.player.rotation, settings.player.pos) settings.bullets.append(tmp) @@ -50,7 +50,6 @@ def update(): tmp = objects.bullet(tmpangle, settings.player.pos) settings.bullets.append(tmp) if event == "Add": - #lint:disable if amount < 20: amount += 1 else: @@ -77,5 +76,5 @@ def update(): if direction != "Clock": tmpan = 360 - tmpan tmp = objects.bullet(a * diffangle + tmpan, settings.player.pos) - #lint:enable - settings.bullets.append(tmp) \ No newline at end of file + settings.bullets.append(tmp) + #lint:enable diff --git a/src/worlds.py b/src/worlds.py index 6d66a87..3c4faf1 100644 --- a/src/worlds.py +++ b/src/worlds.py @@ -1,10 +1,7 @@ from . import settings from . import objects from . import draw -from . import menu import pygame -import random -import math """An abstact level for handeling multiple worlds.""" @@ -15,18 +12,18 @@ class world(): pass def generate(self, background, dstars, dtargets): - #initialize a new "world" + # initialize a new "world" - #load background image + # load background image self.background = background self.background_pos = self.background.get_rect() - #set background position + # set background position self.background_pos.left = int(-(settings.player.rel_x * ( settings.screenx_current * (settings.fake_size - 1)))) self.background_pos.top = int(-(settings.player.rel_y * ( settings.screeny_current * (settings.fake_size - 1)))) - #create targets and stars + # create targets and stars self.stars = [] self.targets = [] for counter in range(dstars): @@ -36,77 +33,7 @@ class world(): tmptarget = objects.target() self.targets.append(tmptarget) - class warp(): - - def __init__(self): - self.x_pos = random.random() - self.y_pos = random.random() - self.screen = settings.screen - self.update() - - def update(self): - self.img = pygame.image.load("./assets/sprites/station1.tif") - self.img = pygame.transform.smoothscale(self.img, - (int(settings.screenx_current * 0.1), - int(settings.screenx_current * 0.1) - )) - self.pos = self.img.get_rect() - self.pos.x = self.x_pos * (settings.world.background_pos.w - self.pos.w) - self.pos.y = self.y_pos * (settings.world.background_pos.h - self.pos.h) - self.anchorx, self.anchory = self.pos.topleft - - def move(self, playerpos): - self.pos.left = self.anchorx - playerpos.x - self.pos.top = self.anchory - playerpos.y - - def test(self, playerpos): - def testpoint(point): - x_sqr = ((point[0] * point[0]) - - (2.0 * self.pos.centerx * point[0]) - + (self.pos.centerx * self.pos.centerx)) - y_sqr = ((point[1] * point[1]) - - (2.0 * self.pos.centery * point[1]) - + (self.pos.centery * self.pos.centery)) - if math.sqrt(x_sqr + y_sqr) < self.pos.w / 2.0: - return True - else: - return False - - def test_collide(): - test = testpoint(playerpos.topleft) - test = test or testpoint(playerpos.bottomleft) - test = test or testpoint(playerpos.topright) - test = test or testpoint(playerpos.bottomright) - return test - if test_collide(): - #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] - settings.world.adjust_to_screen() - settings.player.up = False - settings.player.down = False - settings.player.left = False - settings.player.right = False - settings.up = False - settings.down = False - settings.left = False - settings.right = False - while test_collide(): - if settings.player.pos.center[0] < self.pos.center[0]: - settings.player.move_ip(-20, 0) - else: - settings.player.move_ip(20, 0) - if settings.player.pos.center[1] < self.pos.center[1]: - settings.player.move_ip(0, -20) - else: - settings.player.move_ip(0, 20) - playerpos = settings.player.pos - - def blit(self): - self.screen.blit(self.img, self.pos) - - self.warp1 = warp() + self.warp1 = objects.warp_station() self.adjust_to_screen() @@ -148,10 +75,10 @@ class world(): def blit(self): """Blit everything in the world.""" - #blit background + # blit background settings.screen.blit(self.background, self.background_pos) - #Blit all objects + # Blit all objects settings.objects_on_screen = 0 for star in self.stars: isdisplayed = star.blitstar() @@ -188,10 +115,13 @@ class world(): draw.no16to9 = False if settings.aspect_ratio != 16.0 / 9: draw.no16to9 = True - delta_screeny = settings.screeny - settings.screeny_current - draw.correcture = pygame.Surface((settings.screenx, delta_screeny)) + delta_screeny = (settings.screeny_current + - (settings.screenx_current * 9.0 / 16)) + draw.correcture = pygame.Surface((settings.screenx_current, delta_screeny) + ).convert_alpha() draw.correcture_pos = draw.correcture.fill((0, 0, 0)) - draw.correcture_pos.bottomleft = (0, settings.screeny) + draw.correcture.set_alpha(255) + draw.correcture_pos.topleft = (0, (settings.screenx_current * 9.0 / 16)) for star in self.stars: star.update(settings.screenx_current / 1920.0) @@ -199,4 +129,4 @@ class world(): for target in self.targets: target.update() - self.warp1.update() \ No newline at end of file + self.warp1.update() diff --git a/todo¬es.txt b/todo¬es.txt deleted file mode 100644 index 18dfa03..0000000 --- a/todo¬es.txt +++ /dev/null @@ -1,2 +0,0 @@ --use … more often -(look at trello for really important info)