-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
97 lines (93 loc) · 3.12 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import pygame
import sys, platform
import scenes
from scenes.game_scene import GameScene
from scenes.menu_scene import MenuScene
from scenes.opening_scene import OpeningScene
from res import load_img
from res.config import SCREEN_SIZE, GAME_NAME
MAPEV = {
'action': pygame.K_SPACE,
'left': pygame.K_a,
'right': pygame.K_d
}
class GameInput(object):
'''
This class handles keyboard and mouse events.
'''
def __init__(self):
self.__quit = self.__no_operation
self.__key_func = {}
def __no_operation(self):
pass
def set_keypressing(self, key_func_pairs: dict):
'''
Setup a keypressing listener for a key.
set_keypressing must receive a dict containing
pairs of pygame.keys and listeners. For example:
ginput.set_keypressing({pygame.K_t: listener})
To remove listener you can use a pair like:
{pygame.K_t: None}
or call clear_key_func
'''
self.__key_func.update(key_func_pairs)
for k, f in key_func_pairs.items():
if not f:
self.__key_func[k] = self.__no_operation
def set_quit_listener(self, listener:'function'):
'''
Set a listener for quit (X button) event.
If listener = None then quit operation will
be not executed anymore
'''
self.__quit = listener if listener else self.__no_operation
def clear_key_func(self):
'''
Removes all listeners for all keys.
'''
self.__key_func = {}
def is_key_pressed(self, key):
if sys.platform == 'emscripten':
if platform.window.pressedButtons:
for ev in platform.window.pressedButtons:
if MAPEV[ev] == key:
return True
return pygame.key.get_pressed()[key]
def listen(self):
'''
Listen for mouse and keyboard events
'''
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
self.__quit()
for k, func in self.__key_func.items():
if self.is_key_pressed(k):
func()
class Game(object):
'''
Handle game stuff. Can be controled everywhere by
accessing game_instance
'''
def __init__(self):
self.screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption(GAME_NAME)
pygame.display.set_icon(load_img('icon.png'))
self.screen.fill('black')
self.running = False
self.game_input = GameInput()
self.game_input.set_quit_listener(self.quit)
self.clock = pygame.Clock()
def quit(self):
''' set running to false '''
self.running = False
def iterate(self) -> bool:
''' performs one iteration of the game
and returns true if game still running '''
if not self.running:
scenes.boot_scene(OpeningScene())
self.running = True
self.game_input.listen()
scenes.current_scene_update()
self.clock.tick(60)
pygame.display.set_caption(f'{GAME_NAME} (fps: {int(self.clock.get_fps())})')
return self.running