forked from matthiap/snake_project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
196 lines (157 loc) · 6.53 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import random
import pygame
import sys
from pygame.locals import *
Snakespeed= 17
Window_Width= 800
Window_Height= 500
Cell_Size = 20 #Width and height of the cells
assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size." #Ensuring that the cells fit perfectly in the window. eg if cell size was 10 and window width or windowheight were 15 only 1.5 cells would fit.
assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size." #Ensuring that only whole integer number of cells fit perfectly in the window.
Cell_W= int(Window_Width / Cell_Size) #Cell Width
Cell_H= int(Window_Height / Cell_Size) #Cellc Height
White= (255,255,255)
Black= (0,0,0)
Red= (255,0,0) #Defining element colors for the program.
Green= (0,255,0)
DARKGreen= (0,155,0)
DARKGRAY= (40,40,40)
YELLOW= (255,255,0)
Red_DARK= (150,0,0)
BLUE= (0,0,255)
BLUE_DARK= (0,0,150)
BGCOLOR = Black # Background color
UP = 'up'
DOWN = 'down' # Defining keyboard keys.
LEFT = 'left'
RIGHT = 'right'
HEAD = 0 # Syntactic sugar: index of the snake's head
def main():
global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
pygame.init()
SnakespeedCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Snake')
while True:
runGame()
showGameOverScreen()
def runGame():
# Set a random start point.
startx = random.randint(5, Cell_W - 6)
starty = random.randint(5, Cell_H - 6)
wormCoords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT
# Start the apple in a random place.
apple = getRandomLocation()
while True: # main game loop
for event in pygame.event.get(): # event handling loop
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT ) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT ) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP ) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN ) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
# check if the Snake has hit itself or the edge
if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
return # game over
for wormBody in wormCoords[1:]:
if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD] ['y']:
return # game over
# check if Snake has eaten an apply
if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
# don't remove worm's tail segment
apple = getRandomLocation() # set a new apple somewhere
else:
del wormCoords[-1] # remove worm's tail segment
# move the worm by adding a segment in the direction it is moving
if direction == UP:
newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
elif direction == DOWN:
newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
elif direction == LEFT:
newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
elif direction == RIGHT:
newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
wormCoords.insert(0, newHead)
DISPLAYSURF.fill(BGCOLOR)
drawGrid()
drawWorm(wormCoords)
drawApple(apple)
drawScore(len(wormCoords) - 3)
pygame.display.update()
SnakespeedCLOCK.tick(Snakespeed)
def drawPressKeyMsg():
pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
pressKeyRect = pressKeySurf.get_rect()
pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
def checkForKeyPress():
if len(pygame.event.get(QUIT)) > 0:
terminate()
keyUpEvents = pygame.event.get(KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0].key == K_ESCAPE:
terminate()
return keyUpEvents[0].key
def terminate():
pygame.quit()
sys.exit()
def getRandomLocation():
return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
def showGameOverScreen():
gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
gameSurf = gameOverFont.render('Game', True, White)
overSurf = gameOverFont.render('Over', True, White)
gameRect = gameSurf.get_rect()
overRect = overSurf.get_rect()
gameRect.midtop = (Window_Width / 2, 10)
overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
DISPLAYSURF.blit(gameSurf, gameRect)
DISPLAYSURF.blit(overSurf, overRect)
drawPressKeyMsg()
pygame.display.update()
pygame.time.wait(500)
checkForKeyPress() # clear out any key presses in the event queue
while True:
if checkForKeyPress():
pygame.event.get() # clear event queue
return
def drawScore(score):
scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (Window_Width - 120, 10)
DISPLAYSURF.blit(scoreSurf, scoreRect)
def drawWorm(wormCoords):
for coord in wormCoords:
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
def drawApple(coord):
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(DISPLAYSURF, Red, appleRect)
def drawGrid():
for x in range(0, Window_Width, Cell_Size): # draw vertical lines
pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
for y in range(0, Window_Height, Cell_Size): # draw horizontal lines
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))
if __name__ == '__main__':
try:
main()
except SystemExit:
pass