Need help improving number guessing game
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Dec 15 16:53:06 EST 2008
feba a écrit :
> Alright! This is feeling more like it.
>
> #!/usr/bin/python
> #Py3k, UTF-8
> import random
>
(snip)
> def youwin(game):
> if game['pnum'] == 1:
> print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game
> ['gcount'])
> else:
> if game['player'] == game['player1']:
> game['p1sc'] += 1
> else:
> game['p2sc'] += 1
If you had initialized your "game" dict with
player1 = dict(score=0)
player2 = dict(score=0),
game = dict(
player1 = player1,
player2 = player2
player = player1
# ...
)
you wouldn't need the test on
game['player'] == game["player1"]
, and could just use:
game["player"]["score"] += 1
(snip)
> first off, I want to thank all of you for your help with this. I
> really don't think I could've learned all of this out nearly as
> quickly by reading tutorials and documentation, let alone had anything
> near the grasp I have on it now. '''This''' is why I like learning by
> doing. The only things I still don't really understand are .strip
> ().lower(),
.strip() returns a copy of the string without leading and ending
whitespaces (inlcuding newlines, tabs etc). .lower() returns a copy of
the string in all lowercases. Since .strip() returns a string object,
you can chain method calls.
" yaDDA\n".strip().lower()
is just a shortcut for
thestring = " yaDDA\n"
tmp1 = thestring.strip() # => "yaDDA"
tmp2 = tmp1.lower() # => "yadda"
> and try/except/else, and I plan on looking them up before
> I do anything else. In the past few hours I've gone from not having a
> clue what the whole {'fred': 0, 'barney': 0} thing was about to being
> able to fully understand what you're talking about, and put it into
> practice
Quite close... You still failed to understand how dicts could be used to
replace 'if/else' statements (dict-base dispatch is very idiomatic in
Python, and is also a good introduction to OO).
(snip)
> 5; I added the ability for it to automatically complete when there's
> only one option left. I was amazed' I was actually going to ask for
> advice on how to do it here. I was going to say "I was thinking (blah
> blah)", but then I just typed it in, and it worked flawlessly.
Yeps. That's probably why most of us here fell in love with Python: it
makes simple thing simple, and tend to JustWork(tm).
> 6; can anyone think of anything else to add on to/do with this game?
rewrite it once again using objects instead of dicts ?
Anyway, thanks for sharing your enthusiasm with us.
More information about the Python-list
mailing list