Skip to content

Commit 196d23d

Browse files
committed
WIDGETS!!11111!!!!
1 parent 1f95daf commit 196d23d

File tree

2 files changed

+122
-27
lines changed

2 files changed

+122
-27
lines changed

core/database_handler.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import json
22
from typing import Any
33
import requests
4+
from PIL import Image
5+
import io
6+
7+
# pylint: disable=W0718
48

59

610
class StatusCodeNot200(Exception): ...
@@ -46,3 +50,44 @@ def get_database(source: str, error_handler: Any, mode: str = 'online') -> dict
4650

4751
return error_handler(8, f"An unknown error happened when trying to access database located at:\n\n{source}\n\nMake sure the URL is correct.") # [!] Unknown error
4852

53+
54+
def get_image(source: str, handler: Any, **kw):
55+
_ = kw.pop('url', None)
56+
_ = kw.pop('timeout', None)
57+
_ = kw.pop('allow_redirects', None)
58+
del _
59+
60+
try:
61+
response = requests.get(url=source, allow_redirects=False, timeout=1.3)
62+
63+
if response.status_code != 200:
64+
raise StatusCodeNot200(f"status code is {response.status_code} and not 200")
65+
66+
img_bytes: bytes | bytearray = response.content
67+
68+
except StatusCodeNot200:
69+
return handler(31, f"The Status Code of URL...\n\n{source}\n\n...is not 200, meaning DoomMapGuesser is unable to collect the image.")
70+
71+
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
72+
return handler(24, "Unable to connect via HTTP. This might be caused by a bad Internet connection.")
73+
74+
except (TimeoutError, requests.exceptions.Timeout):
75+
return handler(21, f"The image's URL...\n\n({source})\n\n...took too long to respond to the GET request.")
76+
77+
except (requests.exceptions.InvalidURL, requests.exceptions.InvalidSchema, requests.exceptions.MissingSchema):
78+
return handler(27, f"The URL...\n\n({source})\n\n...is invalid.")
79+
80+
except Exception as e:
81+
return handler(28, f"Unknown error when trying to obtain the chosen image with URL:\n\n{source}\n\nError Details:\n{e}")
82+
83+
try:
84+
image_data = io.BytesIO(img_bytes)
85+
image = Image.open(image_data, "r")
86+
87+
except ValueError as e:
88+
return handler(26, f"The collected image is not in its RAW form or isn't even an image, therefore cannot be used by DoomMapGuesser.\n\nError Details:\n{e}")
89+
90+
except Exception as e:
91+
return handler(28, f"Unknown error when trying to read the chosen image with URL with PIL:\n\n{source}\n\nError Details:\n{e}")
92+
93+
return image

main.py

Lines changed: 77 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@
1010
import simple_webbrowser
1111
from PIL import ImageTk, Image
1212
from core import level_db, utils_constants
13-
from core.database_handler import get_database
13+
from core.database_handler import get_database, get_image
1414
from core.settings import SettingsObject
1515
import math
16-
import io
1716
import requests
1817
import json
1918

@@ -324,7 +323,7 @@ class __InvalidButtonAction(Exception): ...
324323
PH_DATA: list[str] | None = None
325324
POINTS: int = 0
326325
GEN_SF: int = 0
327-
CUR_IMAGE = None
326+
CUR_IMG_LINK = None
328327

329328

330329
class Database:
@@ -772,9 +771,7 @@ def add_database(source: str, *_, index: int | None = None) -> Database | bool:
772771
DATABASES[0].use()
773772

774773

775-
def generate_new_screenshot(**kw) -> None:
776-
global CUR_DATA, GEN_SF
777-
774+
def generate_new_map_data(**kw) -> list[str] | int:
778775
db: Database = kw.get('database', CUR_DB)
779776

780777
warrens: list[str] | None = db.warrens
@@ -783,18 +780,15 @@ def generate_new_screenshot(**kw) -> None:
783780
# [*] 1st Case: WARRENS and HELL_KEEP are undefined
784781
# [i] this code assumes Database.verify() has been ran
785782
if warrens is None and hell_keep is None:
786-
GEN_SF += 4
787-
CUR_DATA = db.generate()
788-
return
783+
return db.generate()
789784

790785
# [*] 2nd Case: WARRENS and HELL_KEEP can be both shown - in this case, we don't need to do anything
791786
if settings.exclude_rule_for_e3m1_e3m9 == 'both':
792-
GEN_SF += 4
793-
CUR_DATA = db.generate()
794-
return
787+
return db.generate()
795788

796789
is_warrens = False
797790
is_hk = False
791+
data = None
798792

799793
# [*] 3rd Case: we loop around 20 times, which should be enough to get rid of WARRENS and HELL_KEEP generated data
800794
# [i] ofc that if we get valid data before the last loop, we end it, duh?!
@@ -823,16 +817,21 @@ def generate_new_screenshot(**kw) -> None:
823817
if is_warrens is False:
824818
break
825819

826-
case _:
820+
case None | 'null' | 'none':
827821
if is_hk is False and is_warrens is False:
828822
break
823+
824+
case _:
825+
data = None
826+
continue
827+
828+
if data is None:
829+
return handle_error(52, "Failed to get an image that respects the chosen exclusion rule for HELL_KEEP and WARRENS.")
829830

830-
GEN_SF += 4
831-
CUR_DATA = data
832-
return
831+
return data
833832

834833

835-
def generate_new_image(**kw) -> str:
834+
def generate_new_image(data: list[str], **kw) -> str:
836835
"""
837836
# generate_new_image
838837
@@ -841,21 +840,65 @@ def generate_new_image(**kw) -> str:
841840
:param database: overwrite for CUR_DB *(should be of type Database)*
842841
843842
Returns:
844-
str: the link to the new image *(it also saves it as a global so it might not be necessary to get the returned value)*
843+
str: the link to the new image
845844
"""
846845

847-
global CUR_IMAGE
848-
849846
db: Database = kw.get('database', CUR_DB)
850847

851-
x = random.choice(db.structure[CUR_DATA[0]][CUR_DATA[1]][CUR_DATA[2]]['screenshots'].remove(CUR_IMAGE))
852-
CUR_IMAGE = x
853-
del x
848+
x = random.choice(db.structure[data[0]][data[1]][data[2]]['screenshots'].remove(CUR_IMG_LINK))
849+
return x
850+
851+
852+
def get_selected_image(img_link: str, **kw) -> Image.Image | int:
853+
return get_image(img_link, handle_error, **kw)
854+
855+
856+
def generate_new_round(*_, first: dict[str, Any] = None, second: dict[str, Any] = None, third: dict[str, Any] = None):
857+
global CUR_DATA, GEN_SF, CUR_IMG_LINK
858+
859+
# [<] ik one letter vars are not good but screw it
860+
if first is None:
861+
a = generate_new_map_data()
862+
863+
else:
864+
a = generate_new_map_data(**first)
865+
866+
if isinstance(a, int):
867+
return # [!?] Cancel the operation, since an error happened
868+
869+
if second is None:
870+
b = generate_new_image(a)
871+
872+
else:
873+
b = generate_new_image(b, **second)
874+
875+
if third is None:
876+
c = get_selected_image(b)
854877

855-
return CUR_IMAGE
878+
else:
879+
c = get_selected_image(b, **third)
880+
881+
GEN_SF += 4
882+
CUR_DATA = a
883+
CUR_IMG_LINK = b
884+
PLAY_ITEMS.cur_img = resize_image(c, settings.image_width, settings.use_width_as_height, settings.image_ratio)
885+
886+
887+
def update_game_widgets():
888+
return handle_error(11, "Not Implemented!")
856889

857890

858891
def setup_play_screen():
892+
global CUR_DATA, POINTS, GEN_SF, CUR_IMG_LINK, PH_DATA
893+
894+
PH_DATA = [random.randint(10, 99) for _ in range(3)]
895+
CUR_DATA = PH_DATA.copy()
896+
897+
PLAY_ITEMS.selected_game = tk.StringVar(root, list(CUR_DB.structure.keys())[0])
898+
PLAY_ITEMS.selected_episode = tk.StringVar(root, list(CUR_DB.structure[PLAY_ITEMS.selected_game].keys())[0])
899+
PLAY_ITEMS.selected_map = tk.StringVar(root, list(CUR_DB.structure[PLAY_ITEMS.selected_game][PLAY_ITEMS.selected_episode].keys())[0])
900+
PLAY_ITEMS.selected_secrets = tk.IntVar(root, 0)
901+
859902
PLAY_ITEMS.heading = ttk.Label(PLAY_ITEMS, text='Play', font=HEADING1)
860903
PLAY_ITEMS.f1 = ttk.Frame(PLAY_ITEMS)
861904
PLAY_ITEMS.f2 = ttk.Frame(PLAY_ITEMS)
@@ -884,13 +927,20 @@ def setup_play_screen():
884927
PLAY_ITEMS.img_widget = ttk.Button(PLAY_ITEMS.f1, image=PLAY_ITEMS.cur_img, command=lambda:
885928
send_dialog('warning', 'TODO', 'Sadly, not done yet.')) # TODO
886929

887-
PLAY_ITEMS.generation_butt = ttk.Button(PLAY_ITEMS.f2, text="Generate", command=lambda:
888-
send_dialog('warning', 'TODO', 'Sadly, not done yet.')) # TODO
930+
PLAY_ITEMS.generation_butt = ttk.Button(PLAY_ITEMS.f2, text="Generate", command=generate_new_round)
889931

890932
PLAY_ITEMS.guessing_butt = ttk.Button(PLAY_ITEMS.f2, text='Guess', command=lambda:
891933
send_dialog('warning', 'TODO', 'Sadly, not done yet.')) # TODO
892934

893-
# TODO: after this it's just the game, episode, map and thingies
935+
936+
PLAY_ITEMS.game_ch = ttk.OptionMenu(PLAY_ITEMS.f5, PLAY_ITEMS.selected_game, PLAY_ITEMS.selected_game.get(), *list(CUR_DB.structure.keys()), command=lambda:
937+
update_game_widgets('game'))
938+
PLAY_ITEMS.episode_ch = ttk.OptionMenu(PLAY_ITEMS.f6, PLAY_ITEMS.selected_episode, PLAY_ITEMS.selected_episode.get(), *list(CUR_DB.structure[PLAY_ITEMS.selected_game].keys()), command=lambda:
939+
update_game_widgets('episode'))
940+
PLAY_ITEMS.map_ch = ttk.OptionMenu(PLAY_ITEMS.f7, PLAY_ITEMS.selected_map, PLAY_ITEMS.selected_map.get(), *list(CUR_DB.structure[PLAY_ITEMS.selected_game][PLAY_ITEMS.selected_episode].keys()), command=lambda:
941+
update_game_widgets('map'))
942+
943+
PLAY_ITEMS.secrets_plus = None # TODO
894944

895945

896946
# [*] Sidebar Buttons

0 commit comments

Comments
 (0)