Generating a Random Weapon for a Merchant

Generating a Random Weapon for a Merchant

Postby Velcrode » Sat Jun 29, 2013 4:57 am

Hello all. This is my first post on this forum, and unfortunately it is an inquiry.

I love video games. Like almost anyone else who grew up playing video games, I have had aspirations to create my own, to implement my own ideas and desires into an interactive experience. This is the first step: I've started learning Python with this text-based RPG. So far, the program allows the user to create their name, to explore, to encounter enemies, to find a merchant, check, status, and other un-exciting things. There are a lot of issues with the code, but for the sake of brevity I would like some help solely with the generation of a random weapon from a set list for a merchant to sell. This part can be found in the Player class, in the def merch block and the def weapon block. Any assistance would be greatly appreciated!!!


Code: Select all
import random
from random import randint
import time
 
class Character:
  def __init__(self):
    self.name = ""
    self.health = 1
    self.health_max = 1
  def do_damage(self, enemy):
    damage = min(
        max(randint(0, self.health) - randint(0, enemy.health), 0), enemy.health)
    enemy.health = enemy.health - damage
    if damage == 0:
      print "%s evades %s's attack." % (enemy.name, self.name)
    else:
      print "%s hurts %s!\n -%dhp" % (self.name, enemy.name, damage)
    return enemy.health <= 0
 
class Enemy(Character):
  def __init__(self, player):
    Character.__init__(self)
    enemy_name1 = randint(0, 7)
    ex = randint(0, 7)
    if enemy_name1 == 0:
      en = "Gibbering Madman"
      eh = ex + 1
    elif enemy_name1 == 1:
      en = "Tainted Fox"
      eh = ex + 2
    elif enemy_name1 == 2:
      en = "White Sasth"
      eh = ex + 3
    elif enemy_name1 == 3:
      en = "Leafmonster"
      eh = ex + 3
    elif enemy_name1 == 4:
      en = "Bandit"
      eh = ex + 4
    elif enemy_name1 == 5:
      en = "Tainted Warrior"
      eh = ex + 5
    elif enemy_name1 == 6:
      en = "Sandcat"
      eh = ex + 6
    elif enemy_name1 == 7:
      en = "Shadow"
      eh = ex + randint(4, 6)
    self.name = "%s"%(en)
    self.health = eh

class Container:
  def __init__(self, name):
    self.name = name
    self.inside = {}

  def __iter__(self):
    return iter(self.inside)

  def __len__(self):
    return len(self.inside)

  def __contains__(self, item):
    return item.raw in self.inside

  def __setitem__(self, item, value):
    self.inside[item.raw] = value
    return self[item]

  def add(self, item, quantity=1):
    if quantity < 0:
      raise ValueError("Negative quantity. Use remove() instead.")

    if item in self:
      self[item].quantity += quantity
      self[item].recalc()
    else:
      self[item] = item

  def remove(self, item, quantity=1):
    if item not in self:
      raise KeyError("You don't have this item.")
    if quantity < 0:
      raise ValueError("Negative quantity. Use add() instead.")

    if self[item].quantity <= quantity:
      del self.inside[item.raw]
    else:
      self[item].quantity -= quantity
      self[item].recalc()

class Item:
  def __init__(self, name, value, quantity=1):
    Character.__init__(self)
    self.name = name
    self.raw = name.strip().lower()
    self.quantity = quantity
    self.value = value

  def recalc(self):
    self.netValue = self.quantity * self.value

class rangedWeapon(Item):
  def __init__(self, name, value, damage):
    self.minDMG = damage[0]
    self.maxDMG = damage[1]
  def damage(rangedWeapon):
    damae = weapon.damage

class armor(Item):
  def __init__(self, name, value, defense):
    Character.__init__(self)
    self.defense = defense

armor_name1 = (0, 21)
if armor_name1 == 0:
  ar = "None", 0, 0,
elif armor_name1 == 1:
  ar = "Saran Wrap", 0, 0,
elif armor_name1 == 2:
  ar = "Imaginary Armor", 0, 0,
elif armor_name1 == 3:
  ar = "Woolen Dress", 3, 1,
elif armor_name1 == 4:
  ar = "Clothes", 3, 1,
elif armor_name1 == 5:
  ar = "Sheepskin Coat", 4, 2,
elif armor_name1 == 6:
  ar = "Wooden Armor", 4, 2,
elif armor_name1 == 7:
  ar = "Leather Jerkin", 5, 3,
elif armor_name1 == 8:
  ar = "Two Leather Jerkins", 6, 4,
elif armor_name1 == 9:
  ar = "Rusted Chainmail", 6, 4,
elif armor_name1 == 10:
  ar = "Polished Chainmail", 10, 5,
elif armor_name1 == 11:
  ar = "Iron Breastplate", 16, 6,
elif armor_name1 == 12:
  ar = "Iron Breastplate and Chainmail", 20, 7,
elif armor_name1 == 13:
  ar = "Steel Breastplate", 25, 8,
elif armor_name1 == 14:
  ar = "Steel Breasplate and Chainmail", 30, 9,
elif armor_name1 == 15:
  ar = "Steel Suit", 35, 11,
elif armor_name1 == 16:
  ar = "Reinforced Steel Suit", 45, 13,
elif armor_name1 == 17:
  ar = "Reforged Steel Alloy Suit", 55, 14,
elif armor_name1 == 18:
  ar = "Warcloth", 60, 15,
elif armor_name1 == 19:
  ar = "Warmail", 70, 17,
elif armor_name1 == 20:
  ar = "Warplate", 85, 21,
elif armor_name1 == 21:
  ar = "Warsuit", 90, 23

class Player(Character):
  def __init__(self):
    Character.__init__(self)
    self.state = 'normal'
    self.merchstate = 'normal'
    self.level = 1
    self.health = 10
    self.health_max = 10
    self.loot = 10
    self.stim = 2
    self.ammo = 10
    self.weapon = "Dirk"
    self.armor = "Leather Jerkin"
    self.inside = {}
  def quit(self):
    print "%s can't find the way back home, and dies of starvation.\nR.I.P." % self.name
    self.health = 0
  def help(self):
    print Commands.keys()
  def status(self): print "Level: %d ---- Health: %d/%d\nGold:%d\nPotions:%d ---- Arrows:%d\nWeapon:%s ---- Armor:%s" % (self.level, self.health, self.health_max, self.loot, self.stim, self.ammo, self.weapon, self.armor)
  def oofammo(self):
    if self.ammo <= 0:
      print "You don't have any arrows."
  def item1(self):
    if self.merchstate == 'buy' :
      if self.merchstim > 0:
        if self.loot >=20:
          self.stim = self.stim +1
          self.loot = self.loot - 20
          self.merchstim = self.merchstim -1
          print "%s bought 1 potion." % self.name
        else:
          print "Not enough gold."
      else:
        print "The merchant has no potions."
    else:
      print "There's no merchant here (that you can see...)"
      self.merchstate = 'normal'
  def item2(self):
    if self.merchstate == 'buy' :
      if self.merchammo > 0:
        if self.loot >= 10:
          self.ammo = self.ammo + 5
          self.loot = self.loot - 10
          self.merchammo = self.merchammo - 5
          print "%s bought 5 arrows." % self.name
        else:
          print "Not enough gold."
      else:
        print "The merchant has no arrows."
    else:
      print "There's no merchant here (that you can see...)"
      self.merchstate = 'normal'
  def sell(self):
    if self.merchstate == 'buy' :
      if self.stim > 0:
        self.stim = self.stim -1
        self.loot = self.loot + 15
        self.merchstim = self.merchstim + 1
        print "%s sold 1 potion." % self.name
      else:
        print "%s has no potions to sell." % self.name
    else:
      print "There's no merchant here (that you can see...)"
      self.merchstate = 'normal'
  def weaponSell(self):
    if self.merchstate == 'buy' :
      if self.weapon == True:
        self.weapon = items[0]
  def getEquipInfo(self): print "%s wields a %s and is wearing %s" % (self.name, self.weapon, self.armor)
  def stim(self):
    if self.stim > 0:
      if self.health < self.health_max:
        self.health = self.health + 5
        self.stim = self.stim - 1
        print "You drink a potion and feel fucking awesome (+5 health)."
        if self.health > self.health_max:
          self.health = self.health_max
          print "%s is at full health." % self.name
      else:
        print "full health."
    else:
      print "no potions. =("
  def merch(self):
    self.merchstate = 'buy'
    self.merchstim = randint (0, 10)
    self.merchammo = randint (0, 50)
    print "%s goes to the Merchants' Clearing." % self.name
    print "Merchant's items:\n potions:%d\n arrows:%d" % (self.merchstim, self.merchammo)
    if randint(0, 6) > 3:
      self.merchweapon = True
      if True:
        self.merchweapon = weapon_name1
        print self.merchweapon
      self.mercharmor = True
      if True:
        self.mercharmor = armor_name1
        print self.mercharmor
  def tired(self):
    print "%s feels tired." % self.name
    self.health = max(1, self.health - 1)
  def rest(self):
    if self.state != 'normal': print "%s can't rest now!" % self.name; self.enemy_attacks()
    else:
      print "%s finds a secluded spot, unrolls his sleeping pad, and rests." % self.name
      if randint(0, 7) > 5:
        self.enemy = Enemy(self)
        print "%s is awakened by a %s!" % (self.name, self.enemy.name)
        self.state = 'fight'
        self.enemy_attacks()
      else:
        if self.health < self.health_max:
          self.health = self.health + 1
        else:
          print "%s awakens feeling refreshed." % self.name; self.health = self.health - 1
  def areas(area1, n=1):
    a1 = area1.split('\n')
    random.shuffle(a1)
    area = []
    for a in range(n):
      try:
        s = a1[a]
        s = s.capitalize() + '.'
        area.apped(s)
      except IndexError:
        break
    return area
  def flee(self):
    if self.state != 'fight': print "%s runs in circles for a while, squawking like a seagull. That'll teach you to fuck around." % self.name; self.tired()
    else:
      if randint(1, self.health + 5) > randint(1, self.enemy.health):
        print "%s flees from the %s." % (self.name, self.enemy.name)
        self.enemy = None
        self.state = 'normal'
      else: print "%s couldn't escape from the %s!" % (self.name, self.enemy.name); self.enemy_attacks()
  def explore(self):
    self.oofammo()
    self.merchstate = 'normal'
    if self.state != 'normal':
      print "%s is too busy right now!" % self.name
      self.enemy_attacks()
    elif self.ammo > 0:
      print "%s wanders a bit." % (self.name)
      if randint(0, 1):
        self.enemy = Enemy(self)
        print "%s encounters a %s!\nEnemy hp: %d." % (self.name, self.enemy.name, self.enemy.health)
        self.state = 'fight'
    else:
      print "%s returns to the town of Jira on the forest's edge." % self.name
      if randint(0, 1):
        self.merch()
  def weapon(Item):
    def __init__(self, name, value, damage):
      Character.__init__(self)
      self.minDMG = damage[0]
      self.maxDMG = damage[1]
    def damage(Weapon):
      return random.randint(self.minDMG, self.maxDMG)
  def attack(self):
    if self.state != 'fight':
      print "%s wacks a tree; the tree's feelings are hurt." % self.name; self.tired()   
    else:
      if self.do_damage(self.enemy):
        print "%s headshots %s!" % (self.name, self.enemy.name)
        self.enemy = None
        self.state = 'normal'
        eloot = randint(0, 25)
        self.loot = eloot + self.loot
        print "You recovered %d gold from the corpse." %(eloot)
        eammo = randint (0, 5)
        self.ammo = eammo + self.ammo
        print "You recovered %d arrows from the corpse." %(eammo)
        stimp = randint(0, 4)
        if stimp == 0:
          self.stim = self.stim +1
          print "You found a potion!"
        if randint(0, self.health_max) == 10:
          self.level = self.level + 1
          self.health = self.health + 1
          self.health_max = self.health_max + 1
          print "%s feels stronger!" % self.name
      else:
        self.enemy_attacks()
  def enemy_attacks(self):
    if self.enemy.do_damage(self): print "%s was slaughtered by %s!\nGAME OVER\n" %(self.name, self.enemy.name)

def weapon_name1(weapon):
  weapon_name1 = (0, 24)

if weapon_name1 == 0:
    we = "None", 0, (0,0),
elif weapon_name1 == 1:
    we = "Imaginary Sword", 0, (0,0),
  elif weapon_name1 == 2:
    we = "Twig", 0, (0,1),
  elif weapon_name1 == 3:
    we = "Rock", 0, (1, 2),
  elif weapon_name1 == 4:
    we = "Stick", 0, (1, 3),
  elif weapon_name1 == 5:
    we = "Dagger Handle", 1, (2, 3),
  elif weapon_name1 == 6:
    we = "Rusty Spoon", 1, (2, 3),
  elif weapon_name1 == 7:
    we = "Stake", 2, (3, 3),
  elif weapon_name1 == 8:
    we = "Dirk", 5, (3, 4),
  elif weapon_name1 == 9:
    we = "Magic Slingshot", 7, (4, 5),
  elif weapon_name1 == 10:
    we = "Wooden Practice Sword (Slightly Thicker Stick)", 8, (5, 6),
  elif weapon_name1 == 11:
    we = "Petrified Wood Sword", 14, (7, 8),
  elif weapon_name1 == 12:
    we = "Shortsword", 15, (9, 11),
  elif weapon_name1 ==  13:
    we = "Rapier", 17, (10, 12),
  elif weapon_name1 == 14:
    we = "Spatha", 20, (12, 14),
  elif weapon_name1 == 15:
    we = "Reforged Steel Shortsword", 23, (12, 15),
  elif weapon_name1 == 16:
    we = "Longsword", 25, (13, 16),
  elif weapon_name1 == 17:
    we = "Steel War Axe", 28, (15, 17),
  elif weapon_name1 == 18:
    we = "Reinforced Steel Longsword", 30, (16, 19),
  elif weapon_name1 == 19:
    we = "Short Spear", 35, (18, 20),
  elif weapon_name1 == 20:
    we = "Heavy Battleaxe", 45, (18, 21),
  elif weapon_name1 == 21:
    we = "Greatsword", 50, (20, 23),
  elif weapon_name1 == 22:
    we = "Poleaxe", 55, (22, 25),
  elif weapon_name1 == 23:
    we = "Warhammer", 60, (25, 28),
  elif weapon_name1 == 24:
    we = "Callandor", 200, (50, 60)

Commands = {
  'quit': Player.quit,
  'help': Player.help,
  'stat': Player.status,
  'rest': Player.rest,
  'e': Player.explore,
  'run': Player.flee,
  'a': Player.attack,
  'p': Player.stim,
  'merch': Player.merch,
  '1': Player.item1,
  '2': Player.item2,
  'sell': Player.sell,
  'sw': Player.weaponSell,
  'eqi': Player.getEquipInfo
  }

p = Player()
print ''
print "Welcome to the land of Grer, a realm in turmoil due to the recent disposition"
print "of the beloved king Quolin. You shall seek your fortune in the dissolution, for"
print "riches may be made in such times of strife."
print ''
p.name = raw_input("What is your character's name? ")
print ''
print "(type help at any time to get a list of actions)\n"
print "%s enters a dark forest, searching for adventure." % p.name
while(p.health > 0):
  line = raw_input(">>> ")
  args = line.split()
  if len(args) > 0:
    commandFound = False
    for c in Commands.keys():
      if args[0] == c[:len(args[0])]:
        Commands[c](p)
        commandFound = True
        break
    if not commandFound:
      print "%s doesn't understand the suggestion." % p.name
Velcrode
 
Posts: 12
Joined: Sat Jun 29, 2013 3:41 am

Re: Generating a Random Weapon for a Merchant

Postby metulburr » Sat Jun 29, 2013 1:46 pm

when you post code, please be sure that you post it exactly the way you have it written, and to even check to make sure. For example, your code has an indentation error:
Code: Select all
if weapon_name1 == 0:
    we = "None", 0, (0,0),
elif weapon_name1 == 1:
    we = "Imaginary Sword", 0, (0,0),
  elif weapon_name1 == 2:

Making sure that your code posted is what you intended is key to getting a response promptly.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1469
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Generating a Random Weapon for a Merchant

Postby ochichinyezaboombwa » Sat Jun 29, 2013 5:38 pm

Velcrode wrote:... for the sake of brevity I would like some help solely with the generation of a random weapon from a set list for a merchant to sell. This part can be found in the Player class, in the def merch block and the def weapon block. Any assistance would be greatly appreciated!!!

You posted 500 lines of code and 10 sentences of text but failed to do a basic thing: explain what is your problem.

Never assume that anybody wants to spend time to read your code. Nobody wants to read bad code. And absolutely, definitely, positively nobody wants to read your mind.

So: you need to limit (!!!) your question, and be very specific. E.g.
a) what do you expect your merch() do?
b) what is the input to it?
c) what kind of output you want it to produce?

Code: Select all
    if randint(0, 6) > 3:
      self.merchweapon = True
      if True:
        self.merchweapon = weapon_name1
I have about 10 questions to you about this masterpiece.

  • What is the average result of randint(0, 6)?
  • Why is it not randint(0, 666)?
  • Or randint(0, 1)?
  • Did you read help(randint)?
  • What is the merchweapon's data type?
  • Is it boolean? or function? or string?
  • What does "if True:" mean? When does it fail?

And yes I can count up to 10 but I am tired.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Generating a Random Weapon for a Merchant

Postby ochichinyezaboombwa » Sat Jun 29, 2013 5:39 pm

metulburr wrote:when you post code, please be sure that you post it exactly the way you have it written, and to even check to make sure. For example, your code has an indentation error:
Code: Select all
if weapon_name1 == 0:
    we = "None", 0, (0,0),
elif weapon_name1 == 1:
    we = "Imaginary Sword", 0, (0,0),
  elif weapon_name1 == 2:

Making sure that your code posted is what you intended is key to getting a response promptly.

Actually I didn't find any indentation problems in the OP.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Generating a Random Weapon for a Merchant

Postby metulburr » Sat Jun 29, 2013 6:51 pm

Actually I didn't find any indentation problems in the OP.

I believe he fiexed it after i posted.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1469
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Generating a Random Weapon for a Merchant

Postby Velcrode » Sat Jun 29, 2013 7:08 pm

I didn't fix the indentation, when I read your comment I checked the code and there was no error.

I've spent all of today reading Berkeley's notes on programming with Python (http://inst.eecs.berkeley.edu/~cs61a/sp ... tions.html) and although I still have much more to get through, I have come to this conclusion (along with some assistance from ochichinyezaboombwa's comment):

What I posted was f*cking stupid!

I falsely believed that my question would be explicit in the title of the post, although I foolishly worded it as a statement. My goal is to generate a random weapon for this merchant. In question form: How do I generate a random weapon for a merchant? The reason I inundated my post with code is because I wanted the whole mess to be available to anyone who could help, and if they saw any other inconsistencies in passing they could bring them to my attention. I believe that embarrassing one's self is one of the most powerful ways to learn.

As for the merchweapon's data type... I'm not sure. I'm starting to think it's an issue of parameters, or something, but I have no idea what solution to implement, or how. I believe weapons is a class (I've since changed the code a bit), and the list of weapon names is an if-else function. I took out the "if True:" thing, I have come to realize with the help of too many others that that kind of coding is silly.

tl;dr: I want to get the merchant's output to be a random weapon, with an input from an if-else function. Is this even possible(methinks not)?
Velcrode
 
Posts: 12
Joined: Sat Jun 29, 2013 3:41 am

Re: Generating a Random Weapon for a Merchant

Postby Mekire » Sat Jun 29, 2013 7:19 pm

Long if/elif/else blocks are rarely the answer. Usually when you feel you need one of these, what you actually need is a dictionary.

Code: Select all
import random

weapon_dict = {"None"            : [0,(0,0)],
               "Imaginary Sword" : [0,(0,0)],
               "Twig"            : [0,(0,1)],
               "Rock"            : [0,(1,2)],
               "Stick"           : [0,(1,3)]}

merch_weap = random.choice(list(weapon_dict.keys()))

print("Merch weapon: {} , Stats: {}".format(merch_weap,weapon_dict[merch_weap]))

-Mek
User avatar
Mekire
 
Posts: 988
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Generating a Random Weapon for a Merchant

Postby Velcrode » Sat Jun 29, 2013 8:02 pm

Thanks Mekire, I thought the if-else block was wrong but had no clue what to exchange it with. It seems the dict function is working, but a new error has arisen, along with questions:

When "if randint(0,1):" evaluates when the "merch" command is called (thanks again ochichin)

Code: Select all
 print("Merch weapon: {} , Stats: {}".format(merch_weapon,weapon_dict[merch_weapon]))
ValueError: zero length field name in format


is the error shown. How do I remedy this? Also, if anyone can explain it, how will the stats in the dict block be made available to the interpreter so they can be printed? I feel like something's missing.
Velcrode
 
Posts: 12
Joined: Sat Jun 29, 2013 3:41 am

Re: Generating a Random Weapon for a Merchant

Postby ochichinyezaboombwa » Sat Jun 29, 2013 8:20 pm

There must be a simple explanation to the error you get. Computers (in contrast to humans) are straightforward.
To get help, you need to show your (obviously changed) merch() code, because Mekire's code works just fine.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Generating a Random Weapon for a Merchant

Postby Velcrode » Sat Jun 29, 2013 8:36 pm

Here's the new "def merch" block:

Code: Select all
def merch(self):
    self.merchstate = 'buy'
    self.merchstim = randint (0, 10)
    self.merchammo = randint (0, 50)
    if randint(0, 1):
      print("Merch weapon: {} , Stats: {}".format(merch_weapon,weapon_dict[merch_weapon]))
      print("Merch armor: {} , Stats: {}".format(merch_armor, armor_dict[merch_armor]))
    print "%s goes to the Merchants' Clearing." % self.name
    print "Merchant's items:\n~Potions:%d\n~Arrows:%d\n" % (self.merchstim, self.merchammo)


I defined merch_weapon and merch_armor in the Player class and in the global frame (shown in that order) to mitigate other error messages ("merch_weapon/armor not defined"):

Code: Select all
def merch_weapon(self):
    if self.merchstate == 'buy':
      self.merch_weapon = random.choice(list(weapon_dict.keys()))
  def merch_armor(self):
    if self.merchstate == 'buy':
      self.merch_armor = random.choice(list(armor_dict.keys()))


Code: Select all
merch_weapon = random.choice(list(weapon_dict.keys()))
merch_armor = random.choice(list(weapon_dict.keys()))


And here's the weapon_dict bloc, in the global frame (armor_dict is essentially the same):

Code: Select all
weapon_dict = {"None"             : [0,(0,0)],
               "Imaginary Sword"  : [0,(0,0)],
               "Twig"             : [0,(0,1)],
               "Rock"             : [0,(1,2)],
               "Stick"            : [0,(1,3)],
               "Dagger Handle"    : [1,(2,3)],
               "Rusty Spoon"      : [1,(2,3)],
               "Stake"            : [2,(3,3)],
               "Dirk"             : [5,(3,4)],
               "Magic Slingshot"  : [7,(4,5)],
               "Wooden Sword"     : [8,(5,6)],
               "Petrified Wood Sword" : [14,(7,8)],
               "Shortsword"       : [15,(9,11)],
               "Rapier"           : [17,(10,12)],
               "Spatha"           : [20,(12,14)],
               "Reforged Steel Shortsword" : [23,(12,15)],
               "Longsword"        : [25,(13,16)],
               "Steel War Axe"    : [28,(15,17)],
               "Reinforced Steel Longsword" : [30,(16,19)],
               "Short Spear"      : [35,(18,20)],
               "Heavy Battleaxe"  : [45,(18,21)],
               "Greatsword"       : [50,(20,23)],
               "Poleaxe"          : [55,(22,25)],
               "Warhammer"        : [60,(25,28)],
               "Callandor"        : [200,(50,60)]}
Velcrode
 
Posts: 12
Joined: Sat Jun 29, 2013 3:41 am

Re: Generating a Random Weapon for a Merchant

Postby ochichinyezaboombwa » Sat Jun 29, 2013 8:56 pm

Please post the output of the command
Code: Select all
python -V
(I speculate it says "Python 2.6.smth")
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Generating a Random Weapon for a Merchant

Postby Velcrode » Sat Jun 29, 2013 9:13 pm

It says "Python 2.6.1" since that's the System Python version, but I have all .py files set to run in Python Launcher 3.3.2.
Velcrode
 
Posts: 12
Joined: Sat Jun 29, 2013 3:41 am

Re: Generating a Random Weapon for a Merchant

Postby Velcrode » Sat Jun 29, 2013 11:24 pm

Can anyone help me define weapondamage based on what weapon the Player currently has?

Code: Select all
   def getEquipInfo(self): print "%s has a minDMG of %s and a maxDMG of %s\n%s has a defense of %s" % (self.weaponname, self.weapondamage, self.armorname, self.armordefense)
AttributeError: Player instance has no attribute 'weapondamage'


New code:

Code: Select all
import random
from random import randint
import time
 
class Character:
  def __init__(self):
    self.name = ""
    self.health = 1
    self.health_max = 1
  def do_damage(self, enemy):
    damage = min(
        max(randint(0, self.health) - randint(0, enemy.health), 0), enemy.health)
    enemy.health = enemy.health - damage
    if damage == 0:
      print "%s evades %s's attack." % (enemy.name, self.name)
    else:
      print "%s hurts %s!\n -%dhp" % (self.name, enemy.name, damage)
    return enemy.health <= 0
 
class Enemy(Character):
  def __init__(self, player):
    Character.__init__(self)
    enemy_name1 = randint(0, 7)
    ex = randint(0, 7)
    if enemy_name1 == 0:
      en = "Gibbering Madman"
      eh = ex + 1
    elif enemy_name1 == 1:
      en = "Tainted Fox"
      eh = ex + 2
    elif enemy_name1 == 2:
      en = "White Sasth"
      eh = ex + 3
    elif enemy_name1 == 3:
      en = "Leafmonster"
      eh = ex + 3
    elif enemy_name1 == 4:
      en = "Bandit"
      eh = ex + 4
    elif enemy_name1 == 5:
      en = "Tainted Warrior"
      eh = ex + 5
    elif enemy_name1 == 6:
      en = "Sandcat"
      eh = ex + 6
    elif enemy_name1 == 7:
      en = "Shadow"
      eh = ex + randint(4, 6)
    self.name = "%s"%(en)
    self.health = eh

class Container(object):
  def __init__(self, name):
    self.name = name
    self.inside = {}

  def __iter__(self):
    return iter(self.inside)

  def __len__(self):
    return len(self.inside)

  def __contains__(self, item):
    return item.raw in self.inside

  def __setitem__(self, item, value):
    self.inside[item.raw] = value
    return self[item]

  def add(self, item, quantity=1):
    if quantity < 0:
      raise ValueError("Negative quantity. Use remove() instead.")

    if item in self:
      self[item].quantity += quantity
      self[item].recalc()
    else:
      self[item] = item

  def remove(self, item, quantity=1):
    if item not in self:
      raise KeyError("You don't have this item.")
    if quantity < 0:
      raise ValueError("Negative quantity. Use add() instead.")

    if self[item].quantity <= quantity:
      del self.inside[item.raw]
    else:
      self[item].quantity -= quantity
      self[item].recalc()

class Item(object):
  def __init__(name, loot_worth, quantity=1):
    Character.__init__(self)
    self.name = name
    self.raw = name.strip().lower()
    self.quantity = quantity
    self.value = value

  def recalc(self):
    self.netValue = self.quantity * self.value

class weapon:
  def __init__(name, loot_worth, damage):
    Character.__init__(self)
    self.damage = damage

class rangedWeapon(Item):
  def __init__(name, loot_worth, damage):
    self.damage = damage

class armor(Item):
  def __init__(name, loot_worth, defense):
    Character.__init__(self)
    self.defense = defense

class Player(Character):
  def __init__(self):
    Character.__init__(self)
    self.state = 'normal'
    self.merchstate = 'normal'
    self.level = 1
    self.health = 10
    self.health_max = 10
    self.loot = 10
    self.stim = 2
    self.ammo = 10
    self.weaponname = "Dirk"
    self.armorname = "Leather Jerkin"
    self.inside = {}
  def quit(self):
    print "%s can't find the way back home, and dies of starvation.\nR.I.P." % self.name
    self.health = 0
  def help(self):
    print Commands.keys()
  def status(self): print "Level: %d ~~~~ Health: %d/%d\nGold:%d\nPotions:%d ~~~~~ Arrows:%d\nWeapon:%s ~~~~~ Armor:%s" % (self.level, self.health, self.health_max, self.loot, self.stim, self.ammo, self.weaponname, self.armorname)
  def oofammo(self):
    if self.ammo <= 0:
      print "You don't have any arrows."
  def buyPotion(self):
    if self.merchstate == 'buy' :
      if self.merchstim > 0:
        if self.loot >=20:
          self.stim = self.stim +1
          self.loot = self.loot - 20
          self.merchstim = self.merchstim -1
          print "%s bought 1 potion." % self.name
        else:
          print "Not enough gold."
      else:
        print "The merchant has no potions."
    else:
      print "There's no merchant here (that you can see...)"
      self.merchstate = 'normal'
  def buyArrows(self):
    if self.merchstate == 'buy' :
      if self.merchammo > 0:
        if self.loot >= 10:
          self.ammo = self.ammo + 5
          self.loot = self.loot - 10
          self.merchammo = self.merchammo - 5
          print "%s bought 5 arrows." % self.name
        else:
          print "Not enough gold."
      else:
        print "The merchant has no arrows."
    else:
      print "There's no merchant here (that you can see...)"
      self.merchstate = 'normal'
  def sell(self):
    if self.merchstate == 'buy' :
      if self.stim > 0:
        self.stim = self.stim -1
        self.loot = self.loot + 15
        self.merchstim = self.merchstim + 1
        print "%s sold 1 potion." % self.name
      else:
        print "%s has no potions to sell." % self.name
    else:
      print "There's no merchant here (that you can see...)"
      self.merchstate = 'normal'
  def weaponSell(self):
    if self.merchstate == 'buy' :
      if self.weapon != 'None':
        self.weapon = 'None'
        self.loot = self.loot + weapon.value
  def getEquipInfo(self): print "%s has a minDMG of %s and a maxDMG of %s\n%s has a defense of %s" % (self.weaponname, self.weapondamage, self.armorname, self.armordefense)
  def stim(self):
    if self.stim > 0:
      if self.health < self.health_max:
        self.health = self.health + 5
        self.stim = self.stim - 1
        print "You drink a potion and feel fucking awesome (+5 health)."
        if self.health > self.health_max:
          self.health = self.health_max
          print "%s is at full health." % self.name
      else:
        print "full health."
    else:
      print "no potions. =("
  def merch(self):
    self.merchstate = 'buy'
    self.merchstim = randint (0, 10)
    self.merchammo = randint (0, 50)
    if randint(0, 1):
      print("Merch weapon: {} , Stats: {}".format(merch_weapon,weapon_dict[merch_weapon]))
      print("Merch armor: {} , Stats: {}".format(merch_armor, armor_dict[merch_armor]))
    print "%s goes to the Merchants' Clearing." % self.name
    print "Merchant's items:\n~Potions:%d\n~Arrows:%d\n" % (self.merchstim, self.merchammo)
  def tired(self):
    print "%s feels tired." % self.name
    self.health = max(1, self.health - 1)
  def rest(self):
    if self.state != 'normal': print "%s can't rest now!" % self.name; self.enemy_attacks()
    else:
      print "%s finds a secluded spot, unrolls his sleeping pad, and rests." % self.name
      if randint(0, 7) > 5:
        self.enemy = Enemy(self)
        print "%s is awakened by a %s!" % (self.name, self.enemy.name)
        self.state = 'fight'
        self.enemy_attacks()
      else:
        if self.health < self.health_max:
          self.health = self.health + 1
        else:
          print "%s awakens feeling refreshed." % self.name; self.health = self.health - 1
  def areas(area1, n=1):
    a1 = area1.split('\n')
    random.shuffle(a1)
    area = []
    for a in range(n):
      try:
        s = a1[a]
        s = s.capitalize() + '.'
        area.apped(s)
      except IndexError:
        break
    return area
  def flee(self):
    if self.state != 'fight': print "%s runs in circles for a while, squawking like a seagull. That'll teach you to fuck around." % self.name; self.tired()
    else:
      if randint(1, self.health + 5) > randint(1, self.enemy.health):
        print "%s flees from the %s." % (self.name, self.enemy.name)
        self.enemy = None
        self.state = 'normal'
      else: print "%s couldn't escape from the %s!" % (self.name, self.enemy.name); self.enemy_attacks()
  def explore(self):
    self.oofammo()
    self.merchstate = 'normal'
    if self.state != 'normal':
      print "%s is too busy right now!" % self.name
      self.enemy_attacks()
    elif self.ammo > 0:
      print "%s wanders a bit." % (self.name)
      if randint(0, 1):
        self.enemy = Enemy(self)
        print "%s encounters a %s!\nEnemy hp: %d." % (self.name, self.enemy.name, self.enemy.health)
        self.state = 'fight'
  def merch_weapon(self):
    if self.merchstate == 'buy':
      self.merch_weapon = random.choice(list(weapon_dict.keys()))
  def merch_armor(self):
    if self.merchstate == 'buy':
      self.merch_armor = random.choice(list(armor_dict.keys()))
  def attack(self):
    if self.state != 'fight':
      print "%s wacks a tree; the tree's feelings are hurt." % self.name; self.tired()   
    else:
      if self.do_damage(self.enemy):
        print "%s headshots %s!" % (self.name, self.enemy.name)
        self.enemy = None
        self.state = 'normal'
        eloot = randint(0, 25)
        self.loot = eloot + self.loot
        print "You recovered %d gold from the corpse." %(eloot)
        eammo = randint (0, 5)
        self.ammo = eammo + self.ammo
        print "You recovered %d arrows from the corpse." %(eammo)
        stimp = randint(0, 4)
        if stimp == 0:
          self.stim = self.stim +1
          print "You found a potion!"
        if randint(0, self.health_max) == 10:
          self.level = self.level + 1
          self.health = self.health + 1
          self.health_max = self.health_max + 1
          print "%s feels stronger!" % self.name
      else:
        self.enemy_attacks()
  def enemy_attacks(self):
    if self.enemy.do_damage(self): print "%s was slaughtered by %s!\nGAME OVER\n" %(self.name, self.enemy.name)

weapon_dict = {"None"             : [0, 0],
               "Imaginary Sword"  : [0, 0],
               "Twig"             : [0, 1],
               "Rock"             : [0, 2],
               "Stick"            : [0, 3],
               "Dagger Handle"    : [1, 3],
               "Rusty Spoon"      : [1, 3],
               "Stake"            : [2, 3],
               "Dirk"             : [5, 4],
               "Magic Slingshot"  : [7, 5],
               "Wooden Sword"     : [8, 6],
               "Petrified Wood Sword" : [14, 8],
               "Shortsword"       : [15, 11],
               "Rapier"           : [17, 12],
               "Spatha"           : [20, 14],
               "Reforged Steel Shortsword" : [23, 15],
               "Longsword"        : [25, 16],
               "Steel War Axe"    : [28, 17],
               "Reinforced Steel Longsword" : [30, 19],
               "Short Spear"      : [35, 20],
               "Heavy Battleaxe"  : [45, 21],
               "Greatsword"       : [50, 23],
               "Poleaxe"          : [55, 25],
               "Warhammer"        : [60, 28],
               "Callandor"        : [200, 60]
               }

armor_dict = {"None"            : [0,0],
              "Saran Wrap"      : [0,0],
              "Imaginary Armor" : [0,0],
              "Woolen Dress"    : [3,1],
              "Clothes"         : [3,1],
              "Sheepskin Coat"  : [4,2],
              "Wooden Armor"    : [4,2],
              "Leather Jerkin"  : [5,3],
              "Two Leather Jerkins" : [6,4],
              "Rusted Chainmail" : [6,4],
              "Polished Chainmail" : [10,5],
              "Iron Breastplate" : [16,6],
              "Iron Breasplate and Chainmail" : [20,7],
              "Steel Breasplate" : [25,8],
              "Steel Suit"      : [35,11],
              "Reinforced Steel Suit" : [45,13],
              "Reforged Steel Alloy Suit" : [55,14],
              "Warcloth"        : [60,15],
              "Warmail"         : [70,17],
              "Warplate"        : [85,21],
              "Warsuit"         : [90,23]
              }

merch_weapon = random.choice(list(weapon_dict.keys()))
merch_armor = random.choice(list(weapon_dict.keys()))

Commands = {
  'quit': Player.quit,
  'help': Player.help,
  'stat': Player.status,
  'rest': Player.rest,
  'e': Player.explore,
  'run': Player.flee,
  'a': Player.attack,
  'p': Player.stim,
  'merch': Player.merch,
  'buy potion': Player.buyPotion,
  'buy arrows': Player.buyArrows,
  'sell': Player.sell,
  'sw': Player.weaponSell,
  'eqi': Player.getEquipInfo
  }

p = Player()
print ''
print "Welcome to the land of Grer, a realm in turmoil due to the recent disposition"
print "of the beloved king Quolin. You shall seek your fortune in the dissolution, for"
print "riches may be made in such times of strife."
print ''
p.name = raw_input("What is your character's name? ")
print ''
print "(type help at any time to get a list of actions)\n"
print "%s enters a dark forest, searching for adventure." % p.name
while(p.health > 0):
  line = raw_input(">>> ")
  args = line.split()
  if len(args) > 0:
    commandFound = False
    for c in Commands.keys():
      if args[0] == c[:len(args[0])]:
        Commands[c](p)
        commandFound = True
        break
    if not commandFound:
      print "%s doesn't understand the suggestion." % p.name
Velcrode
 
Posts: 12
Joined: Sat Jun 29, 2013 3:41 am


Return to Game Development

Who is online

Users browsing this forum: Google [Bot] and 3 guests