-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPuzzle.py
More file actions
90 lines (77 loc) · 3.05 KB
/
Copy pathPuzzle.py
File metadata and controls
90 lines (77 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import helpers
import os
import sys
import random
from Board import Board
class Puzzle:
DIFFICULTY = {
'easy': 1,
'medium': 2,
'hard': 3,
'evil': 4
}
def __init__(self):
# Get Selenium Chrome Driver
self.browser = helpers.getChromeDriver()
# Standard sudoku is 9*9
# There seems to be unlimited levels but we will stick to 1 - 1000
def set(self, difficulty, level=random.randint(1, 1000), size=9):
self.difficulty = difficulty
self.level = level
self.size = size
self.showConfig()
# Load game into browser
self.browser.get(self.getUrl())
# Load board
self.board = Board(self.browser, self.size)
# Construct puzzle URL
# The parameters are confusing because they call difficulty level
# and level is called set_id
def getUrl(self):
# The main website uses iframe to embed the actual game
# Main url is http://websudoku.com
# but the iframe pulls from http://show.websudoku.com
return 'http://show.websudoku.com/?' \
+ 'level=' + str(self.difficulty) \
+ '&set_id=' + str(self.level)
# Show puzzle configuration
def showConfig(self):
print('Difficulty = ' + str(self.difficulty))
print('Level = ' + str(self.level))
# Let's play!
def play(self):
stack = []
(i, j) = self.board.emptyCells.popleft()
possibleValues = self.board.getCellPossibleValues(i, j)
print('Adding all possible values for cell (' + str(i) + ', ' +
str(j) + ') to stack: ' + ', '.join(map(str, possibleValues)))
for possibleValue in possibleValues:
stack.append((i, j, possibleValue))
while len(stack) > 0:
# Pick a possible value
(i, j, val) = stack.pop()
print('Trying ' + str(val) +
' for cell (' + str(i) + ', ' + str(j) + ')')
self.board.setCell(i, j, val)
if len(self.board.emptyCells) == 0:
break
# Recount empty cell on back trace
self.board.recountEmptyCells(i, j)
(next_i, next_j) = self.board.emptyCells.popleft()
possibleValues = self.board.getCellPossibleValues(
next_i, next_j)
# This candidate value is invalid
if len(possibleValues) == 0:
# Unset current cell and move to the next possible value
print('No possible value for cell (' +
str(next_i) + ', ' + str(next_j) + '), let\'s traceback.')
self.board.unsetCell(i, j)
# This candidate value looks good
else:
print('Adding all possible values for cell (' + str(next_i) + ', ' +
str(next_j) + ') to stack: ' + ', '.join(map(str, possibleValues)))
for possibleValue in possibleValues:
stack.append((next_i, next_j, possibleValue))
print('Done!')
self.board.print()
helpers.submit(self.browser)