[Tutor] Controling my loops and redundant code?!?
Bob Gailer
bgailer at gmail.com
Thu Jan 26 18:52:22 CET 2006
At 08:44 AM 1/25/2006, Jon Moore wrote:
Hi,
I have written the program below as an exercise from a book I am working my
way through.
Objective from book:
Write a character creator program for a role-playing-game. The player should
be given a pool of 30 points to spend on four attributes: strength, health,
wisdom and dexterity. The player should be able to spend points from the
pool on any attribute and should be also be able to take points from an
attribute and put them back in the pool.
Although the program meets the aim of the exercise set out in the book ,
there are a couple of things I am not happy with!
1. I am sure I have written far more code than required. Where could I have
made some shorcuts?
2. Should the user enter a value greater than what is available, the program
kicks the user all the way back to the main menu. How could I tidy this up
to just loop round to ask the user to try a new value?
choice = None
# Set max number of available points
POINTS_POOL = 30
# store attribute values
attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity",
0]]
Some ideas to chew on as you develop skills and understanding of
programming.
Separate the "essential data" from the code. The essential data are
attributes, associated points and max_points. So
attributes = ["Strength", "Health", "Wisdom", "Dexterity"]
points = [0, 0, 0, 0]
MAX_POINTS = 30
In this model the relationship between attributes and points is by position.
Later you will study and use classes; then the points list will be replaced
by a list of class instances, one per attribute.
Develop code that operates on these lists to accomplish the various
objectives. The code itself will never refer to any attribute by name!
For example - to list the attributes with their points:
for x in range(len(attributes)):
print "\t",attributes[x], points[x]
To assign values. Note I separated getting input from converting it to
integer so we can see if the user's entry is convertible.:
available_points = MAX_POINTS - sum(points)
print "You have " + available_points + " available."
for x in range(len(attributes)):
cvalue = raw_input("How much would you like to assign to " + attributes[x]
+ " ?: "))
if cvalue.isdigit():
value = int(cvalue)
else:
print "Number expected"
[snip]
--
Bob Gailer
510-978-4454
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060126/38497fad/attachment.html
More information about the Tutor
mailing list