Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Python] Roll the dice!
06-22-2010, 11:35 PM
Post: #1
[Python] Roll the dice!
A nice way to make a program which will roll the dice for us and give as a value between 1 and 6 is to use Lambda Functions. We'll need some help from random module.

Code:
>>> from random import randint
>>> dice = lambda :randint(1,6)
>>> dice()
5
>>> dice()
2

[Image: 45669_pythonlogo.png][Image: 45668_javalogo.png]
Find all posts by this user
Quote this message in a reply
06-23-2010, 04:10 AM
Post: #2
RE: [Python] Roll the dice!
Heh I love Python's libraries.

"Character is determined more by the lack of certain experiences than by those one has had."
Friedrich Nietzsche
Visit this user's website Find all posts by this user
Quote this message in a reply
01-21-2011, 07:54 PM (This post was last modified: 01-21-2011 07:56 PM by codecaine.)
Post: #3
RE: [Python] Roll the dice!
or if you want to roll two dice and return a tuple

from random import randint as roll;

dicepair = lambda : (roll(1,6), roll(1,6));
print(dicepair());
Visit this user's website Find all posts by this user
Quote this message in a reply
01-22-2011, 03:11 AM (This post was last modified: 01-22-2011 03:28 AM by Alphablend.)
Post: #4
RE: [Python] Roll the dice!
I was planning to write code for 5 dices, for the game Yahtzee.
I don't know the difference but in my country this game is called Yamb.

In this game there are certain rules, which I don't want to explain now.
When player rolls the dices, he has 2 more attempts to roll, and he pick which dices he wants to roll again and which ones he wants to leave the way they are.

When inspiration comes to me I'll post the code here.

Output should be like this:
Code:
1st throw:
d1=1
d2=1
d3=6
d4=4
d5=2
Input the number of dice you want to roll again (input 'r' to roll): 3
Input the number of dice you want to roll again (input 'r' to roll): 4
Input the number of dice you want to roll again (input 'r' to roll): 5
Input the number of dice you want to roll again (input 'r' to roll): r
2nd throw:
d1=1
d2=1
d3=6 #changed
d4=6 #changed
d5=6 #changed
Input the number of dice you want to roll again (input 'r' to roll): ...
3rd throw:
...
Again? (y/n): ...

Or maybe a better way:
Code:
1st throw:
d1=1
d2=1
d3=6
d4=4
d5=2
Input the numbers of dices you want to roll again (split by space): 3 4 5
2nd throw:
d1=1
d2=1
d3=6 #changed
d4=6 #changed
d5=6 #changed
Input the numbers of dices you want to roll again (split by space): 1 2
3rd throw:
d1=4 #changed
d2=4 #changed
d3=6
d4=6
d5=6
Again? (y/n): ...
Where 'y' should throw them all again and 'n' should terminate the program.

[Image: 45669_pythonlogo.png][Image: 45668_javalogo.png]
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: