Character creating program ie Dungeons and Dragons.
Player has 30 points to spend on 4 attributes - strength, health, wisdom, and dexterity.
Player should be able to spend points from the pool on any attribute and should be able to take points from an attribute and put them back into the pool.
Currently i'm able to deduct points how do you return it back to the pool?
Also is there an easy method from preventing the player from entering more points than what the pool has?

# Character Development Dungeons and Dragons
# pool are the total points that I can use.
pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None

while choice !="0":
    print \
    """

    Character Development

    0 - Exit
    1 - attributes
    """
    
    choice = raw_input("Choice: ")
    print
    # exit
    if choice == "0":
      print "Good-bye."

    # Strength points
    elif choice == "1":
      strength = int(raw_input("How much strength points do you want?: "))
      print "Your Strength points are", strength
      health = int(raw_input("How much health points do you want?: "))
      print "Your health points are", health
      wisdom = int(raw_input("How much wisdom points do you want?: "))
      print "Your wisdom points are", wisdom
      dexterity = int(raw_input("How much dexterity points do you want?: "))
      print "Your dexterity points are", dexterity
      balance = int(pool-strength-health-wisdom-dexterity)
      print "After deducting all your attribute points you have", balance , "total points left",

    # some unknown choice
    else:
      print "Sorry, but", choice, "isn't a valid choice."

raw_input("\n\nPress the enter key to exit.")

Recommended Answers

All 15 Replies

I would take the whole section where you're asking for attribute points and enclose it inside of a while loop. Lets say you establish your initial variables

pool=30
health = 0
etc...
AllDone = False

Now open up a while loop that will continue until AllDone = True.

while AllDone != True:
   # Ask for the strength attribute
   answer = raw_input("strength: ")

   # Now do some input validation
   if answer > pool:
      print "That's too much, dog."
      continue # This will make it start over at the beginning of the while loop
   strength += answer

   # Now do the same thing for the other attributes.  At the end of
   # the loop you should only have valid answers in your variables
   # Set AllDone to True so you wont send the user back through the
   # Loop

I used a function and that cut down on code needed:

# Character Development Dungeons and Dragons
# pool are the total points that I can use.
pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None

def getInt(prompt, maximum, cur):
    
    i = 0

    print prompt
    i = int(raw_input())
    
    while (cur+i) > maximum:
        print prompt
        i = int(raw_input())
        
    return i
    

    
while choice !="0":
    current = 0
    print \
    """

    Character Development

    0 - Exit
    1 - attributes
    """
    
    choice = raw_input("Choice: ")
    print
    # exit
    if choice == "0":
      print "Good-bye."
   
    # Strength points
    elif choice == "1":
      strength = getInt("How much strength points do you want?: ", pool,current)
      current +=strength
      print "Your Strength points are", strength
      health = getInt("How much health points do you want?: ", pool,current)
      current +=health
      print "Your health points are", health
      wisdom = getInt("How much wisdom points do you want?: ", pool,current)
      current +=wisdom
      print "Your wisdom points are", wisdom
      dexterity = getInt("How much dexterity points do you want?: ", pool,current)
      current +=dexterity
      print "Your dexterity points are", dexterity
      balance = int(pool-strength-health-wisdom-dexterity)
      print "After deducting all your attribute points you have", balance , "total points left",

    # some unknown choice
    else:
      print "Sorry, but", choice, "isn't a valid choice."

raw_input("\n\nPress the enter key to exit.")

I suggest a refactoring using a class

# Character Development Dungeons and Dragons
# pool are the total points that I can use.


class CharacterDevelopment(object):
    attributes = "strength health wisdom dexterity".split()
    pool = 30

    def __init__(self):
	self.attribs = dict((attr, 0) for attr in self.attributes)

    @property
    def current(self):
	return sum(self.attribs.values())

    @property
    def balance(self):
	return self.pool - self.current

    def run(self):
	choice = None
	while choice !="0":
	    print """

    Character Development

    0 - Exit
    1 - Set attributes
    2 - Display Attributes
    """
	    choice = raw_input("Choice: ")
	    print
	    # exit
	    if choice == "0":
		print("Good-bye.")
	    # Strength points
	    elif choice == "1":
		for attr in self.attributes:
		    if not self.queryAttribute(attr):
			break
		print("After deducting all your attribute points you have %d total points left" % self.balance)
	    elif choice == "2":
		print("Your attributes points are:")
		for attr in self.attributes:
		    print("  %s : %d" %(attr, self.attribs[attr]))
		print("Your balance is %d" % self.balance)
	    else:
		print("Sorry, but %d isn't a valid choice." % choice)
	raw_input("\n\nPress the enter key to exit.")      

    def queryAttribute(self, attr):
	m = self.pool - (self.current - self.attribs[attr])
	value = self.getInt("How much %s points do you want (<= %d) ?: " % (attr, m), m)
        if value is None:
	    return False
	else:
	    self.attribs[attr] = value
	    print("Your %s points are %d" % (attr, self.attribs[attr]))
	    return True


    def getInt(self, prompt, maximum):
	try:
	    print(prompt)
	    i = self.int_input()
	    while i > maximum:
		print("Sorry, the maximum possible value is %d" % maximum)
		print(prompt)
		i = self.int_input()
	    return i
	except ValueError:
	    return None

    def int_input(self):
	return int(raw_input())


cd = CharacterDevelopment()
cd.run()

What else am I missing?
When I ran the program for example enter 10 for strength points it returns back - "That's too much."

pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None
AllDone = False

while AllDone != True:
    # Ask for the strength attribute
    answer = raw_input("How much strength points you are requesting: ")
    
    # Now do some input validation
    if answer > pool:
         print "That's too much."
         continue # This will make it start over at the beginning of the while loop
         strength += answer
    
    # Ask for the health attribute
    answer = raw_input("How much health points you are requesting: ")

    # Now do some input validation
    if answer > pool:
        print "That's too much."
        continue # This will make it start over at the beginning of the while loop
    health += answer

    # Ask for wisdom attribute
    answer = raw_input("How much wisdom points you are requesting: ")

    # Now do some input validation
    if answer > pool:
        print "That's too much."
        continue # This will make it start over at the beginning of the while loop
    wisdom += answer

    # Ask for dexterity attribute
    answer = raw_input("How much dexterity points you are requesting: ")

    # Now do some input validation
    if answer > pool:
        print "That's too much."
        continue # This will make it start over at the beginning of the while loop
    dexterity += answer

It took me a second to figure this one out...and I only knew the answer because I have been reading these boards. As you can imagine, I am fairly new to Python also.

raw_input accepts a string from the user. So when the user types in 10 for his answer, python creates a string with a 1 and a 0 in it. When you compare answer to pool you are comparing a string to an integer. You need to convert the users answer into an integer. Here is some code to demonstrate.

pool = 30
answer = raw_input('Give me a number: ') #assume user types 10

print answer > pool #Answer will be True.

print int(answer) > pool #Answer will be False

Ran the above code -
I get the error msg - Token Error: EOF in multi-line statement.

# Character Development Dungeons and Dragons
# pool are the total points that I can use.
pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None

def getInt(prompt, maximum,cur):

    i = 0

    print prompt
    i = int(raw_input())

    while (cur+i) > maximum:
        print prompt
        i = int(raw_input())

    return i   

while choice !="0":
    print \
    """

    Character Development

    0 - Exit
    1 - attributes
    """
    
    choice = raw_input("Choice: ")
    print
    # exit
    if choice == "0":
      print "Good-bye."

    # Strength points
    elif choice == "1":
      strength = getInt(raw_input("How much strength points do you want?: ", pool,current)
      current += strength                  
      print "Your Strength points are", strength
      health = getInt(raw_input("How much health points do you want?: ", pool,current)
      current +=health             
      print "Your health points are", health
      wisdom = getInt(raw_input("How much wisdom points do you want?: ", pool,current)
      current +=wisdom             
      print "Your wisdom points are", wisdom
      dexterity = getInt(raw_input("How much dexterity points do you want?: "pool,current)
      current +=dexterity                
      print "Your dexterity points are", dexterity
      balance = int(pool-strength-health-wisdom-dexterity)
      print "After deducting all your attribute points you have", balance , "total points left", 
    
 
    # some unknown choice
    else:
      print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")

My code returned the EOF error? That seems odd. Here is the exact output of my Python interpreter

Python 2.5.1 (r251:54863, Feb  4 2008, 21:48:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> pool = 30
>>> answer = raw_input('Give me a number: ')
Give me a number: 10
>>> print answer > pool
True
>>> print int(answer) > pool
False
>>>

When I run the code that you provided in your last sample I get a different error. I believe the reason is because you're not properly passing arguments to your getInt function. Look at line 43, 46, 49, etc. You have more left parenthesis than right parenthesis and that is probably because you don't want to have the raw_input on those lines. I think you just want to pass the string, the max, and the current.

Ok I fixed the parenthesis issue. Ran the program got this error msg
NameError: name 'current' is not defined
So later on I added current = 0
Reran the program inserted 10 points for strength outputs
How much strength points do you want?: 10
10

# Character Development Dungeons and Dragons
# pool are the total points that I can use.
pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0

choice = None

def getInt(prompt, maximum,cur):

    i = 0

    print prompt
    i = int(raw_input())

    while (cur+i) > maximum:
        print prompt
        i = int(raw_input())

    return i   

while choice !="0":
    print \
    """

    Character Development

    0 - Exit
    1 - attributes
    """
    
    choice = raw_input("Choice: ")
    print
    # exit
    if choice == "0":
      print "Good-bye."

    # Strength points
    elif choice == "1":
      strength = getInt(raw_input("How much strength points do you want?: "), pool,current)
      current += strength                  
      print "Your Strength points are", strength
      health = getInt(raw_input("How much health points do you want?: "), pool,current)
      current +=health             
      print "Your health points are", health
      wisdom = getInt(raw_input("How much wisdom points do you want?: "), pool,current)
      current +=wisdom             
      print "Your wisdom points are", wisdom
      dexterity = getInt(raw_input("How much dexterity points do you want?: "), pool,current)
      current +=dexterity                
      print "Your dexterity points are", dexterity
      balance = int(pool-strength-health-wisdom-dexterity)
      print "After deducting all your attribute points you have", balance , "total points left", 
    
 
    # some unknown choice
    else:
      print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")

Ok fixed that integer issue. How do you stop the loop?

pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None
AllDone = False

while AllDone != True:
    # Ask for the strength attribute
    answer = raw_input("How much strength points you are requesting: ")
    
    # Now do some input validation
    if int(answer) > pool:
         print "That's too much."
         continue # This will make it start over at the beginning of the while loop
         strength += answer
    else:
         print "Strength points you have",int(answer) 
    
    # Ask for the health attribute
    answer = raw_input("How much health points you are requesting: ")

    # Now do some input validation
    if int (answer) > pool:
        print "That's too much."
        continue # This will make it start over at the beginning of the while loop
        health += answer
    else:
        print "Health points you have:", int(answer)


        
    # Ask for wisdom attribute
    answer = raw_input("How much wisdom points you are requesting: ")

    # Now do some input validation
    if int(answer) > pool:
        print "That's too much."
        continue # This will make it start over at the beginning of the while loop
        wisdom += answer
    else:
        print "Wisdom points you have:", int(answer)

    # Ask for dexterity attribute
    answer = raw_input("How much dexterity points you are requesting: ")

    # Now do some input validation
    if int(answer) > pool:
        print "That's too much."
        continue # This will make it start over at the beginning of the while loop
        dexterity += answer
    else:
        print "dexterity points you have:", int(answer)

That's what you want, right?

The problem i'm having it's going beyond the 30 pool points?
strength - Enter 10
health - Enter 10
wisdom - Enter 10
dexterity - Enter 10 it shouldn't allow me.
Did it work for you?

For example -
How much strength points you are requesting: 10
Strength points you have 10
How much health points you are requesting: 10
Health points you have: 10
How much wisdom points you are requesting: 10
Wisdom points you have: 10
How much dexterity points you are requesting: 10
dexterity points you have: 10

How much strength points you are requesting:

I started to write up something to demonstrate working code but my wife is being a complete pain in the butt right now. She wont give me even one more second to fix some of the bugs in this code so this will have to do. Sorry. Blame her.

pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None
# AllDone = False

def CheckForValidInput(answer):
  try:
    int(answer)
  except ValueError:
    return "NotNumber"
  if int(answer) > pool:
    return "TooBig"
  return True

def AllocatePoints(prompt):
  AllDone = False
  while AllDone != True:
	print "How many points do you want to allocate for",prompt,": ",
	answer = raw_input()
	ResultofCheck = CheckForValidInput(answer)
	if ResultofCheck == "TooBig":
	  print "  ## You do not have that many points available ##"
	  continue
	if ResultofCheck == "NotNumber":
	  print "  ## That isn't even a number, you idiot! ##"
	  continue
	AllDone = True
  return int(answer)

def PrintAllocation():
  print "Strength:", strength
  print "Health:", health
  print "Wisdom:", wisdom
  print "Dexterity:",dexterity
  print " "
  print "Points remaining to allocate:",pool

while pool > 0:
  strength += AllocatePoints("strength")
  pool -= strength
  PrintAllocation()
  
  health += AllocatePoints("health")
  pool -= health
  PrintAllocation()
  
  wisdom += AllocatePoints("wisdom")
  pool -= wisdom
  PrintAllocation()
  
  dexterity += AllocatePoints("dexterity")
  pool -= wisdom
  PrintAllocation()

Like I said, not perfect. You'll have to take it from here. The in-laws are in town and I probably wont get to touch a computer until after Christmas.

Ok thanks for your help. Don't want to get you in trouble with the wife.

Results of the 3 different programs - 1 worked the other two had problems
This one worked fine -

# Character Development Dungeons and Dragons
# pool are the total points that I can use.

class CharacterDevelopment(object):
    attributes = "strength health wisdom dexterity".split()
    pool = 30
	
    def __init__(self):
         self.attribs = dict((attr, 0) for attr in self.attributes)

    @property
    def current(self):
        return sum(self.attribs.values())

    @property
    def balance(self):
        return self.pool - self.current

 
    def run(self):
        choice = None
        while choice !="0":
            print """

 
    Character Development
 
    0 - Exit
    1 - Set attributes
    2 - Display Attributes
    """

            choice = raw_input("Choice: ")
            print
            # exit
            if choice == "0":
               print("Good-bye.")
            # Strength points
            elif choice == "1":
               for attr in self.attributes:
                   if not self.queryAttribute(attr):
                      break
               print("After deducting all your attribute points you have %d total points left" % self.balance)

            elif choice == "2":
               print("Your attributes points are:")
               for attr in self.attributes:
                   print(" %s : %d" %(attr, self.attribs[attr]))
               print("Your balance is %d" % self.balance)
            else:
               print("Sorry, but %d isn't a valid choice." % choice)
    raw_input("\n\nPress the enter key to exit.")

    def queryAttribute(self, attr):
      m = self.pool - (self.current - self.attribs[attr])
      value = self.getInt("How much %s points do you want (<= %d) ?: " % (attr, m), m)
      if value is None:
         return False
      else:
         self.attribs[attr] = value
         print("Your %s points are %d" % (attr, self.attribs[attr]))
         return True


    def getInt(self, prompt, maximum):
      try:
         print(prompt)
         i = self.int_input()
         while i > maximum:
             print("Sorry, the maximum possible value is %d" % maximum)
             print(prompt)
             i = self.int_input()
         return i
      except ValueError:
         return None

    def int_input(self):
         return int(raw_input())


cd = CharacterDevelopment()

cd.run()

This one got stuck after answering the 1st input.

# Character Development Dungeons and Dragons
# pool are the total points that I can use.
pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None

def getInt(prompt, maximum, cur):

    i = 0

    print prompt
    i = int(raw_input())
    
    while (cur+i) > maximum:
        print prompt
        i = int(raw_input())

    return i   

while choice !="0":
    current = 0
    print \
    """

    Character Development

    0 - Exit
    1 - attributes
    """
    
    choice = raw_input("Choice: ")
    print
    # exit
    if choice == "0":
      print "Good-bye."

    # Strength points
    elif choice == "1":
      strength = getInt(raw_input("How much strength points do you want?: "), pool, current)
      current += strength                  
      print "Your Strength points are", strength
      health = getInt(raw_input("How much health points do you want?: "), pool,current)
      current +=health             
      print "Your health points are", health
      wisdom = getInt(raw_input("How much wisdom points do you want?: "), pool,current)
      current +=wisdom             
      print "Your wisdom points are", wisdom
      dexterity = getInt(raw_input("How much dexterity points do you want?: "), pool,current)
      current +=dexterity                
      print "Your dexterity points are", dexterity
      balance = int(pool-strength-health-wisdom-dexterity)
      print "After deducting all your attribute points you have", balance , "total points left", 
    
 
    # some unknown choice
    else:
      print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")

The 3rd one gave wrong calculation.
ie -
Enter 10 for strength
Enter 10 for health
Enter 10 for wisdom
Enter 0 for dexterity
It outputed - Strength: 10
Health: 10
Wisdom: 10
Dexterity: 0
Points remaining to allocate: -10

pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0
choice = None

# AllDone = False

 
def CheckForValidInput(answer):

   try:
     int(answer)
   except ValueError:
     return "NotNumber"
   if int(answer) > pool:
     return "TooBig"
   return True

def AllocatePoints(prompt):
   AllDone = False
   while AllDone != True:
        print "How many points do you want to allocate for",prompt,": ",
        answer = raw_input()
        ResultofCheck = CheckForValidInput(answer)
        if ResultofCheck == "TooBig":

          print " ## You do not have that many points available ##"
          continue
        if ResultofCheck == "NotNumber":
          print " ## That isn't even a number, you idiot! ##"
          continue
        AllDone = True
   return int(answer)

def PrintAllocation():
   print "Strength:", strength
   print "Health:", health
   print "Wisdom:", wisdom
   print "Dexterity:",dexterity
   print " "
   print "Points remaining to allocate:",pool

 

while pool > 0:
   strength += AllocatePoints("strength")
   pool -= strength
   PrintAllocation()

 
   health += AllocatePoints("health")
   pool -= health
   PrintAllocation()

   wisdom += AllocatePoints("wisdom")
   pool -= wisdom
   PrintAllocation()

   dexterity += AllocatePoints("dexterity")
   pool -= wisdom
   PrintAllocation()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.