Some quick and dirty threading to make http request non-blocking

This commit is contained in:
Joseph Ferano 2023-10-30 23:09:29 +07:00
parent 60deaed18a
commit dc03796275
3 changed files with 44 additions and 28 deletions

View File

@ -4,6 +4,8 @@ from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from typing import Set from typing import Set
import threading
import os import os
from websudoku import * from websudoku import *
@ -68,22 +70,34 @@ cursorSurface = pg.Surface((CURSOR_SIZE, CURSOR_SIZE), pg.SRCALPHA)
cursor = Cursor() cursor = Cursor()
input_method = InputMethod.FILL input_method = InputMethod.FILL
# TODO: We have to make this async
sudoku = get_sudoku_puzzle(Difficulty.EVIL)
# sudoku = get_sudoku_puzzle_test()
board = [] board = []
pencil_marks = []
sudoku = None
for i in range(81): data_lock = threading.Lock()
if sudoku.editmask[i] == 0:
board.append(Cell(sudoku.solution[i], True)) def data_callback(sudoku_data):
# Handle the data here, e.g., store it in a global variable
for i in range(81):
if sudoku_data.editmask[i] == 0:
board.append(Cell(sudoku_data.solution[i], True))
else: else:
board.append(Cell()) board.append(Cell())
pencil_marks = [] for i in range(81):
for i in range(81):
pm = PencilMark() if not board[i].given else None pm = PencilMark() if not board[i].given else None
pencil_marks.append(pm) pencil_marks.append(pm)
global sudoku
with data_lock:
sudoku = sudoku_data
def http_request_thread():
data = get_sudoku_puzzle(Difficulty.EVIL)
data_callback(data)
http_thread = threading.Thread(target=http_request_thread)
http_thread.start()
def draw_grid(): def draw_grid():
@ -214,7 +228,7 @@ while running:
if num.isdigit() and num != '0': if num.isdigit() and num != '0':
num = int(num) num = int(num)
idx = (cursor.row - 1) * 9 + cursor.col - 1 idx = (cursor.row - 1) * 9 + cursor.col - 1
if not board[idx].given: if board and not board[idx].given:
match input_method: match input_method:
case InputMethod.FILL: case InputMethod.FILL:
board[idx].value = num board[idx].value = num
@ -260,6 +274,8 @@ while running:
screen.fill('cornflower blue') screen.fill('cornflower blue')
draw_grid() draw_grid()
with data_lock:
if sudoku is not None:
draw_numbers() draw_numbers()
draw_cursor() draw_cursor()
draw_hud() draw_hud()

View File

@ -13,10 +13,18 @@
* DONE Add "Done" button * DONE Add "Done" button
* DONE Check if puzzle is complete * DONE Check if puzzle is complete
* DONE Improve pencil mark colors * DONE Improve pencil mark colors
* DONE Async http request
* TODO Show errors * TODO Show errors
* TODO Generalized button code
* TODO Pass difficulty through command line * TODO Pass difficulty through command line
* TODO Choose difficulty buttons
* TODO Button to load a new puzzle
* TODO Delete center pencil marks 1 num at a time
* TODO Toast on valid solve * TODO Toast on valid solve
* TODO Show the time it took * TODO Show the time it took
* TODO Save current game * TODO Save current game
* TODO Create a pip file * TODO Create a pip file
* TODO Help labels * TODO Show current input method
* TODO Show keybindings somehow
* TODO Pause button
* TODO Support undo

View File

@ -1,4 +1,4 @@
import http.client from urllib.request import urlopen
import re import re
from enum import Enum from enum import Enum
from dataclasses import dataclass from dataclasses import dataclass
@ -17,7 +17,7 @@ class Difficulty(Enum):
host = "five.websudoku.com" host = "five.websudoku.com"
def get_sudoku_puzzle_test(): async def get_sudoku_puzzle_test():
cheat = [ 1,7,6,5,9,4,3,2,8, cheat = [ 1,7,6,5,9,4,3,2,8,
3,5,8,6,7,2,9,1,4, 3,5,8,6,7,2,9,1,4,
2,9,4,8,1,3,6,5,7, 2,9,4,8,1,3,6,5,7,
@ -39,7 +39,6 @@ def get_sudoku_puzzle_test():
return Sudoku(cheat, editmask) return Sudoku(cheat, editmask)
def get_sudoku_puzzle(difficulty: Difficulty) -> Sudoku: def get_sudoku_puzzle(difficulty: Difficulty) -> Sudoku:
"""Makes a web request to websudoku.com to grab a sudoku puzzle """Makes a web request to websudoku.com to grab a sudoku puzzle
@ -49,22 +48,15 @@ def get_sudoku_puzzle(difficulty: Difficulty) -> Sudoku:
Returns: Returns:
A Sudoku object which contains the cheat and the editmask A Sudoku object which contains the cheat and the editmask
""" """
response = urlopen("https://five.websudoku.com/?level=4")
conn = http.client.HTTPSConnection(host)
conn.request("GET", "/?level=2")
response = conn.getresponse()
if response.status == 200: if response.status == 200:
html_content = response.read().decode('utf-8') html_content = response.read().decode('utf-8')
# print(html_content)
for line in html_content.split('\n'): for line in html_content.split('\n'):
if "editmask" in line: if "editmask" in line:
editmask = [ int(n) for n in re.findall(r'\d', line) ] editmask = [ int(n) for n in re.findall(r'\d', line) ]
if "var cheat" in line: if "var cheat" in line:
cheat = [ int(n) for n in re.findall(r'\d', line) ] cheat = [ int(n) for n in re.findall(r'\d', line) ]
conn.close()
return Sudoku(cheat, editmask) return Sudoku(cheat, editmask)
else: else:
print("Error getting sudoku puzzle:", response.status, response.reason) print("Error getting sudoku puzzle:", response.status, response.reason)