pydoku/websudoku.py

50 lines
1.2 KiB
Python

import http.client
import re
from enum import Enum
from dataclasses import dataclass
from typing import List
@dataclass
class Sudoku:
cheat: List[int]
editmask: List[int]
class Difficulty(Enum):
EASY = 1
MEDIUM = 2
HARD = 3
EVIL = 4
host = "five.websudoku.com"
def get_sudoku_puzzle(difficulty: Difficulty) -> Sudoku:
"""Makes a web request to websudoku.com to grab a sudoku puzzle
Args:
difficulty: Choose between easy, medium, hard, or evil
Returns:
A Sudoku object which contains the cheat and the editmask
"""
conn = http.client.HTTPSConnection(host)
conn.request("GET", "/?level=4")
response = conn.getresponse()
if response.status == 200:
html_content = response.read().decode('utf-8')
# print(html_content)
for line in html_content.split('\n'):
if "editmask" in line:
editmask = [ int(n) for n in re.findall(r'\d', line) ]
if "var cheat" in line:
cheat = [ int(n) for n in re.findall(r'\d', line) ]
conn.close()
return Sudoku(cheat, editmask)
else:
print("Error getting sudoku puzzle:", response.status, response.reason)
return None