* move examples to a more canonical location
[pyion.git] / examples / ohritem.py
blob0c94e7ff5d325344816c381e056cd0c9285f883e
1 """
2 OHRRPGCE/FF6 style random item selection (percentage probability based)
3 """
5 from ion.n.random import percent
6 def got_item (info):
7 """ Illustrates OHRRPGCE's behaviour giving items after battle.
8 XXX make this into an example.
9 Pass a tuple (item, item %, rareitem, rareitem %) as the info parameter.
12 Returns
13 -------
14 item : object
15 One of (item, rareitem, -1) (where -1 indicates nothing dropped)
17 Notes
18 -----
19 equivalent to::
21 tmp = chain (((item %, item), (rareitem %, rareitem)))
22 if tmp:
23 return tmp[-1]
24 return -1
26 """
28 if percent (info[1]):
29 # rareitem's chance to drop:
30 # (100% - item%) * rareitem%
32 # eg. item% == 50, rareitem% == 50
33 # drop item 25% of the time,
34 # rareitem 25% of the time,
35 # nothing 50% of the time.
37 # with rareitem% == 25:
38 # item 37.5%
39 # rareitem 12.5%
40 # nothing 50%
42 if percent ((info[3] * (100 - info[1])) / 100 ):
43 return info[2] # rareitem
44 else:
45 return info[0] # item
46 else:
47 return -1 # nothing :(
49 # expressed in weighted sampling:
51 # remainder = float (100 - info[1])
53 # return weightedSample ((info[0],info[2], -1), (info[1],
54 # (remainder / 2.0) * (info[3]/100.0), remainder / 2.0)
56 # In more general, weighting is like:
57 # item @ item%
58 # item2 @ remainder
59 # item3 @ i2remainder
60 # item4 @ i3remainder
61 # None @ allremainder
63 # With remainders weighted into the previous remainder space.
66 # say, 50% 40% 30% 20%
68 # then..
69 # 50% chance of 1
70 # 20% (40% * 50%) chance of 2
71 # 8% (30% * (100% - (50% + 20%))) chance of 3
72 # 4.2% chance (20% * (100% - (50% + 20% + 8%)) ) of 4
73 # 16.8% chance (20% * (100% - (50% + 20% + 8% + 4.2%)) ) of None
75 # to be precise (percentages expressed like 1.00 == 100%)
77 # weights = []
78 # weights.append (factorlist[0])
79 # factorlist.pop(0)
81 # for fac in factorlist:
82 # weights.append ((fac / 100.0) * (100.0 - sum(weights)))
84 # weights.append (100.0 - sum(weights))
86 # examples:
92 # a dictionary mapping number -> name
93 lut = {
94 -1: "Nothing",
95 1: "Item",
96 2: "RareItem",
99 print '100, 100:'
100 #give item, never rareitem or nothing:
101 for i in range (16):
102 print lut[ got_item ((1, 100, 2, 100))]
105 print '\n\n50, 50:'
106 # give item 50% of the time, rareitem 25% of the time,
107 # or nothing 25% of the time:
108 for i in range (32):
109 print lut[ got_item ((1, 50, 2, 50))]
112 print '\n\n75, 33:'
113 # give item 75% of the time, rareitem 8% of the time,
114 # or nothing 17% of the time:
116 for i in range (32):
117 print lut[ got_item ((1, 75, 2, 33))]