Skip to content

Instantly share code, notes, and snippets.

@fuglede
Last active August 29, 2015 14:22
Show Gist options
  • Save fuglede/f3fa8c114f3053952972 to your computer and use it in GitHub Desktop.
Save fuglede/f3fa8c114f3053952972 to your computer and use it in GitHub Desktop.
15 the game
"""
A game where two players take turns choosing different numbers in
1, ..., 9 until one player has chosen three numbers that sum to 15,
thereby winning the game. If all numbers are chosen without any player
winning, the game is declared a tie.
"""
import itertools
class FifteenGame:
def __init__(self):
self.newGame()
def newGame(self):
self.activePlayer = 0 # Players are labelled 0 and 1
self.numbers = [[], []] # List containing each player's choices
self.gameOver = False # Has the game ended yet?
self.winningSet = () # Contains a solution set if a player has won
self.tie = False # Is true if the game has ended in a tie
def chooseNumber(self, n):
if self.gameOver:
raise RuntimeError("Game not in progress")
if n not in range(1, 10):
raise ValueError("Number should be integer between 1 and 9")
if n in self.numbers[0] + self.numbers[1]:
raise ValueError("Number already chosen by previous player")
self.numbers[self.activePlayer].append(n)
if not self.checkWinCondition():
self.activePlayer = (self.activePlayer + 1) % 2 # Switch player
def checkWinCondition(self): # Checks if the game has ended
if set(self.numbers[0] + self.numbers[1]) == set(range(1, 10)):
self.gameOver = True
self.tie = True
for subset in list(itertools.combinations(self.numbers[self.activePlayer], 3)):
if sum(subset) == 15:
self.gameOver = True
self.winningSet = subset
return self.gameOver
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment