Note that OP constructed his list so that some values are weighted according
to the user's decision (Aggressive or defensive), Just let's not forget that
brilliance~ ;-)
Suggestions below.
> Here is a snippet that might work for one batter:
>
> #!/usr/bin/env python
> # cricket.py
> # 2007-07-26
> # b h a a l u u at g m a i l dot c o m
> import random
>
> def batterUp():
> score=[1,2,3,4,6,'Out']
> totalScore=0
> while 1:
> hit=random.choice(score)
> if hit != score[-1]:
> totalScore=totalScore+hit
> print "You batted",hit,"Total runs:",totalScore
> else:
> totalScore=totalScore+0
> print "You're OUT! Total runs:",totalScore
> break
>
> batterUp()
> # end criket.py
>
> Notice that the list, score , has integers and a string in it.
> I use the integers to add to the running score, and use the
> string 'Out' to stop the while loop. I just did this, and it ran
> okay the few times I tried it. YMMV. =)
This is one situation where the python concept of ask forgiveness later is
convenient.
For example.
###########
def play():
score = [1,2,3,4,6,'Out']
totalScore = 0
while 1:
hit = random.choice(score)
try:
totalScore += int(hit)
print "You batted a %s; Total runs: %d" % (hit,totalScore)
except ValueError:
print "You're OUT! Total runs:", totalScore
break
############
And a way that is even better of which I just thought ;-)
Use a special value to mean 'out'. This avoids the string problem.
A value of zero makes the comparisons with if even simpler.
#########
def play():
scores = [1,1,2,2,3,4,6,0,0] #Zero means "out"
totalScore = 0
while 1:
hit = random.choice(scores)
totalScore += hit
if hit: # The magic check - even makes sense, if no hit, then
"out"
print "You batted a %d, Total runs: %d" % (hit, totalScore)
else:
print "You're OUT! Total runs: %d" % totalScore
##########
A sneaky application of a form of encapsulation that OOP people like to use.
;-)
(So you only have to have one play function)
#######
aggr_scores = [1,2,3,4,4,6,6,0,0,0]
defe_scores = [1,1,1,2,2,3,4,6,0,0]
user_choice = raw_input("Which?\n\t(a) Aggressive\n\t(b) Defensive\n\nYour
choice: ")
if user_choice == 'a':
scores = aggr_scores
elif user_choice == 'b':
scores = defe_scores
else:
print "Please choose a or b"
play()
########
Or even better.
#########
score_lookup = {'a':[1,2,3,4,4,6,6,0,0,0],
'b':[1,1,1,2,2,3,4,6,0,0]}
# raw_input here
scores = score_lookup[user_choice]
play()
#############
HTH,
JS
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor