-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameloop.py
116 lines (75 loc) · 2.27 KB
/
gameloop.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#import sys
import pygame
import direction
import board
#from threading import Thread
import debug
class Game:
def __init__(self):
# Create the game board
self.board = board.Board()
#graphic size of cells
self.blockSize = 60
# Initialize pygame
pygame.init()
#window
self.screenSize = (self.board.width * self.blockSize, self.board.height * self.blockSize)
self.screen = pygame.display.set_mode(self.screenSize)
#timeticks
self.timeStep = 250 # milliseconds per step
pygame.time.set_timer(pygame.USEREVENT, self.timeStep)
def run(self):
# the player
player = getPlayer(self.timeStep)
loop = True
while loop:
# draw calls
self.updateScreen()
# thread to let the AIs begin computations
player.think(self.board)
# loop for interrupts
while loop :
# get events : clos window, key press or timer expired
event = pygame.event.wait()
# close window
if event.type == pygame.QUIT:
pygame.quit()
return
# handle key press
elif event.type == pygame.KEYDOWN:
player.handleKey(event)
# timer expired
elif event.type == pygame.USEREVENT:
# get decision of player (human or AI)
decision = player.getDecision()
# act on it
if decision!=None : self.board.command(decision)
# update the board
loop = self.board.endTurn() != self.board.DEATH
break
# Game over!
self.updateScreen()
pygame.time.wait(1500)
def updateScreen(self):
self.screen.fill(self.board.color)
self.drawSnake()
self.drawFood();
pygame.display.update()
def drawRect(self, color, x, y):
size = self.blockSize
rect = (x * size, y * size, size, size)
pygame.draw.rect(self.screen, color, rect, 0)
def drawFood(self):
(x, y) = self.board.food.position
self.drawRect(self.board.food.color, x, y )
def drawSnake(self):
color = ()
length = len(self.board.snake.body)
for i in range(0, length):
if( i == 0 ): color = self.board.snake.headColor
else:
r, g, b = self.board.snake.color
factor = (float(length - i) / length) * 0.7 + 0.3 # min 0.3, max 1, linear between
color = int(r * factor), int(g * factor), int(b * factor)
(x, y) = self.board.snake.body[i]
self.drawRect(color, x, y)