-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInteractiveFlappies.py
251 lines (218 loc) · 8.58 KB
/
InteractiveFlappies.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import pygame
import pygame_menu
import os
import configparser
import sqlite3
from datetime import date
pygame.font.init()
pygame.get_init()
configParser = configparser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), 'game.cfg')
configParser.read(configFilePath)
# Game-Speed and difficulty in a sense
VELOCITY = configParser.getint("difficulty", "VELOCITY")
PIPE_DISTANCE = configParser.getint("difficulty", "PIPE_DISTANCE")
PIPE_GAP = configParser.getint("difficulty", "PIPE_GAP")
WIN_WIDTH = configParser.getint("window", "WIN_WIDTH")
WIN_HEIGHT = configParser.getint("window", "WIN_HEIGHT")
BIRD_IMGS = [pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird1.png"))),
pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird2.png"))),
pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird3.png")))]
PIPE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "pipe.png")))
BASE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "base.png")))
BG_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bg.png")))
STAT_FONT = pygame.font.SysFont("comicsans", 50)
difficulty = 1
name = "Anonymous"
def end_game(win, score: int, user_name: str):
def render_multi_line(text, x, y, fsize):
lines = text.splitlines()
for i, l in enumerate(lines):
win.blit(STAT_FONT.render(l, 1, (255, 255, 255)), (x, y + fsize * i))
got_highscore = write_leaderboard(score=score, write_name=user_name, difficulty_int=difficulty)
win.blit(BG_IMG, (0, 0))
text = "Game ended\nYou scored: {}\n".format(score)
if got_highscore:
text += "That's good!\n"
text += "\nPress Escape\n (end)\n or return\n (menu)"
render_multi_line(text, 100, 200, 50)
pygame.display.update()
clock = pygame.time.Clock()
ending = True
while ending:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
ending = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: # End game
ending = False
if event.key == pygame.K_RETURN: # return to menu
begin_game(win)
ending = False # Needed to close menu if upper-right x is pressed. Without the menu freezes.
pygame.quit()
quit()
def begin_game(surface):
global difficulty
global name
def set_difficulty(value, my_difficulty):
global difficulty
difficulty = my_difficulty
def get_name(my_name):
global name
name = my_name
def start_the_game():
global difficulty
global name
with open("game_variables.transfer", 'w') as f:
f.write("Difficulty:{}\n".format(difficulty))
f.write("Name:{}\n".format(name))
menu.close()
def draw_bg():
surface.blit(BG_IMG, (0, 0))
def show_highscores():
global difficulty
if difficulty == 0:
mode = "normal"
elif difficulty == 1:
mode = "easy"
elif difficulty == 2:
mode = "hard"
else:
raise ValueError
highscores = show_leaderboard(difficulty_int=difficulty)
leaders = pygame_menu.Menu('Leaderboard', 450, 700, theme=pygame_menu.themes.THEME_DEFAULT,
onclose=pygame_menu.events.BACK)
leaders.add.label("Mode: "+mode)
leader_table = leaders.add.table()
leader_table.default_cell_padding = 5
leader_table.shadow()
for scores in highscores:
leader_table.add_row(scores)
leaders.add.button("Back", pygame_menu.events.BACK)
leaders.mainloop(surface, bgfun=draw_bg)
menu = pygame_menu.Menu('Welcome', 400, 400,
theme=pygame_menu.themes.THEME_BLUE, onclose=pygame_menu.events.BACK)
menu.add.text_input('Name :', default=name, onchange=get_name)
menu.add.selector('Difficulty :', [('Easy', 1), ('Normal', 0), ('Hard', 2)], onchange=set_difficulty, style='fancy')
menu.add.button('Play', start_the_game)
menu.add.button('Highscores', show_highscores)
menu.add.button('Quit', pygame_menu.events.EXIT)
menu.mainloop(surface, bgfun=draw_bg)
def create_db(db_path: str) -> int:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE scores_easy (
score INTEGER,
name TEXT,
date TEXT
)""")
cursor.execute("""CREATE TABLE scores_normal (
score INTEGER,
name TEXT,
date TEXT
)""")
cursor.execute("""CREATE TABLE scores_hard (
score INTEGER,
name TEXT,
date TEXT
)""")
conn.commit()
cursor.close()
conn.close()
return 0
def write_leaderboard(score: int, write_name: str, difficulty_int: int) -> bool:
if difficulty_int == 0:
mode = "normal"
elif difficulty_int == 1:
mode = "easy"
elif difficulty_int == 2:
mode = "hard"
else:
raise ValueError
db_path = os.path.join(os.path.dirname(__file__), 'leaderboard.db')
if not os.path.isfile(db_path): # If database is missing, create new
create_db(db_path)
today = date.today().strftime('%d %m %Y')
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
if mode == "easy":
cursor.execute("SELECT * FROM scores_easy ORDER BY score ASC")
elif mode == "normal":
cursor.execute("SELECT * FROM scores_normal ORDER BY score ASC")
elif mode == "hard":
cursor.execute("SELECT * FROM scores_hard ORDER BY score ASC")
tops = cursor.fetchall()
empty_places = len(tops) < 10
is_leader = False
for _, leader in enumerate(tops):
if score > leader[0]:
is_leader = True
else:
break
if empty_places: # If there are less than 10 entries, automatically add score
is_leader = True
if is_leader:
# Remove last and insert here
if not empty_places:
if mode == "easy":
cursor.execute("DELETE FROM scores_easy WHERE score = (SELECT MIN(score) FROM scores_easy);")
elif mode == "normal":
cursor.execute("DELETE FROM scores_normal WHERE score = (SELECT MIN(score) FROM scores_normal);")
elif mode == "hard":
cursor.execute("DELETE FROM scores_hard WHERE score = (SELECT MIN(score) FROM scores_hard});")
if mode == "easy":
cursor.execute("INSERT INTO scores_easy VALUES (?, ?, ?)", (score, write_name, today))
elif mode == "normal":
cursor.execute("INSERT INTO scores_normal VALUES (?, ?, ?)", (score, write_name, today))
elif mode == "hard":
cursor.execute("INSERT INTO scores_hard VALUES (?, ?, ?)", (score, write_name, today))
conn.commit()
cursor.close()
conn.close()
return is_leader
def clear_leaderboard() -> int:
print("Be careful!\nThis will delete ALL entries in the leaderboard.")
really = input("Are you really sure this is what you want? (yN) ")
if really == ("y" or "Y"):
print("Initializing deletion...")
db_path = os.path.join(os.path.dirname(__file__), 'leaderboard.db')
if not os.path.isfile(db_path): # If database is missing, create new
create_db(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("DELETE FROM scores_easy")
cursor.execute("DELETE FROM scores_normal")
cursor.execute("DELETE FROM scores_hard")
conn.commit()
cursor.close()
conn.close()
return 0
else:
print("Noting deleted")
return 1
def show_leaderboard(difficulty_int: int) -> list:
if difficulty_int == 0:
mode = "normal"
elif difficulty_int == 1:
mode = "easy"
elif difficulty_int == 2:
mode = "hard"
else:
raise ValueError
db_path = os.path.join(os.path.dirname(__file__), 'leaderboard.db')
if not os.path.isfile(db_path): # If database is missing, create new
create_db(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
if mode == "easy":
cursor.execute("SELECT * FROM scores_easy ORDER BY score DESC")
elif mode == "easy":
cursor.execute("SELECT * FROM scores_normal ORDER BY score DESC")
elif mode == "easy":
cursor.execute("SELECT * FROM scores_hard ORDER BY score DESC")
tops = cursor.fetchall()
conn.close()
return tops
if __name__ == '__main__':
clear_leaderboard()