Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Peg Solitaire by Al Sweigart al@inventwithpython.com
- # More info at https://en.wikipedia.org/wiki/Peg_solitaire
- EMPTY = '.'
- MARBLE = 'O'
- NORTH = 'north'
- SOUTH = 'south'
- EAST = 'east'
- WEST = 'west'
- ALL_SPACES = 'C1 D1 E1 C2 D2 E2 A3 B3 C3 D3 E3 F3 G3 A4 B4 C4 D4 E4 F4 G4 A5 B5 C5 D5 E5 F5 G5 C6 D6 E6 C7 D7 E7'.split()
- def getNewBoard():
- board = {}
- # Set every space on the board to a marble:
- for space in ALL_SPACES:
- board[space] = MARBLE
- # Set the center space to be empty:
- board['D4'] = EMPTY
- return board
- def displayBoard(board):
- spaces = []
- for space in ALL_SPACES:
- spaces.append(board[space])
- print('''
- ABCDEFG
- 1 {}{}{}
- 2 {}{}{}
- 3 {}{}{}{}{}{}{}
- 4 {}{}{}{}{}{}{}
- 5 {}{}{}{}{}{}{}
- 6 {}{}{}
- 7 {}{}{}
- '''.format(*spaces))
- def canMoveInDirection(board, space, direction):
- x, y = space # Split up `space` into the x and y coordinates.
- if direction == NORTH:
- neighborSpace = x + str(int(y) - 1) # E.g. convert y of 3 to '2'
- secondNeighborSpace = x + str(int(y) - 2) # E.g. convert y of 3 to '1'
- elif direction == SOUTH:
- neighborSpace = x + str(int(y) + 1) # E.g. convert y of 3 to '4'
- secondNeighborSpace = x + str(int(y) + 2) # E.g. convert y of 3 to '5'
- elif direction == WEST:
- neighborSpace = chr(ord(x) - 1) + y # E.g. convert 'C' to 'B'
- secondNeighborSpace = chr(ord(x) - 2) + y # E.g. convert 'C' to 'A'
- elif direction == EAST:
- neighborSpace = chr(ord(x) + 1) + y # E.g. convert 'C' to 'D'
- secondNeighborSpace = chr(ord(x) + 2) + y # E.g. convert 'C' to 'E'
- # Check if the neighboring space exists:
- if neighborSpace in ALL_SPACES:
- # Check if there is a marble in the neighboring space:
- if board[neighborSpace] == MARBLE:
- # Check if the neighbor's neighboring space exists:
- if secondNeighborSpace in ALL_SPACES:
- # Check if there is an empty space there:
- if board[secondNeighborSpace] == EMPTY:
- return True
- return False
- def getMoveableMarbles(board):
- moveableMarbles = [] # Contain a list of spaces whose marble can jump.
- for space in ALL_SPACES:
- if board[space] == EMPTY:
- continue # There's no marble here, so it's not a valid move.
- # Determine if the marble at this space can move:
- if canMoveInDirection(board, space, NORTH) or \
- canMoveInDirection(board, space, SOUTH) or \
- canMoveInDirection(board, space, WEST) or \
- canMoveInDirection(board, space, EAST):
- moveableMarbles.append(space)
- continue
- return moveableMarbles
- def getPlayerMove(board):
- while True:
- # Ask the player to enter a valid move:
- moveableMarbles = getMoveableMarbles(board)
- print('Enter the marble you want to move:')
- print(' '.join(moveableMarbles))
- space = input().upper()
- if space in moveableMarbles:
- break # If the space has a moveable marble, break out of the loop.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement