-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspaceship.py
126 lines (97 loc) · 2.62 KB
/
spaceship.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import time
import random
from threading import Event, Thread
from pynput import keyboard
from pathlib import Path
FPS = 30
DELAY = 1.0 / FPS
WIDTH = 16
PLAYER_POS = 3
MAX_SPEED = 1
FRICTION_CONST = 0.8
SPACESHIP = '🚀'
VOID_CHAR = '. '
FIREWORK_CHAR = '🎆'
SPARKLE_CHAR = '✨'
world = [VOID_CHAR] * WIDTH
foreground = [VOID_CHAR] * WIDTH
background = [None] * WIDTH
velocity = 0.0
total_km = 0.0
c = 0
new_press = Event()
pressed = False
debug_text = None
data_file = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "game_data.txt"
def load_km():
try:
with open(data_file, "r") as file:
return float(file.read().strip())
except (FileNotFoundError, ValueError):
return 0.0
def save_km(km):
data_file.parent.mkdir(parents=True, exist_ok=True)
with open(data_file, "w") as file:
file.write(f"{km:.2f}")
def render():
print(f"Total km: {total_km:.2f} ", end="")
global c
local_world = [x for x in foreground]
local_world[PLAYER_POS] = SPACESHIP
if velocity > 0.9:
local_world[PLAYER_POS-1] = FIREWORK_CHAR
if c % 3 == 0 or c % 2 == 0:
local_world[PLAYER_POS-2] = FIREWORK_CHAR
c += 1
print(''.join(local_world[:-1]))
if debug_text: print(f"DEBUG: {debug_text}")
def on_release(key):
global pressed
new_press.set()
pressed = True
def run():
global velocity, total_km, pressed
ax = 0.0
counter = 0.0
total_km = load_km()
listener = Thread(target=lambda: keyboard.Listener(on_release=on_release).start())
listener.daemon = True
listener.start()
render()
while True:
n_evts = 0
if pressed:
n_evts += 1
pressed = False
elif n_evts > 0:
n_evts -= 1
if n_evts > 0:
ax += 0.02
elif velocity > 0:
ax -= 0.005
elif velocity <= 0:
ax = 0
velocity = 0
velocity += ax - velocity * FRICTION_CONST
velocity = min(velocity, MAX_SPEED)
if velocity == 0:
new_press.wait(DELAY)
new_press.clear()
continue
counter += velocity
if counter >= 1:
foreground.pop(0)
if random.randint(0, 5) == 1:
foreground.append(SPARKLE_CHAR)
else:
foreground.append(VOID_CHAR)
counter -= 1
total_km += 0.01
save_km(total_km)
render()
time.sleep(max(0, DELAY - (time.time() % DELAY)))
if __name__ == "__main__":
run()