Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8ed29fc

Browse files
committedJan 29, 2022
add ConsoleSnake project
1 parent 035b932 commit 8ed29fc

File tree

5 files changed

+468
-0
lines changed

5 files changed

+468
-0
lines changed
 

‎ConsoleSnake/.gitignore

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
pip-wheel-metadata/
24+
share/python-wheels/
25+
*.egg-info/
26+
.installed.cfg
27+
*.egg
28+
MANIFEST
29+
30+
# PyInstaller
31+
# Usually these files are written by a python script from a template
32+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
33+
*.manifest
34+
*.spec
35+
36+
# Installer logs
37+
pip-log.txt
38+
pip-delete-this-directory.txt
39+
40+
# Unit test / coverage reports
41+
htmlcov/
42+
.tox/
43+
.nox/
44+
.coverage
45+
.coverage.*
46+
.cache
47+
nosetests.xml
48+
coverage.xml
49+
*.cover
50+
*.py,cover
51+
.hypothesis/
52+
.pytest_cache/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
target/
76+
77+
# Jupyter Notebook
78+
.ipynb_checkpoints
79+
80+
# IPython
81+
profile_default/
82+
ipython_config.py
83+
84+
# pyenv
85+
.python-version
86+
87+
# pipenv
88+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
90+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
91+
# install all needed dependencies.
92+
#Pipfile.lock
93+
94+
# celery beat schedule file
95+
celerybeat-schedule
96+
97+
# SageMath parsed files
98+
*.sage.py
99+
100+
# Environments
101+
.env
102+
.venv
103+
env/
104+
venv/
105+
ENV/
106+
env.bak/
107+
venv.bak/
108+
109+
# Spyder project settings
110+
.spyderproject
111+
.spyproject
112+
113+
# Rope project settings
114+
.ropeproject
115+
116+
# mkdocs documentation
117+
/site
118+
119+
# mypy
120+
.mypy_cache/
121+
.dmypy.json
122+
dmypy.json
123+
124+
# Pyre type checker
125+
.pyre/

‎ConsoleSnake/LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2021 tomimara52
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

‎ConsoleSnake/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# ConsoleSnake
2+
Snake game in your windows, linux or macOS console

‎ConsoleSnake/getch.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
'''
2+
A Python class implementing KBHIT, the standard keyboard-interrupt poller.
3+
Works transparently on Windows and Posix (Linux, Mac OS X). Doesn't work
4+
with IDLE.
5+
6+
This program is free software: you can redistribute it and/or modify
7+
it under the terms of the GNU Lesser General Public License as
8+
published by the Free Software Foundation, either version 3 of the
9+
License, or (at your option) any later version.
10+
11+
This program is distributed in the hope that it will be useful,
12+
but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
GNU General Public License for more details.
15+
16+
'''
17+
18+
import os
19+
20+
# Windows
21+
if os.name == 'nt':
22+
import msvcrt
23+
24+
# Posix (Linux, OS X)
25+
else:
26+
import sys
27+
import termios
28+
import atexit
29+
from select import select
30+
31+
32+
class KBHit:
33+
34+
def __init__(self):
35+
'''Creates a KBHit object that you can call to do various keyboard things.
36+
'''
37+
38+
if os.name == 'nt':
39+
pass
40+
41+
else:
42+
43+
# Save the terminal settings
44+
self.fd = sys.stdin.fileno()
45+
self.new_term = termios.tcgetattr(self.fd)
46+
self.old_term = termios.tcgetattr(self.fd)
47+
48+
# New terminal setting unbuffered
49+
self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
50+
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)
51+
52+
# Support normal-terminal reset at exit
53+
atexit.register(self.set_normal_term)
54+
55+
56+
def set_normal_term(self):
57+
''' Resets to normal terminal. On Windows this is a no-op.
58+
'''
59+
60+
if os.name == 'nt':
61+
pass
62+
63+
else:
64+
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
65+
66+
67+
def getch(self):
68+
''' Returns a keyboard character after kbhit() has been called.
69+
Should not be called in the same program as getarrow().
70+
'''
71+
72+
s = ''
73+
74+
if os.name == 'nt':
75+
try:
76+
return msvcrt.getch().decode('utf-8')
77+
except UnicodeDecodeError:
78+
return ' '
79+
80+
else:
81+
return sys.stdin.read(1)
82+
83+
84+
def getarrow(self):
85+
''' Returns an arrow-key code after kbhit() has been called. Codes are
86+
0 : up
87+
1 : right
88+
2 : down
89+
3 : left
90+
Should not be called in the same program as getch().
91+
'''
92+
93+
if os.name == 'nt':
94+
msvcrt.getch() # skip 0xE0
95+
c = msvcrt.getch()
96+
vals = [72, 77, 80, 75]
97+
98+
else:
99+
c = sys.stdin.read(3)[2]
100+
vals = [65, 67, 66, 68]
101+
102+
return vals.index(ord(c.decode('utf-8')))
103+
104+
105+
def kbhit(self):
106+
''' Returns True if keyboard character was hit, False otherwise.
107+
'''
108+
if os.name == 'nt':
109+
return msvcrt.kbhit()
110+
111+
else:
112+
dr,dw,de = select([sys.stdin], [], [], 0)
113+
return dr != []
114+
115+
116+
if __name__ == "__main__":
117+
118+
kb = KBHit()
119+
120+
print('Hit any key, or ESC to exit')
121+
x=1
122+
while True:
123+
x+=1
124+
#print (x)
125+
if kb.kbhit():
126+
c = kb.getch()
127+
if ord(c) == 27: # ESC
128+
break
129+
print(c)
130+
131+
kb.set_normal_term()

‎ConsoleSnake/main.py

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
# -*- coding: UTF-8 -*-
2+
import time
3+
import os
4+
from random import randint
5+
from getch import KBHit
6+
7+
8+
class Snake:
9+
10+
def __init__(self, x, y):
11+
self.parts = [[1, 1]]
12+
self.length = 1
13+
self.dir = 'd'
14+
self.skins = ['O']
15+
self.fruit = [randint(2, x), randint(2, y)]
16+
self.size = [x, y]
17+
self.print_in_coords()
18+
19+
def get_opposites(self):
20+
return {"w": "s", "s": "w", "d": "a", "a":"d"}
21+
22+
def set_skins(self):
23+
"""
24+
This iterates each snake part, and based where the adjacent ones are,
25+
it gives it a skin between the following: │ ─ └ ┐ ┌ ┘
26+
27+
"""
28+
skins = ['O']
29+
coords_subtraction = lambda a, b: [x1 - x2 for (x1, x2) in zip(a, b)]
30+
for i in range(1, len(self.parts)):
31+
if i == len(self.parts)-1:
32+
a = self.parts[-2]
33+
b = self.parts[-1]
34+
else:
35+
b = self.parts[i+1]
36+
a = self.parts[i-1]
37+
diff = coords_subtraction(a, b)
38+
if diff[0] == 0:
39+
skins.append('│')
40+
elif diff[1] == 0:
41+
skins.append('─')
42+
else:
43+
a = self.parts[i-1]
44+
b = self.parts[i]
45+
diff2 = coords_subtraction(a, b)
46+
if sum(diff) == 0:
47+
if sum(diff2) == 1:
48+
skins.append('└')
49+
else:
50+
skins.append('┐')
51+
else:
52+
if diff2[1] == -1 or diff2[0] == 1:
53+
skins.append('┌')
54+
else:
55+
skins.append('┘')
56+
57+
self.skins = skins
58+
59+
def print_in_coords(self):
60+
"""
61+
Prints the field of game with '·',
62+
prints the snake body parts,
63+
prints the fruit ('X')
64+
"""
65+
coords = self.parts
66+
os.system('cls' if os.name == 'nt' else 'clear')
67+
for i in range(self.size[1], 0, -1):
68+
for j in range(1, self.size[0]+1):
69+
if [j, i] in coords:
70+
print(self.skins[coords.index([j, i])], end=' ')
71+
elif [j, i] == self.fruit:
72+
print('X', end=' ')
73+
else:
74+
print('·', end=' ')
75+
print('')
76+
77+
def update_coors(self):
78+
"""
79+
Makes every part of the snake move to where the following was,
80+
except the head, that moves to the direction the user input
81+
"""
82+
83+
for i in range(len(self.parts)-1, 0, -1):
84+
self.parts[i] = self.parts[i-1][:]
85+
86+
if self.dir == 'w':
87+
self.parts[0][1] += 1
88+
elif self.dir == 'd':
89+
self.parts[0][0] += 1
90+
elif self.dir == 's':
91+
self.parts[0][1] -= 1
92+
elif self.dir == 'a':
93+
self.parts[0][0] -= 1
94+
95+
def check_fruit(self):
96+
"""
97+
Checks if the snake's head is in the same place as the fruit,
98+
if so, the snake grows and another fruit is spawned
99+
"""
100+
if self.parts[0] == self.fruit:
101+
self.grow()
102+
self.generate_fruit()
103+
104+
def alive(self):
105+
"""
106+
Check if the head hit a body part or has crossed the limits
107+
"""
108+
head = self.parts[0]
109+
if (head in self.parts[1:]) or (not(0 < head[0] <= self.size[0])) or (not(0 < head[1] <= self.size[1])):
110+
return False
111+
return True
112+
113+
def get_action(self, character):
114+
if (character in 'wasd') and (self.get_opposites()[character] != self.dir or len(self.parts) == 1):
115+
self.dir = character
116+
self.update_coors()
117+
self.check_fruit()
118+
self.set_skins()
119+
self.print_in_coords()
120+
return self.alive()
121+
122+
def generate_fruit(self):
123+
new_coords = [randint(1,self.size[0]), randint(1,self.size[1])]
124+
if new_coords in self.parts:
125+
self.generate_fruit()
126+
else:
127+
self.fruit = new_coords
128+
129+
def grow(self):
130+
if len(self.parts) > 1:
131+
last = self.parts[-1]
132+
sec_last = self.parts[-2]
133+
diff = [x1 - x2 for (x1, x2) in zip(sec_last, last)]
134+
if diff[0] == 0:
135+
if diff[1] > 0:
136+
self.parts.append([last[0], last[1]-1])
137+
else:
138+
self.parts.append([last[0], last[1]+1])
139+
elif diff[0] > 0:
140+
self.parts.append([last[0]-1, last[1]])
141+
else:
142+
self.parts.append([last[0]+1, last[1]])
143+
else:
144+
head = self.parts[0]
145+
if self.dir == 'w':
146+
self.parts.append([head[0], head[1]-1])
147+
elif self.dir == 'd':
148+
self.parts.append([head[0]-1, head[1]])
149+
elif self.dir == 's':
150+
self.parts.append([head[0], head[1]+1])
151+
elif self.dir == 'a':
152+
self.parts.append([head[0]+1, head[1]])
153+
self.length += 1
154+
155+
156+
def main():
157+
snake = Snake(15, 10) # This means the game field is 15x10
158+
update_time = .125 # This is how much time there is between updates, 1/update_time = fps
159+
keep_playing = True
160+
kb = KBHit()
161+
while keep_playing:
162+
t = 0
163+
key_stroke = ' '
164+
while t < update_time:
165+
start = time.time()
166+
if kb.kbhit():
167+
key_stroke = kb.getch()
168+
end = time.time()
169+
t += end - start
170+
171+
keep_playing = snake.get_action(key_stroke)
172+
if snake.size[0] * snake.size[1] <= snake.length:
173+
print('You win!')
174+
break
175+
kb.set_normal_term()
176+
print('Score:', snake.length)
177+
while True:
178+
again = input('Keep playing? (y/n) ')
179+
if again.lower() == 'y':
180+
main()
181+
break
182+
elif again.lower() == 'n':
183+
print('Bye')
184+
break
185+
else:
186+
print('Input a valid answer')
187+
188+
if __name__ == "__main__":
189+
main()

0 commit comments

Comments
 (0)
Please sign in to comment.