Root commit

This commit is contained in:
adithyagenie 2022-11-03 01:32:13 +05:30
commit 8fd89a3d5d
9 changed files with 1268 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
log.txt
maze.zip
PlayerBase_func.pybak
__pycache__
maze/__pycache__
maze/modules/__pycache__

BIN
credentials.pickle Normal file

Binary file not shown.

View file

@ -0,0 +1,713 @@
import mysql.connector
import os
import re
import curses
import maze.modules.maze
from .password_forget import sender
import random
import string
from time import sleep
from base64 import b64decode, b64encode
loggedin = False
U = gamerid = None
quitting = False
sql = con = None
def get(
query,
): # Simplifed function to fetch records from mysql instead of typing fetchall over nd over
con.execute(query)
r = con.fetchall()
return r
def post(
query,
): # Simplifed function to commit queries to mysql instead of typing this again and again
con.execute(query)
try:
sql.commit()
except:
print("ERROR OCCURED COMMITTING CHANGES")
def databaseinit(): # Creates database if it doesn't exist
try:
tempsql = mysql.connector.connect(host="localhost", user="root", passwd="root")
tempcon = tempsql.cursor()
tempcon.execute("CREATE DATABASE IF NOT EXISTS labyrinth")
tempsql.commit()
global sql, con
sql = mysql.connector.connect(
host="localhost", user="root", passwd="root", database="labyrinth"
)
con = sql.cursor()
return True
except (
mysql.connector.errors.ProgrammingError,
mysql.connector.errors.DatabaseError,
):
print("Invalid password/username.")
return False
def tableinit():
try:
post(
"CREATE TABLE IF NOT EXISTS player_details\
(\
gamerid CHAR(4) PRIMARY KEY,\
username VARCHAR(32) NOT NULL,\
email VARCHAR(32) NOT NULL,\
password VARCHAR(32) NOT NULL\
) "
)
post(
"CREATE TABLE IF NOT EXISTS scores\
(\
gamerid CHAR(4) PRIMARY KEY,\
highscore INT,\
lastplayed DATE,\
timesplayed INT\
) "
)
except Exception as e:
print(e)
print("ERROR: Creating Table(s)")
def screenhandler(screen): # MAIN MENU
h, w = screen.getmaxyx()
global loggedin, U, gamerid
screen.clear()
screen.refresh()
screen.addstr(1, w // 2 - 8, "ACCOUNT SETTINGS")
if loggedin:
screen.addstr(2, w // 2 - 8, f"Logged in as: {U}")
screen.addstr(h // 2 - 3, w // 2 - 4, "1. Login")
screen.addstr(h // 2 - 2, w // 2 - 8, "2. Create Account")
screen.addstr(h // 2 - 1, w // 2 - 12, "3. Modify account details")
screen.addstr(h // 2 - 0, w // 2 - 12, "4. View account details")
screen.addstr(h // 2 + 1, w // 2 - 8, "5. Delete Account")
screen.addstr(h // 2 + 2, w // 2 - 9, "6. Forgot Password?")
screen.addstr(h // 2 + 3, w // 2 - 3, "esc. Quit")
screen.refresh()
while True:
key = screen.getch()
if key == ord("1"):
login(screen)
elif key == ord("2"):
new_add(screen)
elif key == ord("3"):
Mod_account(screen)
elif key == ord("4"):
view_account(screen)
elif key == ord("5"):
Delete(screen)
elif key == ord("6"):
forgotpassword(screen)
elif key == 27:
maze.modules.maze.menu(screen)
break
screen.refresh()
def screenwipe(screen, sx, sy): # Failed password and stuff reset from screen
y, x = screen.getmaxyx()
for i in range(sx, x):
screen.addstr(sy, i, " ")
for i in range(sy + 1, y - 1):
for j in range(0, x - 1):
if screen.instr(i, j, 1) != " ":
screen.addstr(i, j, " ")
screen.refresh()
def Input(
y, x, screen, ispassword=False
): # Function to get type-able inputs, with delete, esc and other keys
inputted = ""
orig_y, orig_x = y, x
while True:
key = screen.getch()
if key == 10:
break
elif key == 8:
if x > orig_x:
x -= 1
screen.addstr(y, x, " ")
inputted = inputted[: len(inputted) - 1]
elif key == 27:
global quitting
quitting = True
break
else:
inputted += chr(key)
if ispassword:
screen.addstr(y, x, "*")
else:
screen.addstr(y, x, chr(key))
x += 1
return inputted
def list_getter(field): # Feed in the field name you want, get all records of it
index = {"username": 1, "email": 2, "password": 3}
return_list = []
res = get("SELECT * FROM player_details")
for i in res:
return_list.append(i[index[field]])
return return_list
def login(screen, calledby=False): # Function to log in
global quitting, U, gamerid, loggedin
screen.clear()
screen.refresh()
y, x = screen.getmaxyx()
usernamelist = list_getter("username")
screen.addstr(1, x // 2 - 3, "LOGIN")
screen.addstr(y // 2 - 2, x // 2 - 7, "Username: ")
while True:
inputU = Input(y // 2 - 2, x // 2 + 3, screen)
if quitting:
screen.addstr("Going back to account settings...")
sleep(3)
quitting = False
screen.clear()
screen.refresh()
screenhandler(screen)
if inputU not in usernamelist:
screen.addstr(
y // 2, 0, "Username does not exist. Do you want to create one? (y/n)"
)
while True:
key = screen.getch()
if key == ord("y"):
if calledby:
new_add(screen, calledby=calledby)
else:
new_add(screen)
return
elif key == ord("n"):
screenwipe(screen, x // 2 + 3, y // 2 - 2)
break
else:
break
res = get(
f"SELECT password,\
gamerid\
FROM player_details\
WHERE username = '{inputU}' "
)
actualpass = (b64decode(res[0][0].encode("ascii"))).decode("ascii")
screen.addstr(y // 2, x // 2 - 7, "Password: ")
while True:
inputP = Input(y // 2, x // 2 + 3, screen, ispassword=True)
if quitting:
screen.addstr("Going back to account settings...")
sleep(3)
screen.clear()
screen.refresh()
screenhandler(screen)
if inputP == actualpass:
loggedin = True
gamerid = res[0][1]
U = inputU
screen.addstr(y // 2 + 2, x // 2 - 4, "Login Successful!")
if calledby:
screen.addstr(y // 2 + 3, x // 2 - 4, "Updating score...")
screen.refresh()
sleep(3)
Update_score(calledby)
return
else:
screen.addstr(y // 2 + 3, x // 2 - 4, "Returning to menu screen...")
screen.refresh()
sleep(3)
screenhandler(screen)
return
else:
screen.addstr(y // 2 + 2, x // 2 - 4, "Wrong password. Try again.")
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sx=x // 2 + 3, sy=y // 2)
screen.refresh()
break
continue
def user(
screen, sy, sx, optionaltxt="Enter username: "
): # Function to get new username for account creation
if quitting:
screen.clear()
screen.refresh()
return
screen.refresh()
userlist = list_getter("username")
screen.addstr(sy, sx, optionaltxt)
while True:
Name = Input(sy, sx + len(optionaltxt), screen)
if quitting:
screen.clear()
screen.refresh()
return
if Name in userlist:
screen.addstr(
sy + 1, 0, "Username already exists, please choose a different one"
)
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sx=sx + len(optionaltxt), sy=sy)
screen.refresh()
break
continue
else:
break
return Name
def password(screen, sy, sx, optionaltxt="Enter Password: "):
if quitting:
screen.clear()
screen.refresh()
return
sl, su, p = 0, 0, 0
screen.refresh()
while True:
screen.addstr(sy, sx, optionaltxt)
Password = Input(sy, sx + len(optionaltxt), screen, ispassword=True)
if quitting:
screen.clear()
screen.refresh()
return
for i in Password:
if i.islower():
sl += 1
elif i.isupper():
su += 1
elif i.isdigit():
p += 1
if sl >= 1 and su >= 1 and p >= 1 and len(Password) <= 10:
break
else:
screen.addstr(sy + 1, sx + 2, "Invalid Password")
screen.addstr(sy + 2, 5, "Password must contain uppercase, lowercase and")
screen.addstr(sy + 3, 5, "digits and should be lesser than 10 characters")
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sx=sx + len(optionaltxt), sy=sy)
screen.refresh()
break
continue
encoded_pass = (b64encode(Password.encode("ascii"))).decode("ascii")
return encoded_pass
def Email(screen, sy, sx, optionaltxt="Enter Email: "): # Function to accept email id
if quitting:
screen.clear()
screen.refresh()
return
ev = re.compile(r"[a-z0-9]+@[a-z]+\.[a-z]{2,3}")
emailist = list_getter("email")
y, x = screen.getmaxyx()
screen.refresh()
while True:
screen.addstr(sy, sx, optionaltxt)
email = Input(sy, sx + len(optionaltxt), screen)
if quitting:
screen.clear()
screen.refresh()
return
if email in emailist:
screen.addstr(
sy + 1, sx, "Given email already exists. Enter a different email."
)
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sx=sx + len(optionaltxt), sy=sy)
screen.refresh()
break
continue
else:
if ev.match(email):
break
else:
screen.addstr(y // 2 + 1, x // 2 - 5, "Invalid Email")
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sx=x // 2 + 3, sy=y // 2)
screen.refresh()
break
continue
return email
def new_add(screen, calledby=False):
screen.clear()
screen.refresh()
y, x = screen.getmaxyx()
global quitting
screen.addstr(1, x // 2 - 8, "ACCOUNT CREATION")
add_name = user(
screen, y // 2 - 4, x // 2 - 10
) # calling fn user for username, password and email
add_password = password(screen, y // 2 - 2, x // 2 - 10)
add_email = Email(screen, y // 2, x // 2 - 10)
add_gamerid = "".join(
random.choices(string.ascii_uppercase + string.digits, k=4)
) # Generates random 4 character alphanumeric
if add_name == None or add_password == None or add_email == None:
screen.refresh()
screen.addstr(
y // 2 + 2, 0, "Cancelling account creation. Returning to account menu..."
)
sleep(3)
screen.clear()
screen.refresh()
quitting = False
screenhandler(screen)
else:
post(
f"INSERT INTO player_details\
(gamerid,\
username,\
email,\
password)\
VALUES ('{add_gamerid}',\
'{add_name}',\
'{add_email}',\
'{add_password}')"
)
screen.refresh()
if calledby:
screen.addstr(
y // 2 + 2, 0, "Account has been created. Returning to login..."
)
screen.refresh()
sleep(3)
login(screen, calledby=calledby)
else:
screen.addstr(
y // 2 + 2, 0, "Account has been created. Returning to account menu..."
)
screen.refresh()
sleep(3)
screenhandler(screen)
def Mod_account(screen):
Userlist = list_getter("username")
screen.clear()
screen.refresh()
y, x = screen.getmaxyx()
global loggedin, quitting
screen.addstr(1, x // 2 - 8, "MODIFY ACCOUNT SETTINGS")
if loggedin == False:
screen.addstr(
y // 2,
0,
"Please log in to you account... Redirecting you to the login menu",
)
screen.refresh()
sleep(3)
login(screen)
return
screen.addstr(3, x // 2 - 8, "What do you want to modify?")
screen.addstr(y // 2 - 3, x // 2 - 4, "1. Username")
screen.addstr(y // 2 - 1, x // 2 - 4, "2. Email")
screen.addstr(y // 2 + 1, x // 2 - 4, "esc. Quit")
while True:
key = screen.getch()
if key == 27:
break
elif key == ord("1"):
screenwipe(screen, 0, 2)
screen.refresh()
newuser = user(
screen,
y // 2,
x // 2 - 10,
optionaltxt="Enter new username: ",
)
post(
f"UPDATE player_details\
SET username = '{newuser}'\
WHERE gamerid = '{gamerid}' "
)
elif key == ord("2"):
screenwipe(screen, 0, 2)
screen.refresh()
newemail = Email(
screen, y // 2, x // 2 - 10, optionaltxt="Enter new email: "
)
post(
f"UPDATE player_details\
SET email = '{newemail}'\
WHERE gamerid = '{gamerid}' "
)
screenwipe(screen, 0, 2)
screen.refresh()
screen.addstr(
y // 2, 5, "Details successfully updated. Returning to account menu..."
)
screen.refresh()
sleep(3)
screenhandler(screen)
def view_account(screen):
global loggedin, U, gamerid
y, x = screen.getmaxyx()
screen.clear()
screen.refresh()
screen.addstr(1, x // 2 - 6, "VIEW ACCOUNT DETAILS")
if not loggedin:
screen.addstr(
y // 2,
0,
"Please log in to you account... Redirecting you to the login menu",
)
screen.refresh()
sleep(3)
login(screen)
return
player_details = get(
f"SELECT *\
FROM player_details\
WHERE gamerid = '{gamerid}' "
)
score_details = get(f"SELECT * FROM scores WHERE gamerid = '{gamerid}'")
screen.addstr(y // 2 - 4, x // 2 - 5, "Gamer ID: " + player_details[0][0])
screen.addstr(y // 2 - 2, x // 2 - 5, "Username: " + player_details[0][1])
screen.addstr(y // 2, x // 2 - 5, "Email: " + player_details[0][2])
if not score_details:
score_details.append(("Bruh",) + ("Not yet available.",) * 3)
screen.addstr(y // 2 + 2, x // 2 - 5, "High Score: " + str(score_details[0][1]))
screen.addstr(y // 2 + 4, x // 2 - 5, "Last Played: " + str(score_details[0][2]))
screen.addstr(y // 2 + 6, x // 2 - 5, "Times Played: " + str(score_details[0][3]))
screen.addstr(y - 1, 0, "Press esc to return to main menu.")
while True:
key = screen.getch()
if key == 27:
break
screen.refresh()
screenhandler(screen)
return
def Delete(screen):
y, x = screen.getmaxyx()
global loggedin, gamerid, U
screen.clear()
screen.refresh()
if loggedin == False:
screen.addstr(
y // 2,
0,
"Please log in to you account... Redirecting you to the login menu",
)
screen.refresh()
sleep(3)
login(screen)
return
post(
f"DELETE FROM player_details\
WHERE gamerid = '{gamerid}'"
)
loggedin = False
gamerid = U = None
def Update_score(Score):
global U, gamerid, loggedin
if not loggedin:
return "guest"
res = get(f"SELECT * FROM scores WHERE gamerid = '{gamerid}'")
if not res:
post(f"INSERT INTO scores (gamerid, timesplayed) VALUES ('{gamerid}', 0)")
# implement to ask whether to update
post(
f"UPDATE scores\
SET highscore = '{Score}'\
WHERE gamerid = '{gamerid}'"
)
Update_lp_tp()
def Update_lp_tp():
global U, gamerid, loggedin
if not loggedin:
return "guest"
post(
f"UPDATE scores\
SET lastplayed = Now(),\
timesplayed = timesplayed + 1\
WHERE gamerid = '{gamerid}'"
)
def forgotpassword(screen):
screen.clear()
screen.refresh()
y, x = screen.getmaxyx()
screen.addstr(1, x // 2 - 7, "FORGOT PASSWORD")
screen.refresh()
global quitting
usernamelist = list_getter("username")
tries = 0
screen.addstr(y // 2 - 2, x // 2 - 7, "Username: ")
while True:
input_u = Input(y // 2 - 2, x // 2 + 3, screen)
if quitting:
screen.addstr("Going back to account settings...")
sleep(3)
quitting = False
screen.clear()
screen.refresh()
screenhandler(screen)
return
if input_u not in usernamelist:
screen.addstr(
y // 2 - 1, 0, "Username does not exist. Press Enter/Space to continue..."
)
while True:
key = screen.getch()
if key == ord(" ") or key == 10:
screenwipe(screen, sy = y // 2 - 2, sx = x // 2 + 3)
screen.refresh()
break
else:
break
res = get(f"SELECT email FROM player_details\
WHERE username = '{input_u}'")
email = res[0][0]
otp = sender(input_u, email)
screen.addstr(y // 2 + 1, 0, "Enter OTP recieved in registered mail address:")
while True:
screen.refresh()
enter_otp = Input(y // 2 + 1, 47, screen)
if quitting:
screen.addstr("Going back to account settings...")
sleep(3)
quitting = False
screen.clear()
screen.refresh()
screenhandler(screen)
return
if str(otp) == enter_otp:
screen.clear()
screen.refresh()
screen.addstr(1, x // 2 - 7, "FORGOT PASSWORD")
while True:
enter_pass = password(screen, y // 2 - 2, x // 2 - 7, optionaltxt="Enter new password: ")
confirm_pass = password(screen, y // 2 + 1, x // 2 - 7, optionaltxt="Confirm password: ")
if enter_pass == confirm_pass:
break
else:
screen.addstr(y // 2 + 3, 0, "Passwords do not match. Press Enter to try again.")
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sy= y // 2 - 2, sx = x // 2 - 7)
break
else:
if tries < 10:
screen.addstr(y // 2 + 3, 0, "Entered OTP is wrong. Press esc to exit or Enter to try again.")
while True:
key = screen.getch()
if key == 10:
screenwipe(screen, sy=y // 2 + 1, sx=47)
tries += 1
screen.refresh()
break
elif key == 27:
screen.clear()
screen.refresh()
screenhandler(screen)
return
continue
else:
screen.addstr(y // 2 + 3, 0, "Entered OTP is wrong. Maximum tries exceeded. Returning to account menu...")
sleep(5)
screen.clear()
screen.refresh()
screenhandler(screen)
return
break
post(f"UPDATE player_details\
SET password = '{enter_pass}'\
WHERE username = '{input_u}'")
screen.addstr(y // 2 + 3, x // 2 - 10, "Password has been changed successfully.")
screen.addstr(y // 2 + 4, x // 2 - 8, "Returning to account menu...")
sleep(3)
screenhandler(screen)
return
def leaderboard(screen):
y, x = screen.getmaxyx()
screen.clear()
screen.addstr(1, y // 2 - 5, "Leaderboard")
screen.refresh()
res = get(
"SELECT p.gamerid,\
p.username,\
s.highscore,\
s.lastplayed\
FROM player_details p,\
scores s\
WHERE p.gamerid = s.gamerid "
)
for i in range(len(res) - 1):
for j in range(len(res) - 1 - i):
if res[j][2] < res[j + 1][2]:
res[j], res[j + 1] = res[j + 1], res[j]
screen.addstr(3, 13, "GamerID")
screen.addstr(3, 30, "Username")
screen.addstr(3, 50, "High Score")
screen.addstr(3, 70, "Last Played")
sy = 5
for i in res:
screen.addstr(sy, 13, str(i[0]))
screen.addstr(sy, 30, str(i[1]))
screen.addstr(sy, 50, str(i[2]))
screen.addstr(sy, 70, str(i[3]))
sy += 1
screen.addstr(y - 1, 0, "Press esc to return to main menu.")
while True:
key = screen.getch()
if key == 27:
break
screen.refresh()
maze.modules.maze.menu(screen)
return

5
maze/modules/__init__.py Normal file
View file

@ -0,0 +1,5 @@
from maze.modules.maze import main
import curses
def bruh():
curses.wrapper(main)

1
maze/modules/__main__.py Normal file
View file

@ -0,0 +1 @@
#bruh

489
maze/modules/maze.py Normal file
View file

@ -0,0 +1,489 @@
import curses
import time
from math import exp, pi, cos, fabs
import random
from collections import defaultdict
from itertools import tee
import maze.modules.PlayerBase_func as database
WON = 0
CONNECTED = {"N": 1, "S": 2, "E": 4, "W": 8}
DIRECTIONS = {"N": (-1, 0), "S": (1, 0), "E": (0, 1), "W": (0, -1)}
ANTIPODES = {"N": "S", "S": "N", "W": "E", "E": "W"}
WALL = {
12: "",
3: "",
10: "",
5: "",
9: "",
6: "",
7: "",
11: "",
14: "",
13: "",
15: "",
0: " ",
4: "",
8: "",
1: "",
2: "",
}
VISITED = 16
class Maze:
def __init__(self, height, width, start=(0, 0)):
self.height = height
self.width = width
self.stack = []
self.cells = {(y, x): 0 for y in range(height) for x in range(width)}
self.build(start)
def eligible_neighbours(self, y, x):
return [
((y + i, x + j), d)
for d, (i, j) in DIRECTIONS.items()
if (y + i, x + j) in self.cells.keys()
and not self.cells[(y + i, x + j)] & VISITED
]
def connected_cells(self, y, x):
cell_directions = [d for (d, v) in CONNECTED.items() if v & self.cells[(y, x)]]
return {
(y + i, x + j): d
for d, (i, j) in DIRECTIONS.items()
if d in cell_directions
}
def build(self, start):
current_cell = start
while [c for c in self.cells.values() if not c & VISITED]:
self.cells[current_cell] |= VISITED
eligible_neighbours = self.eligible_neighbours(*current_cell)
if not eligible_neighbours:
next_cell = self.stack.pop()
else:
self.stack.append(current_cell)
next_cell, direction = random.choice(eligible_neighbours)
self.cells[current_cell] |= CONNECTED[direction]
self.cells[next_cell] |= CONNECTED[ANTIPODES[direction]]
current_cell = next_cell
def track(self, start=(0, 0)):
yield start
current_cell = start
self.stack = []
for coord in self.cells.keys():
self.cells[coord] &= ~VISITED
while [c for c in self.cells.values() if not c & VISITED]:
self.cells[current_cell] |= VISITED
eligible_neighbours = [
(c, d)
for (c, d) in self.connected_cells(*current_cell).items()
if not self.cells[c] & VISITED
]
if not eligible_neighbours:
next_cell = self.stack.pop()
else:
self.stack.append(current_cell)
next_cell, direction = random.choice(eligible_neighbours)
yield next_cell
current_cell = next_cell
def __repr__(self):
log = open("log.txt", "w")
log.write(
str(self.cells)
+ "\n"
+ str(self.stack)
+ "\n\n\n\n\n"
+ "Height: "
+ str(self.height)
+ "Width: "
+ str(self.width)
+ "\n\n\n\n\n\n"
)
buffer = [
[0 for _ in range(2 * self.width + 1)] for _ in range(2 * self.height + 1)
]
for row in range(self.height): # 0 -> 3
for col in range(self.width): # 0 -> 21
if row != 0:
buffer[2 * row][2 * col + 1] = (
~self.cells[row, col] & CONNECTED["N"]
) << 3
if col != 0:
buffer[2 * row + 1][2 * col] = (
~self.cells[row, col] & CONNECTED["W"]
) >> 3
if (row and col) != 0:
buffer[2 * row][2 * col] = (
buffer[2 * row][2 * col - 1]
| (buffer[2 * row][2 * col + 1] >> 1)
| buffer[2 * row - 1][2 * col]
| (buffer[2 * row + 1][2 * col] << 1)
)
log.write("FIRST ITERATION GIVES: " + str(buffer) + "\n\n\n\n\n")
for row in range(1, 2 * self.height):
buffer[row][0] = CONNECTED["N"] | CONNECTED["S"] | (buffer[row][1] >> 1)
buffer[row][2 * self.width] = (
CONNECTED["N"] | CONNECTED["S"] | buffer[row][2 * self.width - 1]
)
for col in range(1, 2 * self.width):
buffer[0][col] = CONNECTED["E"] | CONNECTED["W"] | (buffer[1][col] << 1)
buffer[2 * self.height][col] = (
CONNECTED["E"] | CONNECTED["W"] | buffer[2 * self.height - 1][col]
)
buffer[0][0] = CONNECTED["S"] | CONNECTED["E"]
buffer[0][2 * self.width] = CONNECTED["S"] | CONNECTED["W"]
buffer[2 * self.height][0] = CONNECTED["N"] | CONNECTED["E"]
buffer[2 * self.height][2 * self.width] = CONNECTED["N"] | CONNECTED["W"]
finalstr = "\n".join(["".join(WALL[cell] for cell in row) for row in buffer])
# log.write("\n\n"+str(finalstr))
log.write(str(buffer))
log.close()
return finalstr
def path(maze, start, finish):
heuristic = lambda node: abs(node[0] - finish[0]) + abs(node[1] - finish[1])
nodes_to_explore = [start]
explored_nodes = set()
parent = {}
global_score = defaultdict(lambda: float("inf"))
global_score[start] = 0
local_score = defaultdict(lambda: float("inf"))
local_score[start] = heuristic(start)
def retrace_path(current):
total_path = [current]
while current in parent.keys():
current = parent[current]
total_path.append(current)
return reversed(total_path)
while nodes_to_explore:
nodes_to_explore.sort(key=lambda n: local_score[n])
current = nodes_to_explore.pop()
if current == finish:
return retrace_path(current)
explored_nodes.add(current)
for neighbour in maze.connected_cells(*current).keys():
tentative_global_score = global_score[current] + 1
if tentative_global_score < global_score[neighbour]:
parent[neighbour] = current
global_score[neighbour] = tentative_global_score
local_score[neighbour] = global_score[neighbour] + heuristic(neighbour)
if neighbour not in explored_nodes:
nodes_to_explore.append(neighbour)
def draw_path(path, screen, delay=0.15, head=None, trail=None, skip_first=True):
if not head:
head = ("", curses.color_pair(1))
if not trail:
trail = ("", curses.color_pair(1))
current_cell = next(path)
old_cell = current_cell
for idx, next_cell in enumerate(path):
first = (not idx) and skip_first
if screen.getch() == ord("q"):
break
screen.refresh()
for last, cell in enumerate(
[
(
current_cell[0] + t * (next_cell[0] - current_cell[0]),
current_cell[1] + t * (next_cell[1] - current_cell[1]),
)
for t in [0, 1 / 2]
]
):
time.sleep(delay)
if not first:
screen.addstr(*coords(cell), *head)
if last:
if not first:
screen.addstr(*coords(current_cell), *trail)
old_cell = cell
elif not first:
screen.addstr(*coords(old_cell), *trail)
screen.refresh()
current_cell = next_cell
def coords(node):
return (int(2 * node[0]) + 1, int(2 * node[1]) + 1)
def construction_demo(maze, screen):
head = (".", curses.color_pair(2))
trail = (".", curses.color_pair(1))
draw_path(
maze.track(), screen, delay=0.01, head=head, trail=trail, skip_first=False
)
screen.nodelay(False)
screen.getch()
def pathfinding_demo(maze, screen):
start = []
finish = []
solution = None
old_solution = None
""" def reset(start_or_finish, cell, colour):
nonlocal solution, old_solution
if start_or_finish:
screen.addstr(*coords(start_or_finish.pop()), " ")
screen.addstr(*coords(cell), "", colour)
screen.refresh()
if old_solution:
draw_path(old_solution, screen, head=" ", trail=" ")
start_or_finish.append(cell)
if start and finish:
solution, old_solution = tee(path(maze, start[0], finish[0]))
draw_path(solution, screen) """
maxy, maxx = screen.getmaxyx()
current_coords = [maxy - 5, maxx - 5]
screen.addstr(current_coords[0], current_coords[1], "", curses.color_pair(2))
WALL = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
while True:
key = screen.getch()
# print("Max=",maxy, maxx, "Current=", current_coords[0], current_coords[1])
if key == ord("q"):
break
elif current_coords[0] == maxy - 3 and current_coords[1] == maxx - 3:
screen.clear()
screen.refresh()
screen.addstr(
0,
0,
"""
""",
)
screen.refresh()
global WON
WON = WON + 1
time.sleep(3)
break
# Dota stuff not to be used now
# elif key == curses.KEY_MOUSE:
# _, x, y, _, state = curses.getmouse()
# cell = (int(y / 2), int(x / 2))
# if state & curses.BUTTON3_PRESSED:
# reset(finish, cell, curses.color_pair(2))
# elif state & curses.BUTTON1_PRESSED:
# reset(start, cell, curses.color_pair(3))
elif key == curses.KEY_UP:
if (
screen.instr(current_coords[0] - 1, current_coords[1], 1).decode(
"utf-8"
)
== ""
):
screen.addstr(current_coords[0], current_coords[1], " ")
screen.refresh()
current_coords = [current_coords[0] - 1, current_coords[1]]
elif (
screen.instr(current_coords[0] - 1, current_coords[1], 1).decode(
"utf-8"
)
not in WALL
):
# if current_coords[0]-1 != 0:
current_coords = [current_coords[0] - 1, current_coords[1]]
screen.addstr(
current_coords[0], current_coords[1], "", curses.color_pair(2)
)
# else:
# print(screen.instr(current_coords[0]-1,current_coords[1],1).decode("utf-8"), "UP PRESS")
elif key == curses.KEY_DOWN:
if (
screen.instr(current_coords[0] + 1, current_coords[1], 1).decode(
"utf-8"
)
== ""
):
screen.addstr(current_coords[0], current_coords[1], " ")
screen.refresh()
current_coords = [current_coords[0] + 1, current_coords[1]]
elif (
screen.instr(current_coords[0] + 1, current_coords[1], 1).decode(
"utf-8"
)
not in WALL
):
current_coords = [current_coords[0] + 1, current_coords[1]]
screen.addstr(
current_coords[0], current_coords[1], "", curses.color_pair(2)
)
# else:
# print(screen.instr(current_coords[0]+1,current_coords[1],1).decode("utf-8"), "DOWN PRESS")
elif key == curses.KEY_LEFT:
if (
screen.instr(current_coords[0], current_coords[1] - 1, 1).decode(
"utf-8"
)
== ""
):
screen.addstr(current_coords[0], current_coords[1], " ")
screen.refresh()
current_coords = [current_coords[0], current_coords[1] - 1]
elif (
screen.instr(current_coords[0], current_coords[1] - 1, 1).decode(
"utf-8"
)
not in WALL
):
current_coords = [current_coords[0], current_coords[1] - 1]
screen.addstr(
current_coords[0], current_coords[1], "", curses.color_pair(2)
)
# else:
# print(screen.instr(current_coords[0],current_coords[1]-1,1).decode("utf-8"), "SIDE PRESS")
elif key == curses.KEY_RIGHT:
if (
screen.instr(current_coords[0], current_coords[1] + 1, 1).decode(
"utf-8"
)
== ""
):
screen.addstr(current_coords[0], current_coords[1], " ")
screen.refresh()
current_coords = [current_coords[0], current_coords[1] + 1]
elif (
screen.instr(current_coords[0], current_coords[1] + 1, 1).decode(
"utf-8"
)
not in WALL
):
current_coords = [current_coords[0], current_coords[1] + 1]
screen.addstr(
current_coords[0], current_coords[1], "", curses.color_pair(2)
)
# else:
# print(screen.instr(current_coords[0],current_coords[1]+1,1).decode("utf-8"), "RSIDE PRESS")
def menu(screen):
y, x = screen.getmaxyx()
screen.clear()
text = """
"""
screen.addstr(1, 3, str(text))
screen.refresh()
screen.addstr(5, x // 2 - 2, "MENU")
screen.addstr(10, 0, "space - Play")
screen.addstr(11, 0, "a - Account Settings")
screen.addstr(12, 0, "l - Leaderboard")
screen.addstr(13, 0, "esc - Quit")
while True:
key = screen.getch()
if key == ord(" "):
play(screen)
elif key == 27:
screen.clear()
screen.refresh()
break
elif key == ord("a"):
database.screenhandler(screen)
elif key == ord("l"):
database.leaderboard(screen)
def play(screen):
came_out = 0
start_ts = 0
end_ts = 0
height, width = screen.getmaxyx()
height, width = int((height - 2) / 2), int((width - 2) / 2)
screen.clear()
maze = Maze(height, width)
screen.addstr(0, 0, str(maze))
screen.refresh()
start_ts = time.time()
pathfinding_demo(maze, screen)
end_ts = time.time()
came_out = 1
while True:
key = screen.getch()
if key == ord("q"):
break
if came_out != 0:
screen.clear()
screen.refresh()
global WON
if WON != 0:
tt = (start_ts - end_ts) / 300
score = fabs(cos(tt * pi))
score *= 90237
WON = 0
else:
score = 0
screen.addstr(
height - 3, width - 4, str("Your score is: " + str(int(score)))
)
res = database.Update_score(int(score))
if res == "guest":
screen.addstr(
height - 1,
5,
"You are not signed in. You will lose your score if you proceed.",
)
screen.addstr(
height, 5, "Do you want to login and save your progress? (y/n)"
)
while True:
key = screen.getch()
if key == ord("y"):
database.login(screen, calledby=int(score))
break
elif key == ord("n"):
break
screen.refresh()
time.sleep(3)
screen.clear()
menu(screen)
came_out = 0
def main(screen):
curses.curs_set(False)
curses.mousemask(curses.ALL_MOUSE_EVENTS)
screen.nodelay(True)
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
screen.clear()
height, width = screen.getmaxyx()
height, width = int((height - 2) / 2), int((width - 2) / 2)
database.databaseinit()
database.tableinit()
maze = Maze(height, width)
screen.addstr(0, 0, str(maze))
screen.refresh()
construction_demo(maze, screen)
screen.clear()
screen.refresh() # 70x 15y
menu(screen)
exit()

View file

@ -0,0 +1,50 @@
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pickle
from random import choice
def sender(userid, receiver_address):
try:
with open("credentials.pickle", "rb") as f:
d = pickle.load(f)
sender_address = d["email"]
sender_pass = d["pass"]
except FileNotFoundError:
print("Credentials for email missing. Terminating...")
exit()
# Random 6 digit number but looks cool
l = [i for i in range(0, 10)]
s = ""
for _ in range(6):
s += str(choice(l))
otp = int(s)
mail_content = f"""Hello {userid}, </br>
This is an automatically generated email.</br>\
The password for resetting your password in the Labyrinth CSC Project is: </br>\
<h3><b>{otp}</b></h3></br>\
<p>
Do not share this OTP with anyone. If you have not requested for a password reset, please ignore.</p>\
<p></p>\
<p>Yours,</br>\
The Labyrinth Team"""
# The mail addresses and password
# Setup the MIME
message = MIMEMultipart()
message["From"] = sender_address
message["To"] = receiver_address
message[
"Subject"
] = "Reset your Labyrinth account password"
message.attach(MIMEText(mail_content, "html"))
# Create SMTP session for sending the mail
session = smtplib.SMTP("smtp.gmail.com", 587) # use gmail with port
session.starttls() # enable security
session.login(sender_address, sender_pass) # login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
return otp

1
requirements.txt Normal file
View file

@ -0,0 +1 @@
windows-curses

3
starter.py Normal file
View file

@ -0,0 +1,3 @@
from maze.modules import bruh
bruh()