Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
92 lines (77 loc) · 2.21 KB
/
Copy pathmain.py
File metadata and controls
92 lines (77 loc) · 2.21 KB
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
import curses
import psycopg2
import os
import time
from dotenv import load_dotenv
def get_connection():
load_dotenv("db.env")
try:
return psycopg2.connect(
host=os.getenv("DB_HOST"),
port=os.getenv("DB_PORT"),
database=os.getenv("DB_NAME"),
user=os.getenv("DB_USER"),
password=os.getenv("DB_PASSWORD")
)
except psycopg2.OperationalError as e:
print(f"Error connecting to database: {e}")
exit(1)
conn = get_connection()
cur = conn.cursor()
def set_direction(direction):
cur.execute("UPDATE game_state SET direction = %s", (direction,))
conn.commit()
def tick():
cur.execute("CALL tick()")
conn.commit()
def get_grid():
cur.execute("SELECT linha FROM game_view")
return cur.fetchall()
def is_game_over():
cur.execute("SELECT game_over FROM game_state")
return cur.fetchone()[0]
def get_score():
cur.execute("SELECT score FROM game_state")
return cur.fetchone()[0]
def game(stdscr):
curses.curs_set(0)
stdscr.nodelay(True)
stdscr.timeout(150)
# initialize game
cur.execute("CALL init_game()")
conn.commit()
while True:
# 1. capture key and update direction
key = stdscr.getch()
if key == curses.KEY_UP:
set_direction('UP')
elif key == curses.KEY_DOWN:
set_direction('DOWN')
elif key == curses.KEY_LEFT:
set_direction('LEFT')
elif key == curses.KEY_RIGHT:
set_direction('RIGHT')
# 2. advance game state
tick()
# 3. render grid
stdscr.clear()
for i, row in enumerate(get_grid()):
try:
stdscr.addstr(i, 0, row[0])
except curses.error:
pass
# 4. check game over
if is_game_over():
try:
stdscr.addstr(21, 0, f"Game Over! Score: {get_score()} - press any key")
stdscr.refresh()
except curses.error:
pass
time.sleep(2)
stdscr.nodelay(False)
stdscr.getch()
break
# close connection
cur.close()
conn.close()
curses.wrapper(game)