Fixing score updation + introducing 4 more tables

This commit is contained in:
adithyagenie 2022-11-26 23:39:00 +05:30
parent 0bfe0cf4f3
commit 25a87ae61c
6 changed files with 66 additions and 51 deletions

View file

@ -56,7 +56,7 @@ def databaseinit(): # Creates database if it doesn't exist
tempcon = tempsql.cursor() tempcon = tempsql.cursor()
tempcon.execute("CREATE DATABASE IF NOT EXISTS labyrinth") tempcon.execute("CREATE DATABASE IF NOT EXISTS labyrinth")
tempsql.commit() tempsql.commit()
tempcon.close()
global sql, con global sql, con
sql = mysql.connector.connect( sql = mysql.connector.connect(
host="localhost", host="localhost",
@ -85,16 +85,17 @@ def tableinit():
password VARCHAR(32) NOT NULL\ password VARCHAR(32) NOT NULL\
) " ) "
) )
for i in ["maze_scores", "pong_scores", "snake_scores", "wordle_scores"]:
post( post(
"CREATE TABLE IF NOT EXISTS scores\ f"CREATE TABLE IF NOT EXISTS {i}\
(\ (\
gamerid CHAR(4) PRIMARY KEY,\ gamerid CHAR(4) PRIMARY KEY,\
highscore INT,\ highscore INT,\
lastplayed DATE,\ lastscore INT,\
timesplayed INT\ lastplayed DATE,\
) " timesplayed INT\
) ) "
)
except Exception as e: except Exception as e:
print(e) print(e)
print("ERROR: Creating Table(s)") print("ERROR: Creating Table(s)")
@ -257,7 +258,7 @@ def login(screen, calledby=None): # Function to log in
screen.addstr(y // 2 + 3, x // 2 - 4, "Updating score...") screen.addstr(y // 2 + 3, x // 2 - 4, "Updating score...")
screen.refresh() screen.refresh()
sleep(3) sleep(3)
Update_score(calledby) Update_score(calledby[0], calledby[1])
return return
else: else:
screen.addstr(y // 2 + 3, x // 2 - 4, "Returning to menu screen...") screen.addstr(y // 2 + 3, x // 2 - 4, "Returning to menu screen...")
@ -514,12 +515,14 @@ def modify_account(screen):
def view_account(screen): def view_account(screen):
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
global loggedin, U, gamerid global loggedin, U, gamerid
y, x = screen.getmaxyx() y, x = screen.getmaxyx()
screen.clear() screen.clear()
screen.refresh() screen.refresh()
screen.border() screen.border()
screen.addstr(1, x // 2 - 6, "VIEW ACCOUNT DETAILS") screen.addstr(1, x // 2 - 9, "VIEW ACCOUNT DETAILS")
if not loggedin: if not loggedin:
screen.addstr( screen.addstr(
y // 2, y // 2,
@ -532,18 +535,22 @@ def view_account(screen):
return return
player_details = get( player_details = get(
f"SELECT *\ f"SELECT *\
FROM player_details\ FROM player_details\
WHERE gamerid = '{gamerid}' " WHERE gamerid = '{gamerid}' "
) )
score_details = get(f"SELECT * FROM scores WHERE gamerid = '{gamerid}'") screen.addstr(3, x // 2 - 7, "Gamer ID: " + player_details[0][0])
screen.addstr(y // 2 - 4, x // 2 - 5, "Gamer ID: " + player_details[0][0]) screen.addstr(5, x // 2 - 8, "Username: " + player_details[0][1])
screen.addstr(y // 2 - 2, x // 2 - 5, "Username: " + player_details[0][1]) screen.addstr(7, x// 2 - 9, "Email: " + player_details[0][2])
screen.addstr(y // 2, x // 2 - 5, "Email: " + player_details[0][2]) j = 0
if not score_details: for i, tablename in enumerate(["maze_scores", "pong_scores", "snake_scores", "wordle_scores"]):
score_details.append(("Bruh",) + ("Not yet available.",) * 3) score_details = get(f"SELECT * FROM {tablename} WHERE gamerid = '{gamerid}'")
screen.addstr(y // 2 + 2, x // 2 - 5, "High Score: " + str(score_details[0][1])) if not score_details:
screen.addstr(y // 2 + 4, x // 2 - 5, "Last Played: " + str(score_details[0][2])) score_details.append(("Bruh",) + ("Not yet available.",) * 3)
screen.addstr(y // 2 + 6, x // 2 - 5, "Times Played: " + str(score_details[0][3])) screen.addstr(8 + 3 * i + j + 1, x // 2 - 15, f"{tablename.split('_')[0].capitalize()}: ", curses.color_pair(3))
screen.addstr(8 + 3 * i + 1 + j, x // 2 - 7, "High Score: " + str(score_details[0][1]), curses.color_pair(2))
screen.addstr(9 + 3 * i + 1 + j, x // 2 - 7, "Last Played: " + str(score_details[0][2]))
screen.addstr(10 + 3 * i + 1 + j, x // 2 - 7, "Times Played: " + str(score_details[0][3]))
j += 1
screen.addstr(y - 1, 5, "Press esc to return to main menu.") screen.addstr(y - 1, 5, "Press esc to return to main menu.")
while True: while True:
@ -596,28 +603,38 @@ def delete(screen):
return return
def Update_score(Score): def Update_score(score, game):
tablename = game + '_scores'
global U, gamerid, loggedin global U, gamerid, loggedin
if not loggedin: if not loggedin:
return "guest" return "guest"
res = get(f"SELECT * FROM scores WHERE gamerid = '{gamerid}'") res = get(f"SELECT * FROM {tablename} WHERE gamerid = '{gamerid}'")
if not res: if not res:
post(f"INSERT INTO scores (gamerid, timesplayed) VALUES ('{gamerid}', 0)") post(f"INSERT INTO {tablename} (gamerid, highscore, lastscore, timesplayed) VALUES ('{gamerid}',0, 0, 0)")
res = get(f"SELECT * FROM {tablename} WHERE gamerid = '{gamerid}'")
# implement to ask whether to update # implement to ask whether to update
post( if res[0][1] < score:
f"UPDATE scores\ post(
SET highscore = '{Score}'\ f"UPDATE {tablename}\
WHERE gamerid = '{gamerid}'" SET highscore = '{score}',\
) lastscore = {score}\
Update_lp_tp() WHERE gamerid = '{gamerid}'"
)
else:
post(
f"UPDATE {tablename}\
SET lastscore = '{score}'\
WHERE gamerid = '{gamerid}'"
)
Update_lp_tp(tablename)
def Update_lp_tp(): def Update_lp_tp(tablename):
global U, gamerid, loggedin global U, gamerid, loggedin
if not loggedin: if not loggedin:
return "guest" return "guest"
post( post(
f"UPDATE scores\ f"UPDATE {tablename}\
SET lastplayed = Now(),\ SET lastplayed = Now(),\
timesplayed = timesplayed + 1\ timesplayed = timesplayed + 1\
WHERE gamerid = '{gamerid}'" WHERE gamerid = '{gamerid}'"

View file

@ -475,16 +475,17 @@ def play(
loadedtime=0, loadedtime=0,
executeguest=False, executeguest=False,
outerscore=0, outerscore=0,
outergame=False
): ):
y, x = screen.getmaxyx() y, x = screen.getmaxyx()
height, width = int((y - 2) / 2), int((x - 2) / 2) height, width = int((y - 2) / 2), int((x - 2) / 2)
def guestswitch(score): def guestswitch(score, game):
screen.clear() screen.clear()
screen.refresh() screen.refresh()
screen.border() screen.border()
screen.addstr(y // 2 - 5, x // 2 - 8, str("Your score is: " + str(int(score)))) screen.addstr(y // 2 - 5, x // 2 - 8, str("Your score is: " + str(int(score))))
res = database.Update_score(int(score)) res = database.Update_score(int(score), game)
if res == "guest": if res == "guest":
screen.addstr( screen.addstr(
height - 1, height - 1,
@ -497,7 +498,7 @@ def play(
while True: while True:
key = screen.getch() key = screen.getch()
if key == ord("y"): if key == ord("y"):
database.login(screen, calledby=int(score)) database.login(screen, calledby=(int(score), game))
break break
elif key == ord("n"): elif key == ord("n"):
break break
@ -507,7 +508,7 @@ def play(
return return
if executeguest: if executeguest:
guestswitch(outerscore) guestswitch(outerscore, outergame)
return return
screen.clear() screen.clear()
@ -549,7 +550,7 @@ def play(
else: else:
score = 0 score = 0
guestswitch(score) guestswitch(score, game="maze")
# res = database.Update_score(int(score)) # res = database.Update_score(int(score))
# if res == "guest": # if res == "guest":
# screen.addstr( # screen.addstr(

View file

@ -163,7 +163,7 @@ def ball_movement(screen, ball, score):
elif collision == "collision": elif collision == "collision":
score.scoreupdate() score.scoreupdate()
screen.addch(old_ball_posy, old_ball_posx, " ") screen.addch(old_ball_posy, old_ball_posx, " ")
screen.addch(ball_posy, ball_posx, "*") screen.addch(ball_posy, ball_posx, "", curses.color_pair(1))
screen.refresh() screen.refresh()
@ -176,6 +176,7 @@ def main(screen):
curses.curs_set(False) curses.curs_set(False)
screen.keypad(True) screen.keypad(True)
y, x = screen.getmaxyx() y, x = screen.getmaxyx()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
screen.border(0, 0, 0, " ", 0, 0, " ", " ") screen.border(0, 0, 0, " ", 0, 0, " ", " ")
ball = Ball(y, x, screen) ball = Ball(y, x, screen)
score = Scores(screen) score = Scores(screen)
@ -202,4 +203,4 @@ def main(screen):
ball_thread.start() ball_thread.start()
player_thread.run() player_thread.run()
time.sleep(1) time.sleep(1)
m1.play(screen, executeguest=True, outerscore=score.score) m1.play(screen, executeguest=True, outerscore=score.score, outergame="pong")

View file

@ -116,7 +116,7 @@ def main(stdscr):
while stdscr.getch() == -1: while stdscr.getch() == -1:
pass pass
time.sleep(2) time.sleep(2)
m.play(stdscr, executeguest=True, outerscore=score) m.play(stdscr, executeguest=True, outerscore=score, outergame="snake")
# Call play with guestcheck to update scores # Call play with guestcheck to update scores
stdscr.clear() stdscr.clear()
stdscr.refresh() stdscr.refresh()

View file

@ -4,7 +4,7 @@ import subprocess
import sys import sys
from maze.modules import bruh from maze.modules import bruh
from maze.modules.PlayerBase_func import databaseinit import maze.modules.PlayerBase_func as player
user = password = None user = password = None
@ -46,11 +46,12 @@ Run 'python starter.py initsql' to initialise credentials of your choice. """
if len(sys.argv) == 1: if len(sys.argv) == 1:
getcreds() getcreds()
bruh() bruh()
player.sql.close()
sys.exit() sys.exit()
else: else:
if sys.argv[1] == "dumpsample": if sys.argv[1] == "dumpsample":
getcreds() getcreds()
databaseinit() player.databaseinit()
subprocess.call( subprocess.call(
f"mysql -u {user} --password={password} -D labyrinth < {os.path.abspath('dbdump.sql')}", f"mysql -u {user} --password={password} -D labyrinth < {os.path.abspath('dbdump.sql')}",
shell=True # , shell=True # ,
@ -58,6 +59,7 @@ else:
# stderr=subprocess.DEVNULL, # stderr=subprocess.DEVNULL,
) )
print("Successfully dumped sample data") print("Successfully dumped sample data")
elif sys.argv[1] == "initsql": elif sys.argv[1] == "initsql":
user = input("Enter MySQL username: ") user = input("Enter MySQL username: ")
password = input("Enter MySQL password: ") password = input("Enter MySQL password: ")

View file

@ -1,6 +0,0 @@
# wordle-curses
A simple TUI wordle game with curses
![ezgif-7-16d0fbabbd](https://user-images.githubusercontent.com/30610197/151707991-824e3c54-9b69-449c-bc65-e500345d7877.gif)
Run `main.py` to play.