Skip to content

Instantly share code, notes, and snippets.

@1328
Created April 30, 2015 16:42
Show Gist options
  • Select an option

  • Save 1328/7976bd5ac3ac11c99acb to your computer and use it in GitHub Desktop.

Select an option

Save 1328/7976bd5ac3ac11c99acb to your computer and use it in GitHub Desktop.
checkers
from itertools import product
from pprint import pprint
class Board(object):
def __init__(self):
self.board = {(a,b):None for a,b in product(range(10),repeat = 2)}
self.place_black()
self.place_white()
def place_black(self):
for row in range(4):
for spot in self.spots(row):
self.board[spot] = Piece('black')
def place_white(self):
for row in range(6, 10):
for spot in self.spots(row):
self.board[spot] = Piece('white')
def spots(self, row):
'''yields valid spots on a row'''
start = not(row % 2)
for i in range(start, 10, 2):
yield (i,row)
def row(self, key):
'''yields pieces on a particular row'''
for i in range(10):
yield self.board[(i, key)]
def __str__(self):
result = ''
for row in range(10):
line = '{}\n'.format(''.join(
str(c) if c else '.' for c in self.row(row)
))
result += line
return result
@staticmethod
def tupple_add(a,b):
return (a[0]+b[0], a[1]+b[1])
def generate_valid_moves(self, start):
piece = self.board[start]
if piece is None:
raise IndexError('No piece at {}'.format(start))
result = []
for move in piece.possible_moves:
stop = self.tupple_add(start, move)
if stop not in self.board:
continue
if self.board[stop] is not None:
continue
result.append(stop)
return result
def move(self, start, stop):
'''move piece at start to stop'''
moves = self.generate_valid_moves(start)
piece = self.board[start]
if stop not in moves:
raise IndexError('Cannot move {} to {}'.format(
start, stop))
self.board[start] = None
self.board[stop] = piece
class Piece(object):
def __init__(self, color):
self.color = color.lower()
def __str__(self):
return self.color[0].upper()
@property
def possible_moves(self):
'''return a list of valid moves'''
if self.color == 'black':
direction = 1
else:
direction = -1
return [(-1, direction), (1,direction)]
def king(self):
'''king a piece'''
return King(self.color)
class King(Piece):
@property
def possible_moves(self):
return [(-1,-1), (1,-1), (-1,1), (1,1)]
b = Board()
print(b)
b.move( (0,3), (1,4))
print(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment