'I'm trying to write a checkers game, but I cannot get the pieces to initialise on the checkerboard
I've managed to initialise the board using a class, but I've been struggling to get the pieces to initialise on the black tiles.
I've attempted using create_oval to make the pieces and also tried to use create_image, but each time I can only get one piece to appear on the board.
I have the following code for initialising the board. I hope someone can help me get the pieces to initialise on this board.
from tkinter import Canvas, PhotoImage
def create_black_piece(canvas, x, y, radius):
x0 = x - radius
y0 = y - radius
x1 = x + radius
y1 = y + radius
return canvas.create_oval(x0, y0, x1, y1)
class Board(Canvas):
"""Class to create a board object"""
def __init__(self):
super().__init__()
self.square = None
self.create_board()
def create_row_black(self, row):
"""Creates a row with a light tile in the left-most position"""
for n in range(8):
self.square = Canvas(width=50, height=50)
self.square.grid(row=row, column=n)
if n % 2 == 0:
self.square.config(bg="tan", highlightthickness=0)
else:
self.square.config(bg="black", highlightthickness=0)
def create_row_red(self, row):
"""Creates a row with a black tile in the left-most position"""
for n in range(8):
self.square = Canvas(width=50, height=50)
self.square.grid(row=row, column=n)
if n % 2 == 0:
self.square.config(bg="black", highlightthickness=0)
else:
self.square.config(bg="tan", highlightthickness=0)
black_piece = PhotoImage(file="black_piece.png")
self.square.create_image(25, 25, image=black_piece)
def create_board(self):
"""Creates the full checkers board, with each row alternating to create the checkered pattern"""
for i in range(8):
if i % 2 == 0:
self.create_row_black(row=i)
else:
self.create_row_red(row=i)
Is it wise to be using OOP to initialise the pieces and the board, or should I have all of the initialisation code in main?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
