SlideShare ist ein Scribd-Unternehmen logo
1 von 8
Downloaden Sie, um offline zu lesen
pyDie
I created pyDie as a re-usable die class program for games or for any program that need a random
probabilities based upon dice or dice like entities. In order to use pyDie you must import the class just
like any Python library. It contains two classes (die and cup).

The die class can be initialized simply by passing a single parameter defining the number of sides
(myDie = pyDie.die(6)) The library will then proceed to create a default die using the number of sides
provided with values starting at 1 and incrementing by 1's till all sides are filled. You may also pass a
second parameter for the low value and create a specialized die based upon the sides and the low value
you assign (such as myDie = pyDie.die(6, 4) creates a die with values from 4 through 9). A third
parameter can be use to set the high value but beware if you specify a low and high value that does not
have a large enough range for the number of sides you specify pyDie will create the die with the right
number of sides and try to make an intelligent decision about the range. Also if you mistakenly make
the low value greater than the high value, pyDie will again attempt to make an intelligent decision
regarding the layout of the die. The last possible parameter for initializing your die is the
incrementation value. This allows you to create dice that increment greater than one number at a time.
An example of this would be (myDie = pyDie.die(8, 1, 16, 2) results in a die with possible values of 1,
3, 5, 7, 9, 11, 13, 15).

Once you have initialized your die you can call the roll method which will randomly choose a value
from your list of possibilities. You can accomplish this by using myDie.roll(), you can then access this
result using the newly created attribute called value (print myDie.value).

The second class in pyDie is the cup class which allows you to store multiple dice and even roll them
all at one time. You can create your cup simply by using myCup = pyDie.cup(). You would then add
your die to the cup using myCup.add(myDie). You can then use the throw method to throw all dice in
the cup (myCup.throw()). You would then access each die's value using the attribute for each die in the
cup. The cup class also has an empty method which clears all dice from the cup, and a remove method
which can be used to remove a single die from the cup simply by using myCup.remove(myDie).

The following is an example of die and cup creation:
import pyDie

myDie = []
cup = pyDie.cup()
# Create 4 standard die
for i in range (1, 5):
   myDie.append(pyDie.die(6))
# Create one eight sided that starts with 10
# and increments by 5's
myDie.append(pyDie.die(8, 10, 50, 5))
# Create one final die that is 10 sided
# and begins with 0 and decrements by 2's
myDie.append(pyDie.die(10, -20, 0, -2))

for die in myDie:
   cup.add(die)

cup.throw()
total=0
print "Die paramaters: (sides, low, high, [range])"
for die in cup.dice:
   total = total + die.value
   print "(%i, %i, %i, %s)"%(die.sides, die.low, die.high, die.possible)
   print "Result of throw for this die: %i"%die.value
   print "--------------------------------------------"

print "Total of all dice: %i"%total




The first four die are standard followed by two non-standard configurations.

In this example we create five standard dice:
import pyDie

myDie = []
cup = pyDie.cup()
# Create 5 standard die
for i in range (1, 6):
   myDie.append(pyDie.die(6))

for die in myDie:
   cup.add(die)

cup.throw()
for die in cup.dice:
   print die.value
Now we will look at some of the intelligent choices that pyDie makes when odd parameters are passed
to it. This test script was used to test pyDie, and although not pretty, it does demonstrate the power and
flexibility of this library.
import pyDie

print "A cup for the dice"
cup = pyDie.cup()

print "A standard die..."
die1 = pyDie.die(6)
print "Die sides=%i, low=%i, high=%i, range=%s"%(die1.sides, die1.low, die1.high, die1.possible)
die1.roll()
print "Result of roll %i"%die1.value
print "Add die to cup"
cup.add(die1)
print "--------------------------------------n"

print "A non-standard 8 sided die"
die2 = pyDie.die(8)
print "Die sides=%i, low=%i, high=%i, range=%s"%(die2.sides, die2.low, die2.high, die2.possible)
die2.roll()
print "Result of roll %i"%die2.value
print "Add die to cup"
cup.add(die2)
print "--------------------------------------n"

print "An 8 sided die with low > high"
die3 = pyDie.die(8, 4, -3)
print "Die sides=%i, low=%i, high=%i, range=%s"%(die3.sides, die3.low, die3.high, die3.possible)
die3.roll()
print "Result of roll %i"%die3.value
print "Add die to cup"
cup.add(die3)
print "--------------------------------------n"


print "Parameters 6, 2, 8, 1"
die4 = pyDie.die(6, 2, 8)
print "Die sides=%i, low=%i, high=%i, range=%s"%(die4.sides, die4.low, die4.high, die4.possible)
die4.roll()
print "Result of roll %i"%die4.value
print "Add die to cup"
cup.add(die4)
print "--------------------------------------n"


print "An eight sided die starting at 10..."
die5 = pyDie.die(8, 10)
print "Die sides=%i, low=%i, high=%i, range=%s"%(die5.sides, die5.low, die5.high, die5.possible)
die5.roll()
print "Result of roll %i"%die5.value
print "Add die to cup"
cup.add(die5)
print "--------------------------------------n"

print "A six sided die (6, 0, -5, -1)"
die6 = pyDie.die(6, 0, -5, -1)
print "Die sides=%i, low=%i, high=%i, range=%s"%(die6.sides, die6.low, die6.high, die6.possible)
die6.roll()
print "Result of roll %i"%die6.value
print "Add die to cup"
cup.add(die6)
print "--------------------------------------n"

print "Roll all die in cup at once"
cup.throw()
for die in cup.dice:
   print die.value

Note: Each highlighted line above illustrates different features of die creation
The first thing to note is that die1 = pyDie.die(6) is a simple default die creation. This is then followed by
die2 = pyDie.die(8) which is a non-standard eight sided die. The interesting part occurs with the third die
die3 = pyDie.die(8, 4, -3) which is created as an eight sided die but the low value is actually higher than the
high value which additionally is a negative number (Note: pyDie ignores the high value and creates the
die beginning with the low value and working up from there, and then sets the high value to the
appropriate value).
The next die created die4 = pyDie.die(6, 2, 8) is a six sided die starting at two and going to eight (since the
high value is outside of the range it is changed to the appropriate value). Following that is an eight
sided die beginning with 10 die5 = pyDie.die(8, 10), this is then followed by a six sided die die6 =
pyDie.die(6, 0, -5, -1) that starts at zero and decrements by one to -5. This is then followed by the throw of
the cup.
Roll all die in cup at once
3
8
7
4
16
-1

As you can see pyDie has been designed with simplicity in mind while still incorporating some
intelligence in order to avoid potential errors.
Source Code
The following is the pyDie source code.
# Program: pyDie.py
# Author: James D. Coen
# Date: 2009.12.11
# Purpose: This program is used to create a generic
#      die roll class so that it can be imported
#      and re-used in various ways

from random import randint, seed
from time import time

class die(object):
   """ A single die. """

  def __init__(self, sides, low=1, high=6, incr=1):
    """ The first argument is the number of sides
    the second is the lowest # possible (default 1)
    the third is the highest # possible (default 6)
    the fourth is the number to increment by (default 1)
    """

     self.sides = sides
     possible = []
     if incr == 0:
         incr = 1
     if incr < 0:
         if low < high:
             for i in range(high, low-1, incr):
                possible.append(i)
         elif low > high:
             for i in range(low, high-1, incr):
                possible.append(i)
         else:
             for i in range(0, sides+1*-1, incr):
                possible.append(i)
         possible.sort()
         while len(possible) > self.sides:
             possible.remove(possible[0])
             low = possible[0]

        while len(possible) < self.sides:
            possible.append(possible[0] + incr)
            possible.sort()
            low = possible[0]
     else:
        if low < high:
            for i in range(low, high+1, incr):
               possible.append(i)
        else:
            for i in range(low, low+sides+1, incr):
               possible.append(i)
        possible.sort()
        while len(possible) > self.sides:
            possible.remove(possible[len(possible)-1])
            high = possible[len(possible)-1]
while len(possible) < self.sides:
          possible.append(possible[len(possible)-1] + incr)
          high = possible[len(possible)-1]

     if low < high:
         self.high = high
         self.low = low
     elif low > high:
         self.low = high
         self.high = low
     else:
         self.low = possible[0]
         self.high = possible[len(possible)-1]
     self.possible = possible

  def roll(self):
    """ Role the die """
    seed(time() * time() * self.sides)
    self.value = randint(self.low, self.high)
    if self.value not in self.possible:
       while self.value not in self.possible:
          self.value = randint(self.low, self.high)

class cup(object):
   """ A cup full of dice. """
   def __init__(self):
     self.dice = []

  def empty(self):
    self.dice = []

  def add(self, die):
    self.dice.append(die)

  def remove(self, die):
    self.dice.remove(die)

  def throw(self):
    for die in self.dice:
        die.roll()

It must be noted that pyDie works extremely well on Linux but there seems to be a problem with the
randomness on the Window's platform that I have not take time to analyze as I do not use this platform
regularly.

Weitere ähnliche Inhalte

Was ist angesagt?

Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
関数プログラミングことはじめ revival
関数プログラミングことはじめ revival関数プログラミングことはじめ revival
関数プログラミングことはじめ revivalNaoki Kitora
 
The Ring programming language version 1.9 book - Part 55 of 210
The Ring programming language version 1.9 book - Part 55 of 210The Ring programming language version 1.9 book - Part 55 of 210
The Ring programming language version 1.9 book - Part 55 of 210Mahmoud Samir Fayed
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
 
Feature-Engineering-Earth-Advocacy-Project-2015
Feature-Engineering-Earth-Advocacy-Project-2015Feature-Engineering-Earth-Advocacy-Project-2015
Feature-Engineering-Earth-Advocacy-Project-2015Ankoor Bhagat
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
Creating masterpieces with raphael
Creating masterpieces with raphaelCreating masterpieces with raphael
Creating masterpieces with raphaelPippi Labradoodle
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212Mahmoud Samir Fayed
 
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDBScala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDBjorgeortiz85
 
Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310Putu Shinoda
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版Yutaka Kato
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...
V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...
V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...DevClub_lv
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
Python tutorial
Python tutorialPython tutorial
Python tutorialRajiv Risi
 
Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in phpChetan Patel
 

Was ist angesagt? (20)

Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
関数プログラミングことはじめ revival
関数プログラミングことはじめ revival関数プログラミングことはじめ revival
関数プログラミングことはじめ revival
 
The Ring programming language version 1.9 book - Part 55 of 210
The Ring programming language version 1.9 book - Part 55 of 210The Ring programming language version 1.9 book - Part 55 of 210
The Ring programming language version 1.9 book - Part 55 of 210
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
Feature-Engineering-Earth-Advocacy-Project-2015
Feature-Engineering-Earth-Advocacy-Project-2015Feature-Engineering-Earth-Advocacy-Project-2015
Feature-Engineering-Earth-Advocacy-Project-2015
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
Creating masterpieces with raphael
Creating masterpieces with raphaelCreating masterpieces with raphael
Creating masterpieces with raphael
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
 
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDBScala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
 
Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310Tugas 3 oganisasi komputer 23510310
Tugas 3 oganisasi komputer 23510310
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...
V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...
V8 by example: A journey through the compilation pipeline by Ujjwas Sharma at...
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in php
 

Andere mochten auch

Las mejores imagenes d internet
Las mejores imagenes d internetLas mejores imagenes d internet
Las mejores imagenes d internetMireia Buchaca
 
Collages by Oana Catalina Gavriliu
Collages by Oana Catalina GavriliuCollages by Oana Catalina Gavriliu
Collages by Oana Catalina Gavriliugrafoana
 
Les Metamorphose1
Les Metamorphose1Les Metamorphose1
Les Metamorphose1dcbrucelee
 
Huong dan MS.Project
Huong dan MS.ProjectHuong dan MS.Project
Huong dan MS.ProjectDinh Xuan Tho
 
Cars and pollution. ruben garcia
Cars and pollution. ruben garciaCars and pollution. ruben garcia
Cars and pollution. ruben garciaM.Amparo
 
XWiki SAS
XWiki SASXWiki SAS
XWiki SASXWiki
 
MATEMATIK TAHUN 4..KERTAS 2
MATEMATIK TAHUN 4..KERTAS 2MATEMATIK TAHUN 4..KERTAS 2
MATEMATIK TAHUN 4..KERTAS 2Shan Kmtg Crew
 
Modele Avec Des Images Fortes (Our Copil Projet Id Zone)
Modele Avec Des Images Fortes (Our Copil Projet Id Zone)Modele Avec Des Images Fortes (Our Copil Projet Id Zone)
Modele Avec Des Images Fortes (Our Copil Projet Id Zone)shudyka
 
When our superheroes went in action with groupchat to save the city.
When our superheroes went in action with groupchat to save the city.When our superheroes went in action with groupchat to save the city.
When our superheroes went in action with groupchat to save the city.ProofHub
 
Grant proposal checklist handout
Grant proposal checklist handoutGrant proposal checklist handout
Grant proposal checklist handoutRAFI-USA
 
Sevilla luces y sombras 6
Sevilla luces y sombras 6Sevilla luces y sombras 6
Sevilla luces y sombras 6Sanmoreno
 
PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS-
PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS- PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS-
PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS- belen salinas
 
Blogging Video and Linkedin
Blogging Video and LinkedinBlogging Video and Linkedin
Blogging Video and LinkedinShane Gibson
 
The Truth About Cookie Overwriting
The Truth About Cookie OverwritingThe Truth About Cookie Overwriting
The Truth About Cookie Overwritingowenhewitson
 
Phiếu đánh giá tín nhiệm
Phiếu đánh giá tín nhiệmPhiếu đánh giá tín nhiệm
Phiếu đánh giá tín nhiệmVu Nguyen
 
Discouraged - Sao Phai Nan Long
Discouraged - Sao Phai Nan LongDiscouraged - Sao Phai Nan Long
Discouraged - Sao Phai Nan LongPhuc Nguyen Thanh
 

Andere mochten auch (20)

Las mejores imagenes d internet
Las mejores imagenes d internetLas mejores imagenes d internet
Las mejores imagenes d internet
 
Collages by Oana Catalina Gavriliu
Collages by Oana Catalina GavriliuCollages by Oana Catalina Gavriliu
Collages by Oana Catalina Gavriliu
 
Les Metamorphose1
Les Metamorphose1Les Metamorphose1
Les Metamorphose1
 
Huong dan MS.Project
Huong dan MS.ProjectHuong dan MS.Project
Huong dan MS.Project
 
Cars and pollution. ruben garcia
Cars and pollution. ruben garciaCars and pollution. ruben garcia
Cars and pollution. ruben garcia
 
XWiki SAS
XWiki SASXWiki SAS
XWiki SAS
 
Sonia Sorci_Le Mat
Sonia Sorci_Le MatSonia Sorci_Le Mat
Sonia Sorci_Le Mat
 
MATEMATIK TAHUN 4..KERTAS 2
MATEMATIK TAHUN 4..KERTAS 2MATEMATIK TAHUN 4..KERTAS 2
MATEMATIK TAHUN 4..KERTAS 2
 
Viborg
ViborgViborg
Viborg
 
Modele Avec Des Images Fortes (Our Copil Projet Id Zone)
Modele Avec Des Images Fortes (Our Copil Projet Id Zone)Modele Avec Des Images Fortes (Our Copil Projet Id Zone)
Modele Avec Des Images Fortes (Our Copil Projet Id Zone)
 
Thu2
Thu2Thu2
Thu2
 
When our superheroes went in action with groupchat to save the city.
When our superheroes went in action with groupchat to save the city.When our superheroes went in action with groupchat to save the city.
When our superheroes went in action with groupchat to save the city.
 
Grant proposal checklist handout
Grant proposal checklist handoutGrant proposal checklist handout
Grant proposal checklist handout
 
Sevilla luces y sombras 6
Sevilla luces y sombras 6Sevilla luces y sombras 6
Sevilla luces y sombras 6
 
PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS-
PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS- PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS-
PLAZA NARCISO LAPRIDA - ANTES Y DESPUÉS-
 
Blogging Video and Linkedin
Blogging Video and LinkedinBlogging Video and Linkedin
Blogging Video and Linkedin
 
The Truth About Cookie Overwriting
The Truth About Cookie OverwritingThe Truth About Cookie Overwriting
The Truth About Cookie Overwriting
 
Phiếu đánh giá tín nhiệm
Phiếu đánh giá tín nhiệmPhiếu đánh giá tín nhiệm
Phiếu đánh giá tín nhiệm
 
Discouraged - Sao Phai Nan Long
Discouraged - Sao Phai Nan LongDiscouraged - Sao Phai Nan Long
Discouraged - Sao Phai Nan Long
 
Citrus leaf
Citrus leafCitrus leaf
Citrus leaf
 

Ähnlich wie Py Die R E A D M E

python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfinfo706022
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009Jordan Baker
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docxBlake0FxCampbelld
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are availableNitesh Dubey
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & listsMarc Gouw
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxVigneshChaturvedi1
 
CS 151 Classes lecture 2
CS 151 Classes lecture 2CS 151 Classes lecture 2
CS 151 Classes lecture 2Rudy Martinez
 
Please help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdfPlease help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdfclimatecontrolsv
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael Pirnat
 
Xi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programsXi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programsProf. Dr. K. Adisesha
 
The Final Programming Project
The Final Programming ProjectThe Final Programming Project
The Final Programming ProjectSage Jacobs
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python Meetup
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 

Ähnlich wie Py Die R E A D M E (20)

python codes
python codespython codes
python codes
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
 
P2 2017 python_strings
P2 2017 python_stringsP2 2017 python_strings
P2 2017 python_strings
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docximport os import matplotlib-pyplot as plt import pandas as pd import r.docx
import os import matplotlib-pyplot as plt import pandas as pd import r.docx
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are available
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
 
Assignment6
Assignment6Assignment6
Assignment6
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptx
 
CS 151 Classes lecture 2
CS 151 Classes lecture 2CS 151 Classes lecture 2
CS 151 Classes lecture 2
 
Please help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdfPlease help this code is supposed to evaluate current node state and i.pdf
Please help this code is supposed to evaluate current node state and i.pdf
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Xi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programsXi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programs
 
The Final Programming Project
The Final Programming ProjectThe Final Programming Project
The Final Programming Project
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 

Mehr von cfministries

Elemental Christianity
Elemental  ChristianityElemental  Christianity
Elemental Christianitycfministries
 
Example Stream Setup
Example  Stream  SetupExample  Stream  Setup
Example Stream Setupcfministries
 
Peering Through The Mercy Seat
Peering Through The Mercy SeatPeering Through The Mercy Seat
Peering Through The Mercy Seatcfministries
 
Apostolic Private Eye
Apostolic  Private  EyeApostolic  Private  Eye
Apostolic Private Eyecfministries
 
Do You Make Jesus Sick
Do You Make  Jesus SickDo You Make  Jesus Sick
Do You Make Jesus Sickcfministries
 
Why Wait Get It Now
Why Wait    Get It NowWhy Wait    Get It Now
Why Wait Get It Nowcfministries
 
The Mind Of God ( Part 5)
The  Mind Of  God ( Part 5)The  Mind Of  God ( Part 5)
The Mind Of God ( Part 5)cfministries
 
The Mind Of God ( Part 4)
The  Mind Of  God ( Part 4)The  Mind Of  God ( Part 4)
The Mind Of God ( Part 4)cfministries
 
The Mind Of God ( Part 3)
The  Mind Of  God ( Part 3)The  Mind Of  God ( Part 3)
The Mind Of God ( Part 3)cfministries
 
The Mind Of God ( Part 2)
The  Mind Of  God ( Part 2)The  Mind Of  God ( Part 2)
The Mind Of God ( Part 2)cfministries
 
The Mind Of God ( Part 1)
The  Mind Of  God ( Part 1)The  Mind Of  God ( Part 1)
The Mind Of God ( Part 1)cfministries
 

Mehr von cfministries (17)

Grade Statistics
Grade StatisticsGrade Statistics
Grade Statistics
 
R P G Generator
R P G  GeneratorR P G  Generator
R P G Generator
 
 
Dealing W Spam
Dealing W SpamDealing W Spam
Dealing W Spam
 
Python Menu
Python MenuPython Menu
Python Menu
 
Elemental Christianity
Elemental  ChristianityElemental  Christianity
Elemental Christianity
 
Example Stream Setup
Example  Stream  SetupExample  Stream  Setup
Example Stream Setup
 
Peering Through The Mercy Seat
Peering Through The Mercy SeatPeering Through The Mercy Seat
Peering Through The Mercy Seat
 
Apostolic Private Eye
Apostolic  Private  EyeApostolic  Private  Eye
Apostolic Private Eye
 
Do You Make Jesus Sick
Do You Make  Jesus SickDo You Make  Jesus Sick
Do You Make Jesus Sick
 
Why Wait Get It Now
Why Wait    Get It NowWhy Wait    Get It Now
Why Wait Get It Now
 
The Mind Of God ( Part 5)
The  Mind Of  God ( Part 5)The  Mind Of  God ( Part 5)
The Mind Of God ( Part 5)
 
The Mind Of God ( Part 4)
The  Mind Of  God ( Part 4)The  Mind Of  God ( Part 4)
The Mind Of God ( Part 4)
 
5 Questions
5  Questions5  Questions
5 Questions
 
The Mind Of God ( Part 3)
The  Mind Of  God ( Part 3)The  Mind Of  God ( Part 3)
The Mind Of God ( Part 3)
 
The Mind Of God ( Part 2)
The  Mind Of  God ( Part 2)The  Mind Of  God ( Part 2)
The Mind Of God ( Part 2)
 
The Mind Of God ( Part 1)
The  Mind Of  God ( Part 1)The  Mind Of  God ( Part 1)
The Mind Of God ( Part 1)
 

Py Die R E A D M E

  • 1. pyDie I created pyDie as a re-usable die class program for games or for any program that need a random probabilities based upon dice or dice like entities. In order to use pyDie you must import the class just like any Python library. It contains two classes (die and cup). The die class can be initialized simply by passing a single parameter defining the number of sides (myDie = pyDie.die(6)) The library will then proceed to create a default die using the number of sides provided with values starting at 1 and incrementing by 1's till all sides are filled. You may also pass a second parameter for the low value and create a specialized die based upon the sides and the low value you assign (such as myDie = pyDie.die(6, 4) creates a die with values from 4 through 9). A third parameter can be use to set the high value but beware if you specify a low and high value that does not have a large enough range for the number of sides you specify pyDie will create the die with the right number of sides and try to make an intelligent decision about the range. Also if you mistakenly make the low value greater than the high value, pyDie will again attempt to make an intelligent decision regarding the layout of the die. The last possible parameter for initializing your die is the incrementation value. This allows you to create dice that increment greater than one number at a time. An example of this would be (myDie = pyDie.die(8, 1, 16, 2) results in a die with possible values of 1, 3, 5, 7, 9, 11, 13, 15). Once you have initialized your die you can call the roll method which will randomly choose a value from your list of possibilities. You can accomplish this by using myDie.roll(), you can then access this result using the newly created attribute called value (print myDie.value). The second class in pyDie is the cup class which allows you to store multiple dice and even roll them all at one time. You can create your cup simply by using myCup = pyDie.cup(). You would then add your die to the cup using myCup.add(myDie). You can then use the throw method to throw all dice in the cup (myCup.throw()). You would then access each die's value using the attribute for each die in the cup. The cup class also has an empty method which clears all dice from the cup, and a remove method which can be used to remove a single die from the cup simply by using myCup.remove(myDie). The following is an example of die and cup creation: import pyDie myDie = [] cup = pyDie.cup() # Create 4 standard die for i in range (1, 5): myDie.append(pyDie.die(6)) # Create one eight sided that starts with 10 # and increments by 5's myDie.append(pyDie.die(8, 10, 50, 5)) # Create one final die that is 10 sided # and begins with 0 and decrements by 2's myDie.append(pyDie.die(10, -20, 0, -2)) for die in myDie: cup.add(die) cup.throw() total=0
  • 2. print "Die paramaters: (sides, low, high, [range])" for die in cup.dice: total = total + die.value print "(%i, %i, %i, %s)"%(die.sides, die.low, die.high, die.possible) print "Result of throw for this die: %i"%die.value print "--------------------------------------------" print "Total of all dice: %i"%total The first four die are standard followed by two non-standard configurations. In this example we create five standard dice: import pyDie myDie = [] cup = pyDie.cup() # Create 5 standard die for i in range (1, 6): myDie.append(pyDie.die(6)) for die in myDie: cup.add(die) cup.throw() for die in cup.dice: print die.value
  • 3. Now we will look at some of the intelligent choices that pyDie makes when odd parameters are passed to it. This test script was used to test pyDie, and although not pretty, it does demonstrate the power and flexibility of this library. import pyDie print "A cup for the dice" cup = pyDie.cup() print "A standard die..." die1 = pyDie.die(6) print "Die sides=%i, low=%i, high=%i, range=%s"%(die1.sides, die1.low, die1.high, die1.possible) die1.roll() print "Result of roll %i"%die1.value print "Add die to cup" cup.add(die1) print "--------------------------------------n" print "A non-standard 8 sided die" die2 = pyDie.die(8) print "Die sides=%i, low=%i, high=%i, range=%s"%(die2.sides, die2.low, die2.high, die2.possible) die2.roll() print "Result of roll %i"%die2.value print "Add die to cup" cup.add(die2) print "--------------------------------------n" print "An 8 sided die with low > high" die3 = pyDie.die(8, 4, -3) print "Die sides=%i, low=%i, high=%i, range=%s"%(die3.sides, die3.low, die3.high, die3.possible)
  • 4. die3.roll() print "Result of roll %i"%die3.value print "Add die to cup" cup.add(die3) print "--------------------------------------n" print "Parameters 6, 2, 8, 1" die4 = pyDie.die(6, 2, 8) print "Die sides=%i, low=%i, high=%i, range=%s"%(die4.sides, die4.low, die4.high, die4.possible) die4.roll() print "Result of roll %i"%die4.value print "Add die to cup" cup.add(die4) print "--------------------------------------n" print "An eight sided die starting at 10..." die5 = pyDie.die(8, 10) print "Die sides=%i, low=%i, high=%i, range=%s"%(die5.sides, die5.low, die5.high, die5.possible) die5.roll() print "Result of roll %i"%die5.value print "Add die to cup" cup.add(die5) print "--------------------------------------n" print "A six sided die (6, 0, -5, -1)" die6 = pyDie.die(6, 0, -5, -1) print "Die sides=%i, low=%i, high=%i, range=%s"%(die6.sides, die6.low, die6.high, die6.possible) die6.roll() print "Result of roll %i"%die6.value print "Add die to cup" cup.add(die6) print "--------------------------------------n" print "Roll all die in cup at once" cup.throw() for die in cup.dice: print die.value Note: Each highlighted line above illustrates different features of die creation
  • 5. The first thing to note is that die1 = pyDie.die(6) is a simple default die creation. This is then followed by die2 = pyDie.die(8) which is a non-standard eight sided die. The interesting part occurs with the third die die3 = pyDie.die(8, 4, -3) which is created as an eight sided die but the low value is actually higher than the high value which additionally is a negative number (Note: pyDie ignores the high value and creates the die beginning with the low value and working up from there, and then sets the high value to the appropriate value).
  • 6. The next die created die4 = pyDie.die(6, 2, 8) is a six sided die starting at two and going to eight (since the high value is outside of the range it is changed to the appropriate value). Following that is an eight sided die beginning with 10 die5 = pyDie.die(8, 10), this is then followed by a six sided die die6 = pyDie.die(6, 0, -5, -1) that starts at zero and decrements by one to -5. This is then followed by the throw of the cup. Roll all die in cup at once 3 8 7 4 16 -1 As you can see pyDie has been designed with simplicity in mind while still incorporating some intelligence in order to avoid potential errors.
  • 7. Source Code The following is the pyDie source code. # Program: pyDie.py # Author: James D. Coen # Date: 2009.12.11 # Purpose: This program is used to create a generic # die roll class so that it can be imported # and re-used in various ways from random import randint, seed from time import time class die(object): """ A single die. """ def __init__(self, sides, low=1, high=6, incr=1): """ The first argument is the number of sides the second is the lowest # possible (default 1) the third is the highest # possible (default 6) the fourth is the number to increment by (default 1) """ self.sides = sides possible = [] if incr == 0: incr = 1 if incr < 0: if low < high: for i in range(high, low-1, incr): possible.append(i) elif low > high: for i in range(low, high-1, incr): possible.append(i) else: for i in range(0, sides+1*-1, incr): possible.append(i) possible.sort() while len(possible) > self.sides: possible.remove(possible[0]) low = possible[0] while len(possible) < self.sides: possible.append(possible[0] + incr) possible.sort() low = possible[0] else: if low < high: for i in range(low, high+1, incr): possible.append(i) else: for i in range(low, low+sides+1, incr): possible.append(i) possible.sort() while len(possible) > self.sides: possible.remove(possible[len(possible)-1]) high = possible[len(possible)-1]
  • 8. while len(possible) < self.sides: possible.append(possible[len(possible)-1] + incr) high = possible[len(possible)-1] if low < high: self.high = high self.low = low elif low > high: self.low = high self.high = low else: self.low = possible[0] self.high = possible[len(possible)-1] self.possible = possible def roll(self): """ Role the die """ seed(time() * time() * self.sides) self.value = randint(self.low, self.high) if self.value not in self.possible: while self.value not in self.possible: self.value = randint(self.low, self.high) class cup(object): """ A cup full of dice. """ def __init__(self): self.dice = [] def empty(self): self.dice = [] def add(self, die): self.dice.append(die) def remove(self, die): self.dice.remove(die) def throw(self): for die in self.dice: die.roll() It must be noted that pyDie works extremely well on Linux but there seems to be a problem with the randomness on the Window's platform that I have not take time to analyze as I do not use this platform regularly.