RosettaCodeData/Task/N-queens-problem/Processing-Python-mode/n-queens-problem.processing-py

29 lines
738 B
Plaintext

from itertools import permutations, product
n = 8
cols = range(n)
i = 0 # solution shown
solutions = [vec for vec in permutations(cols)
if n == len(set(vec[i] + i for i in cols))
== len(set(vec[i] - i for i in cols))]
def setup():
size(400, 400)
textAlign(CENTER, CENTER)
textFont(createFont("DejaVu Sans", 44))
def draw():
background(0)
w = width / n
for x, y in product(range(n), range(n)):
fill(255 * ((x + y) % 2))
square(x * w, y * w, w)
if solutions[i][y] == x:
fill(255 - 255 * ((x + y) % 2))
text(u'♕', w / 2 + x * w, w / 3 + y * w)
def keyPressed(): # show next solution
global i
i = (i + 1) % len(solutions)