Table of contents
Introduction
The Eight Queens puzzle is a classic combinatorial problem. The task is to arrange eight queens on an 8x8 chessboard without any two queens threatening each other. This means that no two queens can be in the same row, column, or diagonal.
In this blog post, I will share my solution for visualizing the Eight Queens problem using Pygame, a popular module in Python for creating games and graphical applications.
The Code
I used the Pygame module to draw the chessboard and represent the queens with an image, making it visually appealing and easy to understand.
import pygame
import sys
# Define constants
SIZE = 50
N = 8
# Initialize pygame
pygame.init()
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Create the screen
screen = pygame.display.set_mode((N * SIZE, N * SIZE))
pygame.display.set_caption('Eight Queens Problem')
# Draw the board
def draw_board(queens):
queen_img = pygame.image.load('queen.jpg')
queen_img = pygame.transform.scale(queen_img, (SIZE, SIZE))
# save queen_img as image
pygame.image.save(queen_img, 'queen_updated.jpg')
for i in range(N):
for j in range(N):
if (i + j) % 2 == 0:
color = WHITE
else:
color = BLACK
pygame.draw.rect(screen, color, (i*SIZE, j*SIZE, SIZE, SIZE))
if (j + 1) in queens and queens[j + 1] == i + 1:
# use the queen image instead of a circle
screen.blit(queen_img,
(int(i * SIZE), int(j * SIZE)))
col = [0] * (N + 1)
def promising(i):
k = 1
promising = True
while k < i and promising:
if col[i] == col[k] or abs(col[i] - col[k]) == i - k:
promising = False
k += 1
return promising
def solve(i):
if promising(i):
if i == N:
draw_board(col)
pygame.display.flip()
pygame.time.wait(500) # Display each solution for half a second
else:
for j in range(1, N + 1):
col[i + 1] = j
solve(i + 1)
def main():
solve(0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
Key Highlights
Initialization: Pygame is initialized, and constants like SIZE (representing the size of each cell) and N (the dimension of the board) are set.
Draw the Board: The
draw_board()
function draws the chessboard and places the queens. We load a queen image, scale it to our desired SIZE, and then save the resized image asqueen_updated.jpg
.Backtracking Algorithm: The
solve()
function uses a backtracking algorithm to explore possible positions for the queens. If a suitable job is detected, the board is shown briefly for 0.5 seconds.Promising Function: The
promising()
function checks if the current position of the queen is safe or not.Main Loop: The program loops after displaying all solutions and waits for the user to close the window.
Conclusion
The Eight Queens problem is an intriguing puzzle that has fascinated many. One can appreciate the beauty of the problem and see its solutions with this Pygame-based visualization. The images for queens add a touch of realism and make the answers more visually appealing.