Skip to content

Commit

Permalink
Merge pull request #7 from Benny1143/tm-upgrade
Browse files Browse the repository at this point in the history
Merge in tm and om upgrade
  • Loading branch information
Benny1143 authored Dec 8, 2022
2 parents 39412ca + 1183ccf commit 811fbd1
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 76 deletions.
70 changes: 34 additions & 36 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def main(self) -> None:
Enter your name (1-7 characters): '''
while True:
# Restrict name input to 7 characters
name = self.print(page_string, True)
name = self.input(page_string)
if len(name) > 7 or len(name) == 0:
self.set_error("Invalid String Length")
continue
Expand All @@ -63,24 +63,25 @@ def switch_dual():
if score:
play_string += f" (scored {score}pt)"

om = OptionManager()
om.add_option("1", play_string, self.game)
om.add_option("2", f"Dual Mode ({self.dual_mode})", switch_dual)
om.add_option("3", "Select Stage", self.stage_selection)
om = OptionManager({
play_string: self.game,
f"Dual Mode ({self.dual_mode})": switch_dual,
"Select Stage": self.stage_selection
})

# Check if user has played stage 1 & 2
if map_score_dict.get("1") and map_score_dict.get("2"):
self.unlocked = True
om.add_option("4", "Map Creator", self.map_creator)
om.add_option("Map Creator", self.map_creator)

om.add_option("0", "Exit", exit)
om.add_option("Exit", exit, "0")

options_string = om.option_printer()

self.refresh_highscore()

string = title + hs_string + options_string
option = om.input(string, self.print, self.set_error)
option = om.input(string, self.input, self.set_error)
om.get_option(option)()

def game(self) -> None:
Expand Down Expand Up @@ -113,8 +114,7 @@ def print_map(map: Map, last_line: bool = False) -> None:
new_map_str = "\n".join(tmp_map_str)
##

self.print(
"\n".join([title, new_map_str, control_str]), last_line, False)
self.print("\n".join([title, new_map_str, control_str]), last_line)
self.clear()
print_map(map)

Expand Down Expand Up @@ -200,21 +200,21 @@ def map_creator(self) -> None:
map_ids = sorted(list(map_ids))

om = OptionManager()
om.add_option(0, "**New Map**")

i = 1
for map_id in map_ids:
om.add_option(i, map_id)
i += 1
om.add_option(map_id)

om.add_option("**New Map**", "0", "0")

options_string = om.option_printer("Select Map")
option = om.input(options_string, self.print, self.set_error)
option = om.input(options_string, self.input, self.set_error)

characters = {}
winning_conditions = {}

if option == "0":
while True:
map_id = self.print("Enter new map name: ", True)
map_id = self.input("Enter new map name: ")
# Check if can have filename
if map_id in map_ids_copy:
self.set_error("Filename has been used")
Expand Down Expand Up @@ -249,13 +249,13 @@ def get_map_wc_string():
wa - add winninng conditions
wd - delete winning conditions
Enter Action: """
option = self.print(
f"Map Name: {map_id}\n" + map_string + input_string, True)
option = self.input(
f"Map Name: {map_id}\n{map_string}{input_string}")
if option == "a":
while True:
map_string = get_map_wc_string()
qn1 = "\nEnter a chinese character (e - exit): "
chi_char = self.print(map_string + qn1, True)
chi_char = self.input(map_string + qn1)

if chi_char == "e":
break
Expand All @@ -267,15 +267,15 @@ def get_map_wc_string():

# Ask for coordinate inputs
qn2 = "enter the x coordinate: "
x_cor = int(self.print(map_string + qn2, True))
x_cor = int(self.input(map_string + qn2))
if x_cor <= 0 or x_cor > 5:
self.set_error("Invalid x_cor not between 1-5")
continue

map_string += qn2 + str(x_cor) + "\n"

qn3 = "enter the y coordinate: "
y_cor = int(self.print(map_string + qn3, True))
y_cor = int(self.input(map_string + qn3))
if y_cor <= 0 or y_cor > 5:
self.set_error("Invalid y_cor not between 1-5")
continue
Expand All @@ -298,7 +298,7 @@ def get_map_wc_string():
while True:
map_string = get_map_wc_string()
question = "\nChinese Character to be deleted (e - exit): "
cc = self.print(map_string + question, True)
cc = self.input(map_string + question)
if cc == "e":
break
# Check if cc exist
Expand All @@ -314,24 +314,24 @@ def get_map_wc_string():
elif option == "wa":
map_string = get_map_wc_string()
qn1 = "\nEnter two Chinese characters (e - exit): "
win_con = self.print(map_string + qn1, True)
win_con = self.input(map_string + qn1)
if len(win_con) != 2 or win_con == "e":
continue

map_string += qn1 + win_con
qn2 = "\nEnter English translation: "
eng = self.print(map_string + qn2, True)
eng = self.input(map_string + qn2)

map_string += qn2 + eng
qn3 = "\nEnter points: "
pts = self.print(map_string + qn3, True)
pts = self.input(map_string + qn3)

winning_conditions[win_con] = WinningCondition(eng, pts)
elif option == "wd":
while True:
map_string = get_map_wc_string()
cc = self.print(
map_string + "\nWinning Condition to be deleted (e - exit): ", True)
cc = self.input(
f"{map_string}\nWinning Condition to be deleted (e - exit): ")
if cc == "e":
break
if cc in winning_conditions:
Expand Down Expand Up @@ -376,8 +376,6 @@ def get_user_map_dic(self):
if values is None:
return score_dict
if type(values) == list:
for i in range(1, len(values)):
print(values[i])
values = zip(get_user_map_scores(
self.name).shallow().get().val(), values[1:])
for key, score in values:
Expand All @@ -394,22 +392,22 @@ def get_score_string(map_id):
score = score_dict.get(map_id)
return f" (scored {score}pt)" if score else ""

om = OptionManager()
om.add_option("1", "Stage 1" + get_score_string("1"), "1")
om.add_option("2", "Stage 2" + get_score_string("2"), "2")
om = OptionManager({
"Stage 1" + get_score_string("1"): "1",
"Stage 2" + get_score_string("2"): "2"
})

if self.unlocked:
map_ids = get_all_map_id()
map_ids.remove("1")
map_ids.remove("2")
map_ids = sorted(list(map_ids))
i = 3

for map_id in map_ids:
om.add_option(i, map_id + get_score_string(map_id), map_id)
i += 1
om.add_option(map_id + get_score_string(map_id), map_id)

options_string = om.option_printer("Select Stage")
option = om.input(options_string, self.print, self.set_error)
option = om.input(options_string, self.input, self.set_error)
option = om.get_option(option)
self.map_id = option

Expand Down
47 changes: 30 additions & 17 deletions om.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,54 @@


class Option:
def __init__(self, option, name, function):
def __init__(self, option: str, name: str, value: any):
self.option = option
self.name = name
self.function = function
self.value = value

def __str__(self) -> str:
return f"{self.option:>4} {self.name}"


class OptionManager:
def __init__(self):
def __init__(self, option_dict: dict = {}):
self.counter = 1
self._options = []
self._dict_options = {}
pass
for name, value in option_dict.items():
self.add_option(name, value)

def add_option(self, option, name, function = None):
if function is None:
function = name
option = str(option)
self._options.append(Option(option, name, function))
self._dict_options[option] = function
def add_option(self, name: str, value: any = None, option: str = None) -> None:
if value is None:
value = name
option = option if option else str(self.counter)
self._options.append(Option(option, name, value))
self._dict_options[option] = value
self.counter += 1

def option_printer(self, question: str = "Enter Option") -> str:
ls = list(map(lambda option: (option.option, option.name), self._options))
return "{color}Options:\n{options_string}\n{question}: {white}".format(
options_string='\n'.join(
f"{option:>4} {name}" for option, name in ls),
options_string = ""
for option in self._options:
options_string += str(option) + "\n"
return "{color}Options:\n{options_string}{question}: {white}".format(
options_string=options_string,
color=colors.Yellow, white=colors.White,
question=question)

def get_option(self, option):
def get_option(self, option: str):
if option in self._dict_options:
return self._dict_options.get(option)

def input(self, string, print_function, error_function):
def input(self, string, input_function, error_function):
while True:
option = print_function(string, True)
option = input_function(string)
if option in self._dict_options:
return option
else:
error_function("Invalid Option")


if __name__ == "__main__":
om = OptionManager({"Test": 1})
om.add_option("Exit", "0", "0")
print(om.option_printer())
45 changes: 22 additions & 23 deletions tm.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ class TerminalManager():
def __init__(self) -> None:
self.error = None
self.length = 18
# Change inplace to True to print inplace
self.inplace = True
self.inplace = True # Change inplace to True to print inplace
if self.inplace:
print("\n"*self.length, flush=True)

Expand All @@ -17,37 +16,37 @@ def clear(self):
print(f"\x1B[{self.length}A" + "\033[K\n" *
(self.length), end="", flush=True)

def print(self, text: str, get_input: bool = False, clear_screen: bool = True):
def print(self, text: str, get_input: bool = False) -> str | None:
length = self.length
if self.error and self.inplace:
length -= 1
text_ls = text.split("\n")
len_text = len(text_ls)
if not self.inplace and self.error:
if get_input:
# print one line above input string
text = "\n".join(text_ls[:-1] + [self.error, text_ls[-1]])
else:
# print above all the text
text = f"{self.error}\n{text}"
self.error = None
if len_text > length:
raise Exception("The print string is longer than space assigned")
if self.inplace and clear_screen:
text = "\033[K\n"*(length - len_text) + \
"\033[K\n".join(text.split("\n")) + "\033[K"
else:
text = "\n"*(length - len_text) + text
raise Exception(
f"{text}\n\nThe print string is longer than space assigned")

if self.inplace:
text = f"\x1B[{length}A" + text
text = "\x1B[{length}A{empty_space}{text}\033[K".format(
length=length,
empty_space="\033[K\n"*(length - len_text),
text="\033[K\n".join(text.split("\n")))
print(self.error if self.error else "\033[K", end="", flush=True)
else:
if self.error:
print(self.error, end="", flush=True)
self.error = None
else:
print("\033[K", end="", flush=True)
if get_input:
text = "\n".join(text_ls[:-1] + [self.error, text_ls[-1]])
else:
text = f"{self.error}\n{text}"
text = "\n"*(length - len_text) + text

self.error = None
if get_input:
return input(text)
print(text, flush=True)

def set_error(self, error: str):
def input(self, text: str) -> str:
return self.print(text, True)

def set_error(self, error: str) -> None:
self.error = colors.Red + error + colors.White + "\r"

0 comments on commit 811fbd1

Please sign in to comment.