Skip to content

Instantly share code, notes, and snippets.

@majiang
Created October 18, 2012 07:31
Show Gist options
  • Select an option

  • Save majiang/3910294 to your computer and use it in GitHub Desktop.

Select an option

Save majiang/3910294 to your computer and use it in GitHub Desktop.
from random import shuffle
C = 12 # number of cards
class Player:
def __init__(self, cards, dealer, awake, id):
self.hand = cards
self.dealer = dealer
self.awake = awake
self.id = id
def play(self, card):
if self.awake and card in self.hand:
if self.dealer.play(card, self):
self.hand.remove(card)
if self.hand:
self.awake = False
else:
self.dealer.win(self)
class Dealer:
def __init__(self, n):
deck = range(C)
shuffle(deck)
self.players = []
self.passed = [False for i in range(n)]
for i in range(n):
self.players.append(Player(deck[i:C:n], self, i == 0, i))
self.top = None # top card
self.last = None # last player
self.continue_game = True
def next(self, player):
next_player = (player.id + 1) % len(self.players)
self.players[next_player].awake = True
def play(self, card, player):
if (self.last != player.id) and (self.top is not None) and (card <= self.top):
return False
self.top, self.last = card, player.id
print 'player %d played card %d.' % (player.id, card)
self.next(player)
return True
def is_pass(self, player):
if player.id != self.last and all(card <= self.top for card in player.hand):
self.next(player)
player.awake = False
return True
def win(self, player):
print 'player %d declared win.' % player.id
self.continue_game = False
def main():
dealer = Dealer(4)
for player in dealer.players:
print player.hand
while dealer.continue_game:
for player in dealer.players:
if not player.awake:
continue
else:
if dealer.is_pass(player):
print 'player %d passes.' % player.id
else:
try:
p = int(raw_input("choose player %d's card from %s\n" % (player.id, player.hand)))
except:
continue
player.play(p)
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment