Skip to content

Commit c02da52

Browse files
committed
Initial commit
1 parent 259dd33 commit c02da52

2 files changed

Lines changed: 345 additions & 0 deletions

File tree

highscore.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
26

snake.py

Lines changed: 344 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,344 @@
1+
#!/usr/bin/python
2+
3+
import os, sys, random
4+
import pygame
5+
from pygame.sprite import Sprite
6+
7+
#sys.stdout = os.devnull
8+
#sys.stderr = os.devnull
9+
10+
class box(object):
11+
def __init__(self, screen, blockSize, x, y, bType = 'body'):
12+
self.screen = screen
13+
self.blockSize = blockSize
14+
self.direction = 2
15+
self.bType = bType
16+
self.x = x
17+
self.y = y
18+
self.color = (245, 101, 44)
19+
self.back = None
20+
self.directionChanged = 0
21+
22+
def getDirection(self):
23+
return self.direction
24+
25+
def setDirection(self, direction):
26+
#self.directionChanged = 1
27+
self.direction = direction
28+
29+
def update(self):
30+
if self.direction == 1:
31+
self.y = self.y -1
32+
elif self.direction == 2:
33+
self.x = self.x +1
34+
elif self.direction == 3:
35+
self.y = self.y +1
36+
elif self.direction == 4:
37+
self.x = self.x -1
38+
39+
#if self.back != None:
40+
# self.back.setDirection(self.direction)
41+
42+
def blit(self):
43+
relX = self.x * self.blockSize
44+
relY = self.y * self.blockSize
45+
pygame.draw.rect(self.screen, self.color, (relX, relY, self.blockSize, self.blockSize) )
46+
if self.back != None:
47+
self.back.setDirection(self.direction)
48+
49+
class game(object):
50+
def __init__(self):
51+
self.screen = None
52+
self.playerBox = None
53+
54+
def move(self, direction):
55+
#print 'direction:', direction
56+
if self.playerBox != None:
57+
curDir = self.playerBox.getDirection()
58+
# DONT move backwards!
59+
if (curDir == 1 and direction == 3) or (curDir == 3 and direction == 1):
60+
pass
61+
elif (curDir == 2 and direction == 4) or (curDir == 4 and direction == 2) :
62+
pass
63+
else:
64+
self.playerBox.setDirection(direction)
65+
66+
def getLastElement(self):
67+
tmp = self.playerBox
68+
found = False
69+
while found == False:
70+
if tmp.back == None:
71+
found = True
72+
else:
73+
tmp = tmp.back
74+
return tmp
75+
76+
def getBodyLen(self):
77+
tmp = self.playerBox
78+
cnt = 0
79+
while tmp != None:
80+
tmp = tmp.back
81+
cnt += 1
82+
return cnt
83+
84+
def fieldContainsBox(self, elements, x, y):
85+
for elem in elements:
86+
if elem.x == x and elem.y == y:
87+
return True
88+
return False
89+
90+
def addSnack(self, elements):
91+
snackCount = 0
92+
coords = []
93+
for elem in elements:
94+
coords.append([ elem.x, elem.y ])
95+
if elem.bType == 'snack':
96+
snackCount += 1
97+
98+
#print 'snackCount', snackCount
99+
if snackCount < self.SNACKS:
100+
xy = [random.randint(1, (self.SCREEN_WIDTH / self.BLOCKSIZE)-1), random.randint(1, (self.SCREEN_HEIGHT / self.BLOCKSIZE-1))]
101+
if not xy in coords:
102+
snack = box(self.screen, self.BLOCKSIZE, xy[0], xy[1])
103+
snack.bType = 'snack'
104+
snack.color = (99, 255, 99)
105+
snack.direction = 0
106+
elements.append(snack)
107+
108+
def eatSnack(self, elements):
109+
for elem in elements:
110+
if elem.bType == 'snack' and elem.x == self.playerBox.x and elem.y == self.playerBox.y:
111+
elements.remove(elem)
112+
return (self.playerBox.x, self.playerBox.y)
113+
return None
114+
115+
def headDied(self, elements):
116+
dead = False
117+
# collision with myself or stuff
118+
for elem in elements:
119+
if elem.bType != 'head' and elem.bType != 'snack' and elem.bType:
120+
if self.playerBox.x == elem.x and self.playerBox.y == elem.y:
121+
dead = True
122+
123+
# border collision
124+
if self.playerBox.x < 0 or self.playerBox.y < 0 or self.playerBox.x > (self.SCREEN_WIDTH / self.BLOCKSIZE)-1 or self.playerBox.y > (self.SCREEN_HEIGHT / self.BLOCKSIZE)-1:
125+
dead = True
126+
127+
if dead == True:
128+
highscores = '0'
129+
scores = self.getBodyLen()
130+
if os.path.isfile("highscore.txt") == True:
131+
f = open("highscore.txt", 'r')
132+
highscores = f.read()
133+
f.close()
134+
135+
if scores > int(highscores):
136+
highscores = str(scores)
137+
f = open("highscore.txt", 'w')
138+
f.write(highscores)
139+
f.close()
140+
141+
lines = ['GAME OVER', 'POINTS: ' + str(scores), "HIGHSCORE "+highscores, "Button / Keyboard: 1 = Speed Up", "Button / Keyboard: 2 = Speed Down", "R = restart / respawn", 'Q = Quit / Exit']
142+
fontSize = 30
143+
fnt = pygame.font.SysFont("MS Comic Sans", fontSize)
144+
xPos = (self.SCREEN_WIDTH / 2)
145+
#print fnt.size(resultText)
146+
for i in range(len(lines)):
147+
txt = lines[i]
148+
self.screen.blit(fnt.render(txt, 1, (0,0,255)), ( xPos - (fnt.size(txt)[0] / 2), 250 +(i * fontSize)))
149+
150+
return dead
151+
152+
def resetGame(self):
153+
self.playerBox = box(self.screen, self.BLOCKSIZE, 3, 3)
154+
self.playerBox.bType = 'head'
155+
156+
self.elements = []
157+
self.elements.append(self.playerBox)
158+
159+
self.haveToAdd = [[3, 3], [3, 3], [3, 3]]
160+
161+
def gameSpeedUp(self):
162+
self.gameSpeedFactor += 1
163+
if self.gameSpeedFactor >= len(self.gameSpeedFactors):
164+
self.gameSpeedFactor -= 1
165+
166+
def gameSpeedDown(self):
167+
self.gameSpeedFactor -= 1
168+
if self.gameSpeedFactor < 0:
169+
self.gameSpeedFactor = 0
170+
171+
def run_game(self):
172+
# Game parameters
173+
self.SCREEN_WIDTH = 1024
174+
self.SCREEN_HEIGHT = 600
175+
BG_COLOR = (8, 13, 41)
176+
ORANGE = (245, 101, 44)
177+
self.BLOCKSIZE = 10
178+
self.SNACKS = 10
179+
self.gameSpeed = 250
180+
self.gameSpeedFactors = range(0, 300, 25)
181+
self.gameSpeedFactor = 0
182+
pygame.init()
183+
184+
# do fancy window stuff
185+
pygame.display.set_caption("SNAKE")
186+
#pygame.display.set_icon(pygame.image.load('imgs/bandit.jpg'))
187+
pygame.mouse.set_visible(False)
188+
189+
self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT), 0, 32)
190+
pygame.display.toggle_fullscreen()
191+
clock = pygame.time.Clock()
192+
redrawCount = 0
193+
194+
pygame.joystick.init()
195+
self.myJoystick = None
196+
self.joystick_names = []
197+
198+
# Enumerate joysticks
199+
for i in range(0, pygame.joystick.get_count()):
200+
self.joystick_names.append(pygame.joystick.Joystick(i).get_name())
201+
202+
# By default, load the first available joystick.
203+
if (len(self.joystick_names) > 0):
204+
self.myJoystick = pygame.joystick.Joystick(0)
205+
self.myJoystick.init()
206+
207+
keymap = {pygame.K_UP:1, pygame.K_RIGHT:2, pygame.K_DOWN:3, pygame.K_LEFT:4}
208+
209+
210+
self.playerBox = None
211+
self.elements = []
212+
self.haveToAdd = []
213+
214+
215+
# The main game loop
216+
#
217+
gameOver = False
218+
doMove = -1
219+
joyButtonDown = False
220+
while True:
221+
if self.playerBox == None:
222+
self.resetGame()
223+
224+
# Limit frame speed to 50 FPS
225+
#
226+
time_passed = clock.tick(50)
227+
redrawCount += time_passed
228+
worldChanged = False
229+
230+
if self.myJoystick != None:
231+
xAx = 0
232+
yAx = 0
233+
# sometimes 2 axis, sometimes 6, wtf?!
234+
if self.myJoystick.get_numaxes() == 2:
235+
xAx = 0
236+
yAx = 1
237+
else:
238+
xAx = 3
239+
yAx = 4
240+
if self.myJoystick.get_axis(xAx) > 0:
241+
doMove = 2
242+
elif self.myJoystick.get_axis(xAx) < 0:
243+
doMove = 4
244+
elif self.myJoystick.get_axis(yAx) > 0:
245+
doMove = 3
246+
elif self.myJoystick.get_axis(yAx) < 0:
247+
doMove = 1
248+
249+
if self.myJoystick.get_button(0) and joyButtonDown == False: # speed up
250+
joyButtonDown = True
251+
self.gameSpeedUp()
252+
elif self.myJoystick.get_button(1) and joyButtonDown == False: # speed down
253+
joyButtonDown = True
254+
self.gameSpeedDown()
255+
elif self.myJoystick.get_button(9) and joyButtonDown == False: # (re)start
256+
joyButtonDown = True
257+
self.resetGame()
258+
gameOver = False
259+
else:
260+
# make shure NO button is down for reset
261+
someJoyButtonDown = False
262+
for i in range(0, self.myJoystick.get_numbuttons()):
263+
if (self.myJoystick.get_button(i)):
264+
someJoyButtonDown = True
265+
joyButtonDown = someJoyButtonDown
266+
267+
for event in pygame.event.get():
268+
if event.type == pygame.QUIT:
269+
self.exit_game()
270+
271+
elif event.type == pygame.KEYDOWN:
272+
if event.key in keymap:
273+
doMove = keymap[event.key]
274+
elif event.key == pygame.K_1: # speed up game
275+
self.gameSpeedUp()
276+
elif event.key == pygame.K_2: # slow down up game
277+
self.gameSpeedDown()
278+
elif event.key == pygame.K_r: # restart game
279+
self.resetGame()
280+
gameOver = False
281+
elif event.key == pygame.K_q:
282+
self.exit_game()
283+
else:
284+
print event.key
285+
#if event.key == pygame.K_UP:
286+
# self.move(1)
287+
else:
288+
pass
289+
#print event
290+
291+
if gameOver == False and redrawCount >= (self.gameSpeed - self.gameSpeedFactors[self.gameSpeedFactor]): #or worldChanged == True:
292+
# ONLY move, when the timer elapses!
293+
# otherwise you could change the direction multiple times before the scenery changes and upates
294+
# strange shit goes on!
295+
if doMove != -1:
296+
self.move(doMove)
297+
doMove = -1
298+
299+
redrawCount = 0
300+
self.screen.fill(BG_COLOR)
301+
302+
# move the elements
303+
for elem in reversed(self.elements):
304+
elem.update()
305+
306+
# add elements BEVORE blit is called and they change direction!
307+
# WEIRD stuff would happen otherwise!!!1!!!!!!!!
308+
if len(self.haveToAdd) > 0:
309+
for i in range(len(self.haveToAdd)):
310+
coords = self.haveToAdd[i]
311+
if self.fieldContainsBox(self.elements, coords[0], coords[1]) == False:
312+
lastElem = self.getLastElement()
313+
lastElem.back = box(self.screen, self.BLOCKSIZE, coords[0], coords[1])
314+
lastElem.back.setDirection(lastElem.getDirection())
315+
self.elements.append(self.getLastElement())
316+
self.haveToAdd.pop(i)
317+
break
318+
else:
319+
# if theres NOTHING to add to the Snake, add a new snak, if needed
320+
# preventing from spawning a snack inside the "new" tail of the snake and shit
321+
self.addSnack(self.elements)
322+
323+
# update elements
324+
for elem in reversed(self.elements):
325+
elem.blit()
326+
327+
# if a snak has been eaten, add it to the to add list
328+
snackEaten = self.eatSnack(self.elements)
329+
if snackEaten != None:
330+
self.haveToAdd.append(snackEaten)
331+
332+
# collision!
333+
if self.headDied(self.elements) == True:
334+
gameOver = True
335+
336+
pygame.display.flip()
337+
338+
339+
def exit_game(self):
340+
sys.exit()
341+
342+
343+
snk = game()
344+
snk.run_game()

0 commit comments

Comments
 (0)