Skip to content

Commit b7ca520

Browse files
authored
Create snake.py
SnakeGame created
1 parent 473c721 commit b7ca520

File tree

1 file changed

+164
-0
lines changed

1 file changed

+164
-0
lines changed

SnakeGame/snake.py

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import cv2
2+
import numpy as np
3+
from random import randint
4+
from random import choice
5+
6+
7+
class SnakePart:
8+
def __init__(self, front, x, y):
9+
self.front = front
10+
self.x = x
11+
self.y = y
12+
13+
def move(self):
14+
# Moves by following the part in front of it
15+
self.x = self.front.x
16+
self.y = self.front.y
17+
18+
class Head:
19+
def __init__(self, direction, x, y):
20+
self.direction = direction
21+
self.x = x
22+
self.y = y
23+
24+
def move(self):
25+
# Checks what its current direction is and moves accordingly
26+
if self.direction == 0:
27+
self.x += 1
28+
elif self.direction == 1:
29+
self.y += 1
30+
elif self.direction == 2:
31+
self.x -= 1
32+
elif self.direction == 3:
33+
self.y -= 1
34+
35+
def display():
36+
37+
# Create a blank image
38+
board = np.zeros([BOARD_SIZE, BOARD_SIZE, 3])
39+
40+
# Color the snake green
41+
for part in snake:
42+
board[part.y, part.x] = [0, 255, 0]
43+
44+
# Color the apple red
45+
board[appley, applex] = [0, 0, 255]
46+
47+
# Display board
48+
cv2.imshow("Snake Game", np.uint8(board.repeat(CELL_SIZE, 0).repeat(CELL_SIZE, 1)))
49+
key = cv2.waitKey(int(1000/SPEED))
50+
51+
# Return the key pressed. It is -1 if no key is pressed.
52+
return key
53+
54+
def win_focus():
55+
# Ugly trick to get the window in focus.
56+
# Opens an image in fullscreen and then back to normal window
57+
cv2.namedWindow("Snake Game", cv2.WINDOW_NORMAL);
58+
board = np.zeros([BOARD_SIZE * CELL_SIZE, BOARD_SIZE * CELL_SIZE, 3])
59+
cv2.imshow("Snake Game", board);
60+
cv2.setWindowProperty("Snake Game", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN);
61+
cv2.waitKey(2000)
62+
cv2.setWindowProperty("Snake Game", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_AUTOSIZE)
63+
64+
65+
if __name__ == '__main__' :
66+
67+
# Size of each cell in the board game
68+
CELL_SIZE = 20
69+
# Number of cells along the width in the game
70+
BOARD_SIZE = 45
71+
# Change SPEED to make the game go faster
72+
SPEED = 12
73+
# After eating an apple the snake grows by GROWTH units
74+
GROWTH = 3
75+
76+
77+
# Variable to track if apple is eaten
78+
eaten = True
79+
# Variable to check if the game should quit
80+
quit = False
81+
# Variable to track growth.
82+
grow = 0
83+
84+
# Array for storing snake
85+
snake = []
86+
87+
#snake's head starts at the center of the board.
88+
head = Head(0, int((BOARD_SIZE - 1)/2), int((BOARD_SIZE - 1)/2))
89+
snake.append(head)
90+
91+
# Start the game by printing instructions
92+
print('w = top, a = left, s = down, d = right')
93+
# Ugly trick to bring the window in focus
94+
win_focus()
95+
96+
while True:
97+
98+
# Checks if the apple is eaten and generates a new one
99+
if eaten:
100+
# Create a list of all possible locations
101+
s = list(range(0, BOARD_SIZE ** 2))
102+
# Delete cells that are part of the snake
103+
try:
104+
for part in snake:
105+
s.remove(part.x*45 + part.y)
106+
except:
107+
pass
108+
109+
# Randomly pick from one of the remaining cells
110+
a = choice(s)
111+
applex = int(a/BOARD_SIZE)
112+
appley = a % BOARD_SIZE
113+
114+
eaten = False
115+
116+
# Makes and displays the board
117+
key = display()
118+
119+
120+
# Gets key presses and moves accordingly
121+
# 8 and 27 are delete and escape keys
122+
# Arrow keys are tricky in OpenCV. So we use
123+
# keys 'w', 'a','s','d' for movement.
124+
# w = top, a = left, s = down, d = right
125+
126+
127+
if key == 8 or key == 27:
128+
break
129+
elif key == ord("d") :
130+
head.direction = 0
131+
elif key == ord("s") :
132+
head.direction = 1
133+
elif key == ord("a") :
134+
head.direction = 2
135+
elif key == ord("w") :
136+
head.direction = 3
137+
138+
# Moving the snake
139+
for part in snake[::-1]:
140+
part.move()
141+
142+
# Collision rules
143+
144+
if head.x < 0 or head.x > BOARD_SIZE - 1 or head.y < 0 or head.y > BOARD_SIZE - 1:
145+
break
146+
147+
for part in snake[1:]:
148+
if head.x == part.x and head.y == part.y:
149+
quit = True
150+
break
151+
152+
if quit:
153+
break
154+
155+
# Grows the snake when it eats an apple
156+
if applex == head.x and appley == head.y:
157+
subx = snake[-1].x
158+
suby = snake[-1].y
159+
eaten = True
160+
grow += GROWTH
161+
# The snake grows graduallly over multiple frames
162+
if grow > 0:
163+
snake.append(SnakePart(snake[-1], subx, suby))
164+
grow -= 1

0 commit comments

Comments
 (0)