write code for checkers game in python using pygame with king piece
- User
write code for checkers game in python using pygame with king piece
- Assistant
write code for checkers game in python using pygame with king piece
Certainly! Below is a basic implementation of a checkers game in Python using Pygame, which includes king piece functionality. This code provides a graphical interface where two players can play checkers against each other on the same computer.
Note: This is a simplified version of the game and may not cover every edge case or include AI for playing against the computer. You can expand upon it to add more features as needed.
First, make sure you have Pygame installed. If not, you can install it using:
pip install pygame
Now, here's the code:
import pygame
import sys
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 800
ROWS, COLS = 8, 8
SQUARE_SIZE = WIDTH // COLS
# RGB Color Codes
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREY = (128, 128, 128)
BLUE = (0, 0, 255)
# Crown image for king pieces
CROWN = pygame.transform.scale(pygame.image.load('crown.png'), (44, 25))
# Create the window
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Checkers')
class Piece:
PADDING = 15
OUTLINE = 2
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
self.king = False
if self.color == RED:
self.direction = -1 # Red pieces move upwards
else:
self.direction = 1 # White pieces move downwards
self.x = 0
self.y = 0
self.calc_pos()
def calc_pos(self):
"""Calculate the x and y pixel position of the piece."""
self.x = SQUARE_SIZE * self.col + SQUARE_SIZE // 2
self.y = SQUARE_SIZE * self.row + SQUARE_SIZE // 2
def make_king(self):
"""Make this piece a king."""
self.king = True
def draw(self, win):
"""Draw the piece on the board."""
radius = SQUARE_SIZE // 2 - self.PADDING
pygame.draw.circle(win, GREY, (self.x, self.y), radius + self.OUTLINE) # Draw the outline
pygame.draw.circle(win, self.color, (self.x, self.y), radius) # Draw the piece
if self.king:
win.blit(CROWN, (self.x - CROWN.get_width() // 2, self.y - CROWN.get_height() // 2)) # Draw the crown
def move(self, row, col):
"""Move the piece to a new row and column."""
self.row = row
self.col = col
self.calc_pos()
class Board:
def __init__(self):
self.board = []
self.red_left = self.white_left = 12 # Number of pieces left for each player
self.red_kings = self.white_kings = 0
self.create_board()
def draw_squares(self, win):
"""Draw the checkerboard pattern."""
win.fill(BLACK)
for row in range(ROWS):
for col in range(row % 2, COLS, 2):
pygame.draw.rect(win, GREY, (row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def create_board(self):
"""Initialize the board with pieces."""
for row in range(ROWS):
self.board.append([])
for col in range(COLS):
if (row + col) % 2 == 0:
self.board[row].append(0) # Empty square
else:
if row < 3:
piece = Piece(row, col, WHITE)
self.board[row].append(piece)
elif row > 4:
piece = Piece(row, col, RED)
self.board[row].append(piece)
else:
self.board[row].append(0)
def draw(self, win):
"""Draw the board and all pieces."""
self.draw_squares(win)
for row in range(ROWS):
for col in range(COLS):
piece = self.board[row][col]
if piece != 0:
piece.draw(win)
def move(self, piece, row, col):
"""Move a piece and manage king conversion."""
self.board[piece.row][piece.col], self.board[row][col] = 0, piece
piece.move(row, col)
if row == ROWS - 1 or row == 0:
piece.make_king()
if piece.color == WHITE:
self.white_kings += 1
else:
self.red_kings += 1
def get_piece(self, row, col):
"""Get the piece at a specific position."""
return self.board[row][col]
def remove(self, pieces):
"""Remove captured pieces from the board."""
for piece in pieces:
self.board[piece.row][piece.col] = 0
if piece != 0:
if piece.color == RED:
self.red_left -= 1
else:
self.white_left -= 1
def winner(self):
"""Check if there is a winner."""
if self.red_left <= 0:
return WHITE
elif self.white_left <= 0:
return RED
return None
def get_valid_moves(self, piece):
"""Get all valid moves for a piece."""
moves = {}
left = piece.col - 1
right = piece.col + 1
row = piece.row
if piece.color == RED or piece.king:
moves.update(self._traverse_left(row - 1, max(row - 3, -1), -1, piece.color, left))
moves.update(self._traverse_right(row - 1, max(row - 3, -1), -1, piece.color, right))
if piece.color == WHITE or piece.king:
moves.update(self._traverse_left(row + 1, min(row + 3, ROWS), 1, piece.color, left))
moves.update(self._traverse_right(row + 1, min(row + 3, ROWS), 1, piece.color, right))
return moves
def _traverse_left(self, start, stop, step, color, left, skipped=[]):
"""Traverse diagonally to the left to find valid moves."""
moves = {}
last = []
for r in range(start, stop, step):
if left < 0:
break
current = self.board[r][left]
if current == 0:
if skipped and not last:
break
elif skipped:
moves[(r, left)] = last + skipped
else:
moves[(r, left)] = last
if last:
if step == -1:
row = max(r - 3, -1)
else:
row = min(r + 3, ROWS)
moves.update(self._traverse_left(r + step, row, step, color, left - 1, skipped=last))
moves.update(self._traverse_right(r + step, row, step, color, left + 1, skipped=last))
break
elif current.color == color:
break
else:
last = [current]
left -=1
return moves
def _traverse_right(self, start, stop, step, color, right, skipped=[]):
"""Traverse diagonally to the right to find valid moves."""
moves = {}
last = []
for r in range(start, stop, step):
if right >= COLS:
break
current = self.board[r][right]
if current == 0:
if skipped and not last:
break
elif skipped:
moves[(r, right)] = last + skipped
else:
moves[(r, right)] = last
if last:
if step == -1:
row = max(r - 3, -1)
else:
row = min(r + 3, ROWS)
moves.update(self._traverse_left(r + step, row, step, color, right -1, skipped=last))
moves.update(self._traverse_right(r + step, row, step, color, right +1, skipped=last))
break
elif current.color == color:
break
else:
last = [current]
right +=1
return moves
class Game:
def __init__(self, win):
self._init()
self.win = win
def update(self):
"""Update the game display."""
self.board.draw(self.win)
self.draw_valid_moves(self.valid_moves)
pygame.display.update()
def _init(self):
"""Initialize or reset the game state."""
self.selected = None
self.board = Board()
self.turn = RED
self.valid_moves = {}
def reset(self):
"""Reset the game."""
self._init()
def select(self, row, col):
"""Select a piece or move to a position."""
if self.selected:
result = self._move(row, col)
if not result:
# If move was invalid, deselect and try selecting another piece
self.selected = None
self.select(row, col)
piece = self.board.get_piece(row, col)
if piece != 0 and piece.color == self.turn:
self.selected = piece
self.valid_moves = self.board.get_valid_moves(piece)
return True
return False
def _move(self, row, col):
"""Move the selected piece to a new position."""
piece = self.board.get_piece(row, col)
if self.selected and (row, col) in self.valid_moves:
self.board.move(self.selected, row, col)
skipped = self.valid_moves[(row, col)]
if skipped:
self.board.remove(skipped)
self.change_turn()
else:
return False
return True
def draw_valid_moves(self, moves):
"""Highlight valid moves for the selected piece."""
for move in moves:
row, col = move
pygame.draw.circle(self.win, BLUE, (col * SQUARE_SIZE + SQUARE_SIZE // 2,
row * SQUARE_SIZE + SQUARE_SIZE // 2), 15)
def change_turn(self):
"""Switch the turn to the other player."""
self.valid_moves = {}
if self.turn == RED:
self.turn = WHITE
else:
self.turn = RED
def winner(self):
"""Get the winner of the game, if any."""
return self.board.winner()
def get_row_col_from_mouse(pos):
"""Convert mouse position to board row and column."""
x, y = pos
row = y // SQUARE_SIZE
col = x // SQUARE_SIZE
return row, col
def main():
"""Main game loop."""
run = True
clock = pygame.time.Clock()
game = Game(WIN)
while run:
clock.tick(60) # Control the game's frame rate (FPS)
if game.winner() is not None:
winner_color = "Red" if game.winner() == RED else "White"
print("Winner:", winner_color)
run = False # End the game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # Quit the game
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
row, col = get_row_col_from_mouse(pos)
game.select(row, col)
game.update()
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
Important Notes:
Crown Image:
crown.png image in the same directory for displaying on king pieces.crown.png.Ending the Game:
Turn Management:
Game class handles turn management, allowing two players to play on the same computer.Valid Moves Highlighting:
Movement and Capturing:
King Pieces:
Explanation of the Code Structure:
Constants and Initialization:
Piece Class:
make_king method upgrades a piece to a king.Board Class:
get_valid_moves method calculates all possible moves for a selected piece.Game Class:
Main Game Loop (main function):
To Run the Game:
Ensure Pygame is Installed:
pip install pygame
Save the Code:
checkers.py.Add a Crown Image (Optional):
crown.png image in the same directory as your checkers.py file.Run the Script:
python checkers.py
Potential Enhancements:
AI Opponent:
User Interface Improvements:
Sound Effects:
Graphics Enhancements:
Legal Move Enforcement:
Multiple Jumps in One Turn:
Feel free to modify the code to suit your needs or ask if you need further assistance or specific features added!
Not yet included in a published release.