diff --git a/credentials.pickle b/credentials.pickle index 093f73c..c8fb886 100644 Binary files a/credentials.pickle and b/credentials.pickle differ diff --git a/maze/menu.py b/maze/menu.py index 4dfc82f..f988c61 100644 --- a/maze/menu.py +++ b/maze/menu.py @@ -7,8 +7,9 @@ import maze.modules.maze_saveandload as sl import maze.modules.PlayerBase_func as database import pong import snake -from maze.modules.about import about import wordle.wordle as wordlegame +from maze.modules.about import about + def menu(screen): exit = False diff --git a/maze/modules/PlayerBase_func.py b/maze/modules/PlayerBase_func.py index 84c5552..ab46f4f 100644 --- a/maze/modules/PlayerBase_func.py +++ b/maze/modules/PlayerBase_func.py @@ -106,9 +106,13 @@ def screenhandler(screen): # MAIN MENU global loggedin, U, gamerid screen.clear() screen.refresh() - screen.addstr(1, w // 2 - 8, "ACCOUNT SETTINGS", curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + 1, w // 2 - 8, "ACCOUNT SETTINGS", curses.color_pair(3) | curses.A_BOLD + ) if loggedin: - screen.addstr(2, w // 2 - 8, f"Logged in as: {U}", curses.color_pair(6) | curses.A_BOLD) + screen.addstr( + 2, w // 2 - 8, f"Logged in as: {U}", curses.color_pair(6) | curses.A_BOLD + ) 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") @@ -253,9 +257,19 @@ def login(screen, calledby=None): # Function to log in loggedin = True gamerid = res[0][1] U = inputU - screen.addstr(y // 2 + 3, x // 2 - 9, "Login Successful!", curses.color_pair(6) | curses.A_BOLD) + screen.addstr( + y // 2 + 3, + x // 2 - 9, + "Login Successful!", + curses.color_pair(6) | curses.A_BOLD, + ) if calledby is not None: - screen.addstr(y // 2 + 4, x // 2 - 8, "Updating score...", curses.color_pair(6) | curses.A_BOLD) + screen.addstr( + y // 2 + 4, + x // 2 - 8, + "Updating score...", + curses.color_pair(6) | curses.A_BOLD, + ) screen.refresh() sleep(3) Update_score(calledby[0], calledby[1]) @@ -397,7 +411,9 @@ def new_add(screen, calledby=None): screen.border() y, x = screen.getmaxyx() global quitting - screen.addstr(1, x // 2 - 8, "ACCOUNT CREATION", curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + 1, x // 2 - 8, "ACCOUNT CREATION", curses.color_pair(3) | curses.A_BOLD + ) add_name = user( screen, y // 2 - 4, x // 2 - 10 ) # calling fn user for username, password and email @@ -452,7 +468,9 @@ def modify_account(screen): screen.border() y, x = screen.getmaxyx() global loggedin, quitting, U - screen.addstr(1, x // 2 - 8, "MODIFY ACCOUNT SETTINGS", curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + 1, x // 2 - 8, "MODIFY ACCOUNT SETTINGS", curses.color_pair(3) | curses.A_BOLD + ) if loggedin == False: screen.addstr( y // 2, @@ -522,7 +540,9 @@ def view_account(screen): screen.clear() screen.refresh() screen.border() - screen.addstr(1, x // 2 - 9, "VIEW ACCOUNT DETAILS", curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + 1, x // 2 - 9, "VIEW ACCOUNT DETAILS", curses.color_pair(3) | curses.A_BOLD + ) if not loggedin: screen.addstr( y // 2, @@ -540,16 +560,32 @@ def view_account(screen): ) screen.addstr(3, x // 2 - 7, "Gamer ID: " + player_details[0][0]) screen.addstr(5, x // 2 - 8, "Username: " + player_details[0][1]) - screen.addstr(7, x// 2 - 9, "Email: " + player_details[0][2]) + screen.addstr(7, x // 2 - 9, "Email: " + player_details[0][2]) j = 0 - for i, tablename in enumerate(["maze_scores", "pong_scores", "snake_scores", "wordle_scores"]): + for i, tablename in enumerate( + ["maze_scores", "pong_scores", "snake_scores", "wordle_scores"] + ): score_details = get(f"SELECT * FROM {tablename} WHERE gamerid = '{gamerid}'") if not score_details: score_details.append(("Bruh",) + ("Not yet available.",) * 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])) + 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.") @@ -605,13 +641,15 @@ def delete(screen): def Update_score(score, game): - tablename = game + '_scores' + tablename = game + "_scores" global U, gamerid, loggedin if not loggedin: return "guest" res = get(f"SELECT * FROM {tablename} WHERE gamerid = '{gamerid}'") if not res: - post(f"INSERT INTO {tablename} (gamerid, highscore, lastscore, timesplayed) VALUES ('{gamerid}',0, 0, 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 if res[0][1] < score: @@ -646,7 +684,9 @@ def forgotpassword(screen): screen.clear() screen.refresh() y, x = screen.getmaxyx() - screen.addstr(1, x // 2 - 7, "FORGOT PASSWORD", curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + 1, x // 2 - 7, "FORGOT PASSWORD", curses.color_pair(3) | curses.A_BOLD + ) screen.refresh() global quitting usernamelist = list_getter("username") @@ -770,7 +810,7 @@ def logout(screen): y, x = screen.getmaxyx() screen.clear() screen.refresh() - scree.border() + screen.border() screen.addstr(1, x // 2 - 2, "LOGOUT", curses.color_pair(3) | curses.A_BOLD) screen.addstr(y // 2, 5, "Logging out of your account...") global loggedin, U, gamerid @@ -790,14 +830,21 @@ def leaderboard(screen): curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK) screen.keypad(True) leaderboardquit = True - tables = {0:"maze_scores", 1:"pong_scores", 2:"snake_scores", 3:"wordle_scores"} + tables = {0: "maze_scores", 1: "pong_scores", 2: "snake_scores", 3: "wordle_scores"} current_page = 0 while leaderboardquit: screen.clear() screen.border() screen.refresh() - screen.addstr(1, x // 2 - 5, "LEADERBOARD", curses.color_pair(3) | curses.A_BOLD) - screen.addstr(3, x // 2 - 2, f"{tables[current_page].split('_')[0].upper()}", curses.color_pair(6) | curses.A_BOLD) + screen.addstr( + 1, x // 2 - 5, "LEADERBOARD", curses.color_pair(3) | curses.A_BOLD + ) + screen.addstr( + 3, + x // 2 - 2, + f"{tables[current_page].split('_')[0].upper()}", + curses.color_pair(6) | curses.A_BOLD, + ) res = get( f"SELECT p.gamerid,\ p.username,\ @@ -807,7 +854,7 @@ def leaderboard(screen): WHERE p.gamerid = s.gamerid " ) - for i in range(len(res) - 1): # Sorting + for i in range(len(res) - 1): # Sorting 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] @@ -822,7 +869,9 @@ def leaderboard(screen): screen.addstr(sy, 50, str(i[2]), curses.color_pair(2) | curses.A_BOLD) sy += 1 screen.addstr(y - 2, 2, "Use arrow keys for different pages.", curses.A_DIM) - screen.addstr(y - 2, x - 36, "Press [esc] to return to main menu.", curses.A_DIM) + screen.addstr( + y - 2, x - 36, "Press [esc] to return to main menu.", curses.A_DIM + ) while True: key = screen.getch() if key == 27: diff --git a/maze/modules/about.py b/maze/modules/about.py index 66895e5..afada91 100644 --- a/maze/modules/about.py +++ b/maze/modules/about.py @@ -1,6 +1,8 @@ -import maze.menu import curses +import maze.menu + + def about(screen): y, x = screen.getmaxyx() screen.clear() @@ -21,9 +23,13 @@ def about(screen): "There are a series of retro games namely the maze, pong, snake and wordle.", ) screen.addstr( - 10, 5, "The maze is generated which always has a path towards the right bottom corner by using " + 10, + 5, + "The maze is generated which always has a path towards the right bottom corner by using ", + ) + screen.addstr( + 11, 5, "a famous generation algorithm named Depth First Search (DFS)." ) - screen.addstr(11, 5, "a famous generation algorithm named Depth First Search (DFS).") screen.addstr( 13, 5, diff --git a/maze/modules/maze.py b/maze/modules/maze.py index 8d00245..2695b20 100644 --- a/maze/modules/maze.py +++ b/maze/modules/maze.py @@ -1,6 +1,5 @@ import curses import random -import sys import time from collections import defaultdict from itertools import tee @@ -253,8 +252,8 @@ def pathfinding_demo( reset(finish, cell, curses.color_pair(2)) reset(start, (0, 0), curses.color_pair(2)) else: - current_coords = [maxy - 5, maxx - 27] - # current_coords = [1, 1] + # current_coords = [maxy - 5, maxx - 27] + current_coords = [1, 1] screen.addstr(current_coords[0], current_coords[1], "█", curses.color_pair(2)) WALL = ["═", "║", "╗", "╚", "╝", "╔", "╠", "╣", "╦", "╩", "╬", "═", "═", "║", "║"] pause_elapsed = 0 @@ -297,12 +296,7 @@ def pathfinding_demo( \t\t\t ████ ██ ██ ██ ██ ██ █ ██ ██ ██ ██ ██ ██ ██ \t\t\t ██ ██ ██ ██ ██ ██ ███ ██ ██ ██ ██ ██ ██ \t\t\t ██ ██████ ██████ ███ ███ ██████ ██ ████ ██""" - screen.addstr( - maxy // 2 - 5, - maxx // 2 - 31, - winmsg, - curses.color_pair(5) - ) + screen.addstr(maxy // 2 - 5, maxx // 2 - 31, winmsg, curses.color_pair(5)) screen.border() screen.refresh() global WON @@ -416,7 +410,7 @@ def play( loadedtime=0, executeguest=False, outerscore=0, - outergame=False + outergame=False, ): y, x = screen.getmaxyx() height, width = int((y - 2) / 2), int((x - 2) / 2) @@ -425,18 +419,25 @@ def play( screen.clear() screen.refresh() screen.border() - screen.addstr(y // 2 - 5, x // 2 - 7, str("Your score is: " + str(int(score))), curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + y // 2 - 5, + x // 2 - 7, + str("Your score is: " + str(int(score))), + curses.color_pair(3) | curses.A_BOLD, + ) res = database.Update_score(int(score), game) if res == "guest": screen.addstr( height - 1, 31, "You are not signed in. You will lose your score if you proceed.", - curses.color_pair(1) | curses.A_BOLD + curses.color_pair(1) | curses.A_BOLD, ) screen.addstr( - height, 37, "Do you want to login and save your progress? (y/n)", - curses.color_pair(1) | curses.A_BOLD + height, + 37, + "Do you want to login and save your progress? (y/n)", + curses.color_pair(1) | curses.A_BOLD, ) while True: key = screen.getch() @@ -495,6 +496,7 @@ def play( guestswitch(score, game="maze") + def main(screen): screen.nodelay(True) curses.curs_set(False) diff --git a/maze/modules/maze_saveandload.py b/maze/modules/maze_saveandload.py index e367de6..2cadb4f 100644 --- a/maze/modules/maze_saveandload.py +++ b/maze/modules/maze_saveandload.py @@ -1,7 +1,7 @@ +import curses import os import pickle from time import sleep -import curses import maze.menu as m @@ -57,11 +57,7 @@ def load(screen): sy = 5 for i in range(len(mazes)): msg = f"{str(i + 1)}. Maze {((mazes[i].replace('.maze', '')).split('_'))[1]} - {((mazes[i].replace('.maze', '')).split('_'))[2]}" - screen.addstr( - sy, - x // 2 - len(msg) // 2, - msg - ) + screen.addstr(sy, x // 2 - len(msg) // 2, msg) sy += 1 while True: screen.addstr(y // 2 + 5, x // 2 - 15, "Enter preferred maze number: ") @@ -76,7 +72,12 @@ def load(screen): if num < len(mazes): break else: - screen.addstr(y - 5, x // 2 - 23, "Entered maze doesn't exist. Please try again.", curses.color_pair(1)) + screen.addstr( + y - 5, + x // 2 - 23, + "Entered maze doesn't exist. Please try again.", + curses.color_pair(1), + ) while True: key = screen.getch() if key == 10: diff --git a/pong.py b/pong.py index c615ba2..8802ee8 100644 --- a/pong.py +++ b/pong.py @@ -155,8 +155,18 @@ def ball_movement(screen, ball, score): collision = ball_coords[2] if collision == "OVER": finalscore = score.score - screen.addstr(y // 2 - 1, x // 2 - 3, "GAME OVER!", curses.color_pair(1) | curses.A_BOLD) - screen.addstr(y // 2, x // 2 - 5, "The Score is: " + str(finalscore), curses.color_pair(3) | curses.A_BOLD) + screen.addstr( + y // 2 - 1, + x // 2 - 3, + "GAME OVER!", + curses.color_pair(1) | curses.A_BOLD, + ) + screen.addstr( + y // 2, + x // 2 - 5, + "The Score is: " + str(finalscore), + curses.color_pair(3) | curses.A_BOLD, + ) time.sleep(0.25) quit.set() time.sleep(1.75) diff --git a/snake.py b/snake.py index b9e8a28..219b3fd 100644 --- a/snake.py +++ b/snake.py @@ -89,7 +89,9 @@ def main(stdscr): new_head = [head[0] - 1, head[1]] # insert and print new head - stdscr.addstr(new_head[0], new_head[1], "█", curses.color_pair(3) | curses.A_BOLD) + stdscr.addstr( + new_head[0], new_head[1], "█", curses.color_pair(3) | curses.A_BOLD + ) snake.insert(0, new_head) # if sanke head is on food @@ -117,8 +119,18 @@ def main(stdscr): or snake[0] in snake[1:] ): msg = "Game Over!" - stdscr.addstr(sh // 2, sw // 2 - len(msg) // 2, msg, curses.color_pair(1) | curses.A_BOLD) - stdscr.addstr(sh // 2 + 1, sw // 2 - 8, "The Score is: "+str(score), curses.color_pair(3) | curses.A_BOLD) + stdscr.addstr( + sh // 2, + sw // 2 - len(msg) // 2, + msg, + curses.color_pair(1) | curses.A_BOLD, + ) + stdscr.addstr( + sh // 2 + 1, + sw // 2 - 8, + "The Score is: " + str(score), + curses.color_pair(3) | curses.A_BOLD, + ) while stdscr.getch() == -1: pass time.sleep(2) diff --git a/starter.py b/starter.py index 783887b..30f12de 100644 --- a/starter.py +++ b/starter.py @@ -3,8 +3,8 @@ import pickle import subprocess import sys -from maze.modules import bruh import maze.modules.PlayerBase_func as player +from maze.modules import bruh user = password = None diff --git a/wordle/dictionary.py b/wordle/dictionary.py index 0de8480..d9746b6 100644 --- a/wordle/dictionary.py +++ b/wordle/dictionary.py @@ -1,12 +1,28 @@ +import pickle + import requests -app_id = "4a8fca56" -app_key = "85885b5929e5b14402e75fcb4898d7f5" +with open("credentials.pickle", "rb") as f: + try: + while True: + d = pickle.load(f) + if d["credtype"] == "oxfordapi": + app_id = d["app_id"] + app_key = d["app_key"] + except EOFError: + pass + language = "en-us" + def defnsyn(w): - url = r"https://od-api.oxforddictionaries.com:443/api/v2/entries/" + language + "/" + w.lower() - r=requests.get(url, headers={"app_id": app_id, "app_key": app_key}) + url = ( + r"https://od-api.oxforddictionaries.com:443/api/v2/entries/" + + language + + "/" + + w.lower() + ) + r = requests.get(url, headers={"app_id": app_id, "app_key": app_key}) if r.status_code != 200: return None, None res = r.json() @@ -14,43 +30,63 @@ def defnsyn(w): lexicalCategories = [] synonyms = [] defn = "" - if len(s1) > 1: - for i in range(len(s1)): - lexicalCategories.append(s1[i]["lexicalCategory"]['id']) - if "verb" in lexicalCategories: - baseindex = s1[lexicalCategories.index("verb")]['entries'][0]['senses'][0] - defn = (baseindex['shortDefinitions'][0]) - if "synonyms" in baseindex: - no = 2 if len(baseindex["synonyms"]) > 3 else len(baseindex["synonyms"]) - while no: - synonyms.append(baseindex["synonyms"][no]["text"]) - no -= 1 - synonyms.reverse() - elif "noun" in lexicalCategories: - baseindex = s1[lexicalCategories.index("noun")]['entries'][0]['senses'][0] - defn = (baseindex['shortDefinitions'][0]) - if "synonyms" in baseindex: - no = 3 if len(baseindex["synonyms"]) > 3 else len(baseindex["synonyms"]) - while no: - synonyms.append(baseindex["synonyms"][no]["text"]) - no -= 1 - synonyms.reverse() + try: + if len(s1) > 1: + for i in range(len(s1)): + lexicalCategories.append(s1[i]["lexicalCategory"]["id"]) + if "verb" in lexicalCategories: + baseindex = s1[lexicalCategories.index("verb")]["entries"][0]["senses"][ + 0 + ] + defn = baseindex["shortDefinitions"][0] + if "synonyms" in baseindex: + no = ( + 2 + if len(baseindex["synonyms"]) > 3 + else len(baseindex["synonyms"]) + ) + while no: + synonyms.append(baseindex["synonyms"][no]["text"]) + no -= 1 + synonyms.reverse() + elif "noun" in lexicalCategories: + baseindex = s1[lexicalCategories.index("noun")]["entries"][0]["senses"][ + 0 + ] + defn = baseindex["shortDefinitions"][0] + if "synonyms" in baseindex: + no = ( + 3 + if len(baseindex["synonyms"]) > 3 + else len(baseindex["synonyms"]) + ) + while no: + synonyms.append(baseindex["synonyms"][no]["text"]) + no -= 1 + synonyms.reverse() + else: + baseindex = s1[0]["entries"][0]["senses"][0] + defn = baseindex["shortDefinitions"][0] + if "synonyms" in baseindex: + no = ( + 3 + if len(baseindex["synonyms"]) > 3 + else len(baseindex["synonyms"]) + ) + while no: + synonyms.append(baseindex["synonyms"][no]["text"]) + no -= 1 + synonyms.reverse() else: - baseindex = s1[0]['entries'][0]['senses'][0] - defn = (baseindex['shortDefinitions'][0]) + baseindex = s1[0]["entries"][0]["senses"][0] + defn = baseindex["shortDefinitions"][0] if "synonyms" in baseindex: no = 3 if len(baseindex["synonyms"]) > 3 else len(baseindex["synonyms"]) while no: synonyms.append(baseindex["synonyms"][no]["text"]) no -= 1 synonyms.reverse() - else: - baseindex = s1[0]['entries'][0]['senses'][0] - defn = (baseindex['shortDefinitions'][0]) - if "synonyms" in baseindex: - no = 3 if len(baseindex["synonyms"]) > 3 else len(baseindex["synonyms"]) - while no: - synonyms.append(baseindex["synonyms"][no]["text"]) - no -= 1 - synonyms.reverse() + except: + print("err") + defn = synonyms = "" return defn, synonyms diff --git a/wordle/solver.py b/wordle/solver.py index 625a476..e9a1f66 100644 --- a/wordle/solver.py +++ b/wordle/solver.py @@ -1,5 +1,6 @@ words = open("words.txt").read().split("\n") + def partition(word, words): # Get how many words will remain for each possible response partitions = [] @@ -8,9 +9,10 @@ def partition(word, words): for c in "MCW": for d in "MCW": for e in "MCW": - partitions.append(len(reduce(word, a+b+c+d+e, words))) + partitions.append(len(reduce(word, a + b + c + d + e, words))) return partitions + def reduce(word, result, words): # word: 5-letter word (lowercase) # result: 5-letter str consisting of M, C, W (misplaced, correct, wrong) @@ -19,16 +21,19 @@ def reduce(word, result, words): nres = [] for w in res: if s == "M": - if w[i] != word[i] and word[i] in w: nres.append(w) + if w[i] != word[i] and word[i] in w: + nres.append(w) if s == "C": - if w[i] == word[i]: nres.append(w) + if w[i] == word[i]: + nres.append(w) if s == "W": if w[i] != word[i]: - if not(word[i] in w) or word.count(word[i]) > 1: + if not (word[i] in w) or word.count(word[i]) > 1: nres.append(w) res = nres return res + print("WORDLE SOLVER") print("=============") # First guess is precomputed @@ -42,8 +47,8 @@ while result != "CCCCC": opt_size = float("inf") for word in words: p = partition(word, words) - avg_partition_size = sum(p)/len(p) + avg_partition_size = sum(p) / len(p) if opt_size > avg_partition_size: opt_size = avg_partition_size opt = word - # print(p) \ No newline at end of file + # print(p) diff --git a/wordle/wordle-solver.py b/wordle/wordle-solver.py index 4b7bb42..9ada072 100644 --- a/wordle/wordle-solver.py +++ b/wordle/wordle-solver.py @@ -8,7 +8,9 @@ correctletters = ["-"] * 5 while maxguesses: try: - correctguess = input("\nEnter correct letter positions (use - for other letters): ").lower() + correctguess = input( + "\nEnter correct letter positions (use - for other letters): " + ).lower() uselessguess = input("Enter all incorrect letters without space: ").lower() wantedguess = input("Enter all letters of incorrect postiions: ").lower() @@ -48,4 +50,4 @@ while maxguesses: except KeyboardInterrupt: print("\n\nThe word was found!") break - maxguesses -= 1 \ No newline at end of file + maxguesses -= 1 diff --git a/wordle/wordle.py b/wordle/wordle.py index 4e353d9..8769758 100644 --- a/wordle/wordle.py +++ b/wordle/wordle.py @@ -1,9 +1,10 @@ -# A slightly more readable version of wordle-curses +import curses +import random +import time -import curses, random, time -from wordle.dictionary import defnsyn import maze.menu import maze.modules.maze as m1 +from wordle.dictionary import defnsyn quitwordle = False words = open("wordle\\words.txt", "r").read().split("\n") @@ -15,7 +16,7 @@ completionMessages = [ "Splendid!", "Amazing!", "Great!", - "Good!" + "Good!", ] # Draw one row of the board @@ -30,6 +31,7 @@ def writeWord(s, word, remark, y): curses.color_pair(colorPairBindings[color]), ) + # Score a word def score(guess, word, alphabet): res = [" "] * 5 @@ -37,8 +39,12 @@ def score(guess, word, alphabet): # First process correct letters for i, c in enumerate(guess): - if c == word[i]: #checking if guess letter corresponds to letter of the same index in chosen word - charIndex = ord(c) - 97 # 97 corresponds to a - gives alphabet number. (eg. h = 8) + if ( + c == word[i] + ): # checking if guess letter corresponds to letter of the same index in chosen word + charIndex = ( + ord(c) - 97 + ) # 97 corresponds to a - gives alphabet number. (eg. h = 8) counts[charIndex] += 1 res[i] = "c" # correct spot alphabet[charIndex] = "c" @@ -48,7 +54,9 @@ def score(guess, word, alphabet): if c != word[i]: charIndex = ord(c) - 97 counts[charIndex] += 1 - if c in word and word.count(c) >= counts[charIndex]: # if freq of letters in guess lesser than freq in word + if ( + c in word and word.count(c) >= counts[charIndex] + ): # if freq of letters in guess lesser than freq in word res[i] = "w" # wrong spot if alphabet[charIndex] != "c": alphabet[charIndex] = "w" @@ -58,6 +66,7 @@ def score(guess, word, alphabet): return "".join(res), alphabet + # Render current board # Updates alphabet use state + renders colours of guesses def render(s, guesses, alphabet): @@ -74,15 +83,16 @@ def render(s, guesses, alphabet): writeWord(s, w, r, i * 2 + 7) s.addstr(len(guesses) * 2 + 10, 0, " ") + # Accept word from user input def getWord(s, y): word = "" while True: - writeWord(s, word, "u" * len(word), y) # u = default blue colour + writeWord(s, word, "u" * len(word), y) # u = default blue colour k = s.getch() - if k == 8: # backspace + if k == 8: # backspace word = word[:-1] - elif k == 27: # esc + elif k == 27: # esc global quitwordle quitwordle = True return "hello" @@ -91,43 +101,42 @@ def getWord(s, y): elif chr(k).isalpha() and len(word) < 5: word += chr(k) + # Run one game of Wordle def run(s): s.clear() - word = random.choice(words) #chosen word + word = random.choice(words) # chosen word with open("log.txt", "a") as f: - f.write("Chosen word: "+ word+"\n") + f.write("Chosen word: " + word + "\n") defn, synonyms = defnsyn(word) - guesses = [] # stores each guess and its result - alphabet = ["u"] * 26 # current status of each letter whether used or not + guesses = [] # stores each guess and its result + alphabet = ["u"] * 26 # current status of each letter whether used or not # c = correct positon, w = correct letter but not position, n = wrong letter, u = not used # "ccccc" means all letters are in correct spot while not (len(guesses)) or (guesses[-1][1] != "ccccc" and len(guesses) < 6): if quitwordle: return - render(s, guesses, alphabet) # Update current state of board from start + render(s, guesses, alphabet) # Update current state of board from start guess = getWord(s, len(guesses) * 2 + 7).lower() - if not (guess in words): # Check if given word is valid + if not (guess in words): # Check if given word is valid s.addstr(len(guesses) * 2 + 10, 0, "INVALID WORD", curses.color_pair(1)) s.refresh() time.sleep(1) continue res, alphabet = score(guess, word, alphabet) guesses.append([guess, res]) - render(s, guesses, alphabet) #Renders final board + render(s, guesses, alphabet) # Renders final board # Ending spiel s.addstr(len(guesses) * 2 + 6, 0, "╰─┴─┴─┴─┴─╯") if guesses[-1][1] != "ccccc": - s.addstr(len(guesses) * 2 + 8, 0, "No more tries - the word was " + word.upper()) - else: s.addstr( - len(guesses) * 2 + 8, - 0, - completionMessages[len(guesses)] + len(guesses) * 2 + 8, 0, "No more tries - the word was " + word.upper() ) + else: + s.addstr(len(guesses) * 2 + 8, 0, completionMessages[len(guesses)]) if defn and synonyms: - s.addstr(len(guesses) * 2 + 9, 0, word+": ", curses.color_pair(2)) + s.addstr(len(guesses) * 2 + 9, 0, word + ": ", curses.color_pair(2)) synonyms = ", ".join(synonyms) s.addstr(len(guesses) * 2 + 9, 8, defn) s.addstr(len(guesses) * 2 + 10, 0, "Some synonyms: ", curses.color_pair(2)) @@ -137,6 +146,7 @@ def run(s): finalscore = allocatescore(guesses) return finalscore + def allocatescore(guesses): finalscore = 0 if len(guesses) <= 3: @@ -149,6 +159,7 @@ def allocatescore(guesses): finalscore = 20 return finalscore + # Main function def main(s): # Initialize colors @@ -164,10 +175,11 @@ def main(s): curses.init_pair(p[0], p[1], curses.COLOR_BLACK) # Run game finalscore = run(s) - with open("log.txt", "a") as f: - f.write(str(finalscore)+"\n") - while s.getch() == -1: - pass + if not finalscore: + finalscore = 0 + else: + while s.getch() == -1: + pass m1.play(s, executeguest=True, outerscore=finalscore, outergame="wordle") maze.menu.menu(s) - return \ No newline at end of file + return