Demo entry 6637665

Snake

   

Submitted by anonymous on Sep 04, 2017 at 23:17
Language: Python 3. Code size: 5.2 kB.

from getch import getch, pause																																													# Ayy
from curses import KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT
import sys, msvcrt
import math
import random
import curses
import time
import MySQLdb

stdscr = curses.initscr()
curses.start_color()

curses.echo()
curses.cbreak()
curses.curs_set(False)

curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_WHITE)

ascii_art_1 = """\
8888888b.           
888   Y88b          
888    888          
888   d88P 888  888 
8888888P"  888  888 
888        888  888 
888        Y88b 888 
888         "Y88888 
                888 
           Y8b d88P 
            "Y88P"                                                                                                                    
"""

ascii_art_2 = """\
 .d8888b.  888b    888        d8888 888    d8P  8888888888 
d88P  Y88b 8888b   888       d88888 888   d8P   888        
Y88b.      88888b  888      d88P888 888  d8P    888        
 "Y888b.   888Y88b 888     d88P 888 888d88K     8888888    
    "Y88b. 888 Y88b888    d88P  888 8888888b    888        
      "888 888  Y88888   d88P   888 888  Y88b   888        
Y88b  d88P 888   Y8888  d8888888888 888   Y88b  888        
 "Y8888P"  888    Y888 d88P     888 888    Y88b 8888888888                                                                                                                                                                              
"""

for y, line_2 in enumerate(ascii_art_2.splitlines(), 2):
	stdscr.addstr(y, 21, line_2)
	stdscr.refresh()
for y, line in enumerate(ascii_art_1.splitlines(), 2):
	stdscr.addstr(y, 1, line, curses.color_pair(1))
	stdscr.refresh()

key = KEY_DOWN

# Declaring var
height = 20
width = 30
begin_x = 25
begin_y = 0
game_win = curses.newwin(height, width, begin_y, begin_x)
game_win.keypad(True)
game_win.nodelay(1)
game_win.border()

begin_x_score = 0
begin_y_score = 20
height_score = 5
width_score = 80
score_win = curses.newwin(height_score, width_score, begin_y_score, begin_x_score)

velocity = 150  # Velocity (sec)
snake = [[10, 7], [10, 6], [10, 5]]

food = [[random.randint(1, height - 2), random.randint(1, width - 2)]]  # Food initial coor

score = 0

try:
	db = MySQLdb.connect("localhost", "root", "Testpass", "snake")
except MySQLdb.Error as e:
	score_win.addstr(1, 1, str(e))
	score_win.refresh()
	time.sleep(2)
	sys.exit()

cursor = db.cursor()

while (True):

	score_win.addstr(1, 1, 'Press 1 to start to play, instead, press 2 to check the leaderboard')
	user_input = score_win.getstr(2, 1).decode(encoding="utf-8")

	if (str(user_input) == '1'):
		break
	elif (str(user_input) == '2'):
		sql = "SELECT username, score FROM leaderboard ORDER BY score DESC LIMIT 10"
		cursor.execute(sql)
		stdscr.erase()
		stdscr.addstr(2, 1, 'LEADERBOARD', curses.color_pair(3))
		for i, row in enumerate(cursor.fetchall()):
			stdscr.addstr(i + 4, 2, str(i + 1) + '. ' + row[0] + ': ' + str(row[1]) + 'pt')
		stdscr.refresh()

	score_win.erase()
	score_win.refresh()

stdscr.erase()
stdscr.refresh()

for i, el in enumerate(snake):  # Initializing snake
	game_win.addch(snake[i][0], snake[i][1], '0')

game_win.addch(food[0][0], food[0][1], 'X', curses.color_pair(1))

while key != 27:

	i = 1

	score_win.addstr(1, 25, 'Score: ' + str(score))
	score_win.addstr(2, 25, 'Velocity: ' + str(velocity) + ' ')

	game_win.timeout(velocity)

	prev_key = key
	key_pressed = game_win.getch()
	key = key_pressed if key_pressed != -1 else prev_key

	snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1),
									 snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)])
	game_win.addch(snake[-1][0], snake[-1][1], ' ')

	if (snake[0] == food[0]):
		food[0][0] = random.randint(1, height - 2);
		food[0][1] = random.randint(1, width - 2)
		if velocity > 1: velocity -= int(math.ceil((velocity * 10) / 100))
		score += 10
	else:
		del snake[-1]

	while (i < len(snake)):
		if (snake[0] == snake[i]):
			key = 27
		i += 1

	if snake[0][0] == height - 1: snake[0][0] = 1
	if snake[0][0] == 0: snake[0][0] = height - 2
	if snake[0][1] == width - 1: snake[0][1] = 1
	if snake[0][1] == 0: snake[0][1] = width - 2

	game_win.addch(snake[0][0], snake[0][1], '0')
	game_win.addch(food[0][0], food[0][1], 'X', curses.color_pair(1))

	score_win.refresh()
	game_win.refresh()

score_win.erase()

score_win.addstr(1, 35, 'You lost :(', curses.color_pair(2))
score_win.addstr(2, 33, 'Your username: ', curses.color_pair(2))
username = score_win.getstr(3, 35).decode(encoding="utf-8")
username = username.strip()
if ((username.replace(" ", "")) == ""):
	username = 'AAA'
score_win.refresh()

sql = "INSERT INTO leaderboard(username, score) VALUES ('%s', '%d')" % (username, score)
cursor.execute(sql)
db.commit()

time.sleep(2)

game_win.erase()
score_win.erase()

# End of the program
db.close()
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).