-
Notifications
You must be signed in to change notification settings - Fork 1
/
game.py
87 lines (73 loc) · 2.39 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
from tkinter import *
import time
import config
from gui import Gui
import moving
from detector import Detector
class GameMaker:
def __init__(self):
root = Tk()
gui = Gui(root)
ball = moving.Ball()
paddleL = moving.PaddleL()
paddleR = moving.PaddleR()
items = {
'ball': ball,
'paddleL': paddleL,
'paddleR': paddleR,
}
detector = Detector()
self.game = Game(root, gui, items, detector)
def __call__(self):
return self.game
class Game:
framelength = 1 / config.framerate
def __init__(self, root, gui, items, detector):
self.root = root
self.gui = gui
self.items = items
for name, item in self.items.items():
self.gui.addItem(name, item.getCoords())
self.detector = detector
self.registerEvents()
def start(self):
self.gameLoop()
def checkCollisions(self):
for item in self.items.values():
coord = item.getCoords()
result = self.detector.checkBounds(coord)
if result:
item.bounce(result)
def gameLoop(self):
exit = False
try:
while not exit:
start_time = time.clock()
for name, item in self.items.items():
item.move()
self.checkCollisions()
#need to check for collision first
#then resolve collision
#then update gui.
for name, item in self.items.items():
self.gui.move(name, item.getCoords())
self.gui.process()
interval = time.clock() - start_time
pause = self.framelength - interval
if pause > 0:
time.sleep(pause)
except TclError:
pass
def registerEvents(self):
self.root.bind('<Key>', self.keyEvent)
self.root.bind('<KeyRelease>', self.keyUpEvent)
def keyEvent(self, event):
if event.keysym == 'Up':
self.items['paddleR'].startUp()
elif event.keysym == 'Down':
self.items['paddleR'].startDown()
def keyUpEvent(self, event):
if event.keysym == 'Up':
self.items['paddleR'].stop()
elif event.keysym == 'Down':
self.items['paddleR'].stop()