-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcardGame.py
128 lines (109 loc) · 3 KB
/
cardGame.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
from random import shuffle
class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]
values = [None, None,"2", "3",
"4", "5", "6", "7",
"8", "9", "10",
"Jack", "Queen",
"King", "Ace"]
def _init_(self, v, s):
"""suit + value are ints"""
self.value = v
self.suit = s
def _lt_(self, c2):
if self.value < c2.value:
return True
if self.value == c2.value:
if self.suit < c2.suit:
return True
else:
return False
return False
def _gt_(self, c2):
if self.value > c2.value:
return True
if self.value == c2.value:
if self.suit > c2.suit:
return True
else:
return False
return False
def _repr_(self):
v = self.values[self.value] +\
" of " + \
self.suits[self.suit]
return v
class Deck:
def _init_(self):
self.cards = []
for i in range(2, 15):
for j in range(4):
self.cards\
.append(Card(i,
j))
shuffle(self.cards)
def rm_card(self):
if len(self.cards) == 0:
return
return self.cards.pop()
class Player:
def _init_(self, name):
self.wins = 0
self.card = None
self.name = name
class Game:
def _init_(self):
name1 = input("p1 name ")
name2 = input("p2 name ")
self.deck = Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
def wins(self, winner):
w = "{} wins this round"
w = w.format(winner)
print(w)
def draw(self, p1n, p1c, p2n, p2c):
d = "{} drew {} {} drew {}"
d = d.format(p1n,
p1c,
p2n,
p2c)
print(d)
def play_game(self):
cards = self.deck.cards
print("beginning War!")
while len(cards) >= 2:
m = "q to quit. Any " + \
"key to play:"
response = input(m)
if response == 'q':
break
p1c = self.deck.rm_card()
p2c = self.deck.rm_card()
p1n = self.p1.name
p2n = self.p2.name
self.draw(p1n,
p1c,
p2n,
p2c)
if p1c > p2c:
self.p1.wins += 1
self.wins(self.p1.name)
else:
self.p2.wins += 1
self.wins(self.p2.name)
win = self.winner(self.p1,
self.p2)
print("War is over.{} wins"
.format(win))
def winner(self, p1, p2):
if p1.wins > p2.wins:
return p1.name
if p1.wins < p2.wins:
return p2.name
return "It was a tie!"
game = Game()
game.play_game()