Putting the 'role' back in role-playing games since 2002.
Donate to Codex
Good Old Games
  • Welcome to rpgcodex.net, a site dedicated to discussing computer based role-playing games in a free and open fashion. We're less strict than other forums, but please refer to the rules.

    "This message is awaiting moderator approval": All new users must pass through our moderation queue before they will be able to post normally. Until your account has "passed" your posts will only be visible to yourself (and moderators) until they are approved. Give us a week to get around to approving / deleting / ignoring your mundane opinion on crap before hassling us about it. Once you have passed the moderation period (think of it as a test), you will be able to post normally, just like all the other retards.

Vapourware Trying to learn programming from ~0, realistic goals naturally help needed.

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
ok i almost figured it out but :
Code:
for bullet in vendor_goods_list:
    if bullet == '9mm bullet' or bullet == '5.56 bullet':
        count = 0
        while count < 19:
            vendor_goods_list.append(bullet)
            count += 1
            print bullet

this creates infinite loop for some reason. but vendor_goods_list is finite !


edit:

Ok i got this @.@ I forgot to make list copy and i operated on actual list !.
Beautiful case when i finally see with my own eyes that i should first make copy of list instead of operating on original.

This is a a shorter solution:

Code:
import itertools as it
for bullet in vendor_goods_list[:]:
  if bullet == '9mm bullet' or bullet == '5.56 bullet':
    vendor_goods_list.extend(it.repeat(bullet, 19))
 
Last edited:

k-t

Novice
Joined
Oct 29, 2012
Messages
18
This is a a shorter solution:

There is even shorter solution:
Code:
for bullet in filter(lambda x: x in ['9mm bullet', '5.56 bullet'], vendor_goods_list):
    vendor_goods_list.extend([bullet] * 19)

:smug:
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
Thanks people for input. I know there is lambda and shorter versions but for now i need to focus to train simple forms. I plan to fiddle with lambda later.

Ok i did vendor program

Idea behind it is that i will create program that will randomly generate vendor inventory from datastructures (in this case dicts and lists. You may notice that list also contains price for every item. Which is something i plan to go back in future as i will need to back to it considering i want to create small game.

Compiled program: vendor (inside it run vendor.exe)
you will need: python 2.7.8
pure .py file: vendor.py

raw code:

Code:
import random

# Vendor script - Generation of items table and displaying it to player

# dictionaries, lists and variables  with data i will use later in code, some may be not used
item_types = ['ammo', 'food', 'weapons']
item_type_weapons = {'knife': 15, 'hammer': 21, '9mm pistol': 67, '5.56 hunting rifle': 240}
item_type_ammo = {'9mm bullet': 3, '5.56 bullet': 15}
item_type_food = {'beef jerky': 12, 'bottle of water': 6, 'can of meat': 26, 'maize': 13}
vendor_names = ['Jack', 'Will', 'Sam']
amount_of_items = random.randrange(4, 15)  # generating number of items available for vendor
vendor_goods_list = []
current_item_list = []
count = 0
# code below

vendor_name = vendor_names[random.randrange(len(vendor_names))]

# creating list which I will later use for assuming price and number of items of same type to sort and get number of x items
for weapon in item_type_weapons:
    current_item_list.append(weapon)
for ammo in item_type_ammo:
    current_item_list.append(ammo)
for food in item_type_food:
    current_item_list.append(food)

while count < amount_of_items:
    vendor_goods_list.append(current_item_list[random.randrange(len(current_item_list))])
    count += 1

# checks vendor_goods_list for bullet type and creates random amount of it from 15 to 43

for bullet in vendor_goods_list[:]:
    if bullet == '9mm bullet' or bullet == '5.56 bullet':
        count = 0
        while count < random.randrange(15, 43):
            vendor_goods_list.append(bullet)
            count += 1

# Crude way to show in vendor amount of bullets instead of every single one

bullets9 = 0
for bullet in vendor_goods_list:
    if bullet == '9mm bullet':
        bullets9 += 1

bullets556 = 0
for bullet in vendor_goods_list:
    if bullet == '5.56 bullet':
        bullets556 += 1

# sorting list to not get nicely sorted list
vendor_goods_list.sort()

# Shop initialization
# crude way of doing it but it got job done
print
print "Welcome to my shop, my name is %s" % vendor_name
print "These are my wares: "
print
print "------WEAPONS---------"
for weapon in vendor_goods_list:
    if weapon in item_type_weapons:
        print weapon
print "--------AMMO----------"
if bullets9 > 0:
    print bullets9, " 9mm bullets"
if bullets556 > 0:
    print bullets556, " 5.56mm bullets"
print "--------FOOD----------"
for food in vendor_goods_list:
    if food in item_type_food:
        print food

raw_input("I put it in just to stop program from quiting after it is done")

I know this is very crude way of doing things but this is my first real program without looking at any help (beside import function at start). I am sure that i could reduce that at least to half its size.
I simply wanted to test my idea. If i could plan something and then realize it.

So for now GOAL2b is done
 
Last edited:

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
I suggest you look up those python docs I linked you to, and check what methods are available with types you use.

For example this:
Code:
vendor_name = vendor_names[random.randrange(len(vendor_names))]
can be shortened to:
Code:
vendor_name = random.choice(vendor_names)

Also doing this:
Code:
for weapon in item_type_weapons:
  current_item_list.append(weapon)
can be shortened to:
Code:
 current_item_list.extend(item_type_weapons.keys())
etc.

Here is the link again: https://docs.python.org/2.7/library/index.html

When you see that you are repeating something a lot and seems like something that is very common in programming look through the library for a function that does that.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
yeah i know that i can shorten a lot list just by spending more time on it or if i scroll through python library.
Also i decided that i will focus on training simple stuff (as training concepts behind things instead of function memorization) in GOAL2

GOAL 3 will be to learn C# syntax and do stuff from then in C# as this is what many people suggest me.
 

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
yeah i know that i can shorten a lot list just by spending more time on it or if i scroll through python library.
Also i decided that i will focus on training simple stuff (as training concepts behind things instead of function memorization) in GOAL2

GOAL 3 will be to learn C# syntax and do stuff from then in C# as this is what many people suggest me.

Then you may as well switch to C# now.
Learning a language is also learning its standard library.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
For short while i just want to practice what i learned in that python training program. Do some actual programs of my own and this is whole point of GOAL2. GOAL2 shouldn't take more than day or two.

ok now i start writing combat. Should be fun.
 

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
For short while i just want to practice what i learned in that python training program. Do some actual programs of my own and this is whole point of GOAL2. GOAL2 shouldn't take more than day or two.

ok now i start writing combat. Should be fun.

Yeah, well I see no point then in Goal3. Why would you learn C# and give up on Python? You could have started with C# then... What if a lot of people recommend another language during you learning C# will you switch to that?
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
I started with Python because course @ code academy was awesome. There is no C# course like that @ codeacademy nor i could find similar one.

First i will do GOAL2 to practice ideas and implementations
In GOAL 3 i will find what is C# in basic form and what is difference (like syntax andstuff)

Considering i have Python experience under my belt i should learn basic stuff much quicker.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
Ok i did simple combat script:

Compiled program: combat (inside it run combat.exe)
you will need: python 2.7.8
pure .py file: combat.py

Idea: Create situation in which player will need to choose a weapon and fight enemy. Player will be able to target head or body. Both enemy and player will have a chance to hit and player target head action will have smaller chance to hit but will have much more damage than normal body shot.

I tried to stay away from functions for now. Wanted to practice lists,dictionaries and code structure (in code with more than 10-20lines).

raw code:

Code:
import random

def clear(num):
    for i in range(num):
        print


enemy_hp = random.randrange(50, 150)
player_hp = 100
weapon_stats = {'knife': 15, 'hammer': 21, '9mm pistol': 67, '5.56 hunting rifle': 240}
weapons_list = ['knife', 'hammer', '9mm pistol', '5.56 hunting rifle']
weapon = []

print "======================================"
print "You found yourself in combat situation"
print "There is cabinet with weapons"
print " Content of cabinet: "
print "---------------"
for x in weapons_list:
    print x
print "---------------"
print
print "which weapon you take out of cabinet ?"

answer = raw_input("Make your choice : ")

for x in weapons_list:
    if x == answer:
        weapon.append(x)

print "You took", weapon, " armed with it you hope to prevail"
print

while enemy_hp > 0 and player_hp > 0:

    print "    ", player_hp, " PLAYER HEALTH"
    print "    ", enemy_hp, " ENEMY HEALTH"
    print "=============================================================="
    print "You have option to attack HEAD or BODY, which do you choose ?"
    print "(targeting head has lower chance of success but damage is much more lethal !)"

    answer2 = raw_input("select a or b: ")

    if answer2 == "a":
        if random.randrange(1, 20) > 15:
            enemy_hp -= (4 * weapon_stats[weapon[0]])
            clear(40)
            print "You struck enemy !"
            if random.randrange(1, 20) > 10:
                player_hp -= 20
                print "Enemy struck you !"
                print

            else:
                print "enemy missed"
                print

        else:
            clear(40)
            print " You missed "
            if random.randrange(1, 20) > 10:
                player_hp -= 20
                print "Enemy struck you !"
                print
            else:
                print "enemy missed"
                print

    elif answer2 == "b":
        if random.randrange(1, 20) > 7:
            enemy_hp -= weapon_stats[weapon[0]]
            clear(40)
            print "You struck enemy !"
            if random.randrange(1, 20) > 10:
                player_hp -= 20
                print "Enemy struck you !"
                print
            else:
                print "enemy missed"
                print

        else:
            clear(40)
            print " You missed "
            if random.randrange(1, 20) > 10:
                player_hp -= 20
                print "Enemy struck you !"
                print
            else:
                print "enemy missed"
                print

print "=============="
print "=============="
print "=============="

if player_hp <= 0:

    print "You died today"
else:
    print "You live another day"

raw_input("")
 

baturinsky

Arcane
Joined
Apr 21, 2013
Messages
5,538
Location
Russia
Btw, http://pastebin.com/ is a good service to show pieces of code

thanks. what is difference between pastebin and rpgcodex [code| ?

Minor, but nice things, like syntax highlight or using full height of screen. http://pastebin.com/bLE7hw9F

question. Can dictionary be more deep ?

I mean for example something like this : { "robert" : 234 : 12313 : 2323 }

You can nest dictionaries and/or arrays. Something like this, not sure it works in Python particularly. { "robert" : {234 : [12313 , 2323]} }
 

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
Btw, http://pastebin.com/ is a good service to show pieces of code

thanks. what is difference between pastebin and rpgcodex [code| ?

Minor, but nice things, like syntax highlight or using full height of screen. http://pastebin.com/bLE7hw9F

question. Can dictionary be more deep ?

I mean for example something like this : { "robert" : 234 : 12313 : 2323 }

You can nest dictionaries and/or arrays. Something like this, not sure it works in Python particularly. { "robert" : {234 : [12313 , 2323]} }

Just to confirm, yes it works. That is actually correct syntax (dictionary with a dictionary which has a list). You can also have dictionaries inside lists.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
I have a bit of problem:

Code:
def make_weapon(name):
    name["name"] = name
    name["type"] = random.choice(weapon_types)
    name["material"] = random.choice(weapon_materials)
    name["damage"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] + weapon_type_sharpness[name["type"]]
    name["weight"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]]
    name["price"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] * weapon_materials_price[name["material"]]
    return name

I am trying to define function that will create dictionary which will be my created weapon. Problem is that it seems that string i input can't be used as name for variable. Does that mean i need to create weapon in other way and then give it name ?

PyCharm interpreter gives me this error:

Code:
=============================
=      WEAPON GENERATOR     =
=============================

===================================================================================
= Upon naming weapon this program will first create weapon from TYPE and MATERIAL =
=        Then it will calculate stats of weapon: DAMAGE , WEIGHT, PRICE           =
===================================================================================

name your weapon : alora
Traceback (most recent call last):
  File "D:/Coding/Projects/PyCharm/Vendor/weapon_generator.py", line 84, in <module>
    make_weapon(weapon_created)
  File "D:/Coding/Projects/PyCharm/Vendor/weapon_generator.py", line 52, in make_weapon
    name["name"] = name
TypeError: 'str' object does not support item assignment

Process finished with exit code 1

full raw code:

Code:
import random

# weapon material its weight and price
weapon_materials = ['gold', 'silver', 'iron', 'bronze', 'steel', 'obsidian']
weapon_materials_weight = {
    'gold': 70,
    'silver': 50,
    'iron': 40,
    'bronze': 30,
    'steel': 50,
    'obsidian': 20
}
weapon_materials_price = {
    'gold': 1000,
    'silver': 500,
    'iron': 100,
    'bronze': 50,
    'obsidian': 10,

}

# weapon type, sharpness, weapon weight modifier and weapon type price
weapon_types = ['flail', 'longsword', 'shortsword', 'spear', 'warhamer', 'mace']
weapon_type_sharpness = {
    'flail': 10,
    'longsword': 50,
    'shortsword': 50,
    'spear': 100,
    'warhamer': 10,
    'mace': 20
}
weapon_type_weight_mod = {
    'flail': 10,
    'longsword': 5,
    'shortsword': 3,
    'spear': 3,
    'warhamer': 20,
    'mace': 15
}
weapon_type_price = {
    'flail': 3,
    'longsword': 7,
    'shortsword': 4,
    'spear': 1,
    'warhamer': 1,
    'mace': 5
}

# FUNCTIONS

def make_weapon(name):
    name["name"] = name
    name["type"] = random.choice(weapon_types)
    name["material"] = random.choice(weapon_materials)
    name["damage"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] + weapon_type_sharpness[name["type"]]
    name["weight"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]]
    name["price"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] * weapon_materials_price[name["material"]]
    return name

def weapon_description(weapon):
    print
    print "The %s, a %s %s" % (weapon["name"], weapon["material"], weapon["type"])
    print "=====STATS======"
    print "damage   - ", weapon["damage"]
    print "weight   - ", weapon["weight"], "|O"
    print "price    - ", weapon["price"], "G"
    print
    return True


# WEAPON GENERATOR CODE BELOW

print "============================="
print "=      WEAPON GENERATOR     ="
print "============================="
print
print "==================================================================================="
print "= Upon naming weapon this program will first create weapon from TYPE and MATERIAL ="
print "=        Then it will calculate stats of weapon: DAMAGE , WEIGHT, PRICE           ="
print "==================================================================================="
print

weapon_created = raw_input("name your weapon : ")
make_weapon(weapon_created)
 

28.8bps Modem

Prophet
Joined
Jan 15, 2014
Messages
302
Location
The Internet, Circa 1993
You're overloading the variable "name". It's the parameter you pass in, and it's of string type, not a dictionary, so when you try to assign to it as a dictionary it won't work.

Something like:
Code:
def make_weapon(name):
    weapon = dict()
    weapon ["name"] = name
    weapon ["type"] = random.choice(weapon_types)
    weapon ["material"] = random.choice(weapon_materials)
    weapon ["damage"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] + weapon_type_sharpness[name["type"]]
    weapon ["weight"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]]
    weapon ["price"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] * weapon_materials_price[name["material"]]
    return weapon

would work fine.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
Because directory is variable and when i will call it it will print out content not the variable name.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
You're overloading the variable "name". It's the parameter you pass in, and it's of string type, not a dictionary, so when you try to assign to it as a dictionary it won't work.

Something like:
Code:
def make_weapon(name):
    weapon = dict()
    weapon ["name"] = name
    weapon ["type"] = random.choice(weapon_types)
    weapon ["material"] = random.choice(weapon_materials)
    weapon ["damage"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] + weapon_type_sharpness[name["type"]]
    weapon ["weight"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]]
    weapon ["price"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] * weapon_materials_price[name["material"]]
    return weapon

would work fine.

yes i know something like this will work. Problem is that it will return variable weapon and whole point of this script is to create new variables that are directories.

My idea is that if for example i will imput "bigsword2" then this script would create variable bigsword2 containing directory. In that case i would be able to use create such variable in code.

TLDR i want to input for example string fuckingsword and it should return me variable fuckingsword with directory in it.
 

baturinsky

Arcane
Joined
Apr 21, 2013
Messages
5,538
Location
Russia
Maybe you should start using classes.

Also, is foo.bar and foo["bar"] the same thing in Python?
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,883
Maybe you should start using classes.

Also, is foo.bar and foo["bar"] the same thing in Python?

Yeah that was also idea but i try for now doing stuff without them. I guess it is one of those things you need OO
 

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
You're overloading the variable "name". It's the parameter you pass in, and it's of string type, not a dictionary, so when you try to assign to it as a dictionary it won't work.

Something like:
Code:
def make_weapon(name):
    weapon = dict()
    weapon ["name"] = name
    weapon ["type"] = random.choice(weapon_types)
    weapon ["material"] = random.choice(weapon_materials)
    weapon ["damage"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] + weapon_type_sharpness[name["type"]]
    weapon ["weight"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]]
    weapon ["price"] = weapon_materials_weight[name["material"]] * weapon_type_weight_mod[name["type"]] * weapon_materials_price[name["material"]]
    return weapon

would work fine.

yes i know something like this will work. Problem is that it will return variable weapon and whole point of this script is to create new variables that are directories.

My idea is that if for example i will imput "bigsword2" then this script would create variable bigsword2 containing directory. In that case i would be able to use create such variable in code.

TLDR i want to input for example string fuckingsword and it should return me variable fuckingsword with directory in it.

If I understand you corectly you want the function which creates a variable with given name which is a reference to a dictionary (not directory)? Then you want to access that variable in code by typing the given name?
For example:
Code:
create_weapon("shiny_weapon")
print shiny_weapon
Why do you want to do that? And how do you plan on using that variable in code if you don't know its name before running the programme?
Btw such thing is possible (but requires some advanced Python manipulation) and I see no point in doing it.
 

28.8bps Modem

Prophet
Joined
Jan 15, 2014
Messages
302
Location
The Internet, Circa 1993
yes i know something like this will work. Problem is that it will return variable weapon and whole point of this script is to create new variables that are directories.

Hrm, I think we may be talking at cross purposes.

You know that calling the function twice, like:

Code:
dagger = make_weapon("dagger of smiting")
bow = make_weapon("bow of vicious maiming +1")

creates two different variables, right?

"return weapon" is not returning a reference, it's copying the value of "weapon." (which is a good thing, since local values are allocated on the stack and will go out of scope and possibly be overwritten when a function returns.)
 

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
yes i know something like this will work. Problem is that it will return variable weapon and whole point of this script is to create new variables that are directories.

Hrm, I think we may be talking at cross purposes.

You know that calling the function twice, like:

Code:
dagger = make_weapon("dagger of smiting")
bow = make_weapon("bow of vicious maiming +1")

creates two different variables, right?

"return weapon" is not returning a reference, it's copying the value of "weapon." (which is a good thing, since local values are allocated on the stack and will go out of scope and possibly be overwritten when a function returns.)

Actually "return weapon" will return a reference and there will be no copying of dictionary since python will allocate the inital "weapon" dictionary on the heap. But your example is probably what Perkel wants to do.
 

As an Amazon Associate, rpgcodex.net earns from qualifying purchases.
Back
Top Bottom