/
ndice2.py
69 lines (56 loc) · 1.83 KB
/
ndice2.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
"""
Class version of ndice1.py.
"""
import random
import sys
class Dice(object):
def __init__(self, n=1):
self.n = n # no of dice
def throw(self):
return [random.randint(1,6) \
for i in range(self.n)]
class Player(object):
def __init__(self, name, capital, guess_function, ndice):
self.name = name
self.capital = capital
self.guess_function = guess_function
self.dice = Dice(ndice)
def play_one_round(self):
self.guess = self.guess_function(self.dice.n)
self.throw = sum(self.dice.throw())
if self.guess == self.throw:
self.capital += self.guess
else:
self.capital -= 1
self.message()
self.broke()
def message(self):
print '%s guessed %d, got %d' % \
(self.name, self.guess, self.throw)
def broke(self):
if self.capital == 0:
print '%s lost!' % self.name
# Guessing strategies
def computer_guess(ndice):
# Any of the outcomes (sum) is equally likely
return random.randint(ndice, 6*ndice)
def player_guess(ndice):
return input('Guess the sum of the no of eyes '\
'in the next throw: ')
def play(nrounds, ndice=2):
player = Player('YOU', nrounds, player_guess, ndice)
computer = Player('Computer', nrounds, computer_guess, ndice)
for i in range(nrounds):
player.play_one_round()
computer.play_one_round()
print 'Status: user has %d euro, machine has %d euro\n' % \
(player.capital, computer.capital)
if player.capital == 0 or computer.capital == 0:
break # terminate game
if computer.capital > player.capital:
winner = 'Machine'
else:
winner = 'You'
print winner, 'won!'
if __name__ == '__main__':
play(nrounds=10, ndice=2)