73 lines
1.9 KiB
Python
73 lines
1.9 KiB
Python
|
import pygame
|
||
|
from .constants import RED, WHITE, BLUE, SQUARE_SIZE
|
||
|
from checkers.board import Board
|
||
|
|
||
|
class Game:
|
||
|
def __init__(self, win):
|
||
|
self._init()
|
||
|
self.win = win
|
||
|
|
||
|
|
||
|
|
||
|
def _init(self):
|
||
|
self.selected = None
|
||
|
self.board = Board()
|
||
|
self.turn = RED
|
||
|
self.valid_moves = {}
|
||
|
self.row = -1
|
||
|
self.col = -1
|
||
|
|
||
|
def update(self):
|
||
|
self.board.draw(self.win)
|
||
|
self.draw_valid_moves(self.row, self.col)
|
||
|
pygame.display.update()
|
||
|
|
||
|
def winner(self):
|
||
|
return self.board.winner()
|
||
|
|
||
|
def reset(self):
|
||
|
self._init()
|
||
|
|
||
|
def select(self, row, col):
|
||
|
if self.selected:
|
||
|
result = self._move(row, col)
|
||
|
if not result:
|
||
|
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)
|
||
|
|
||
|
self.row = row
|
||
|
self.col = col
|
||
|
return True
|
||
|
self.row = -1
|
||
|
self.col = -1
|
||
|
return False
|
||
|
|
||
|
def _move(self, row, col):
|
||
|
row = row
|
||
|
col = col
|
||
|
piece = self.board.get_piece(row, col)
|
||
|
if self.selected and piece == 0 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, row, col):
|
||
|
pygame.draw.circle(self.win, BLUE, (col * SQUARE_SIZE + SQUARE_SIZE//2, row * SQUARE_SIZE + SQUARE_SIZE//2), 15)
|
||
|
|
||
|
def change_turn(self):
|
||
|
self.valid_moves = {}
|
||
|
if self.turn == RED:
|
||
|
self.turn = WHITE
|
||
|
else:
|
||
|
self.turn = RED
|