本文整理汇总了Python中dice.Dice.roll方法的典型用法代码示例。如果您正苦于以下问题:Python Dice.roll方法的具体用法?Python Dice.roll怎么用?Python Dice.roll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dice.Dice
的用法示例。
在下文中一共展示了Dice.roll方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_double_roll
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def test_double_roll(sides, rolls):
""" Check that the probability for the sum of two n-sided dice matches
the expected distribution.
"""
# Store the expected probabilities for the sum of two dice.
exp = {}
for x in range(2, 2*sides + 1):
exp[x] = prob_double_roll(x, sides)
# Create a dictionary to hold the tally for each outcome.
tally = {}
for key in exp:
tally[key] = 0
# Initialise the dice.
dice = Dice(sides)
# Roll two dice 'rolls' times.
for i in range(0, rolls):
# Sum the value of the two dice rolls.
roll_sum = dice.roll() + dice.roll()
# Increment the tally for the outcome.
tally[roll_sum] += 1
# Compute the probabilities and check with expected values.
for key in tally:
average = tally[key] / rolls
assert average == pytest.approx(exp[key], rel=1e-2)
示例2: __init__
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
class PokerApp:
def __init__(self, interface):
self.dice = Dice()
self.money = 100
self.interface = interface
def run(self):
while self.money >= 10 and self.interface.wantToPlay():
self.playRound()
self.interface.close()
def playRound(self):
self.money = self.money - 10
self.interface.setMoney(self.money)
self.doRolls()
result, score = self.dice.score()
self.interface.showResult(result, score)
self.money = self.money + score
self.interface.setMoney(self.money)
def doRolls(self):
self.dice.rollAll()
roll = 1
self.interface.setDice(self.dice.values())
toRoll = self.interface.chooseDice()
while roll < 3 and toRoll != []:
self.dice.roll(toRoll)
roll = roll + 1
self.interface.setDice(self.dice.values())
if roll < 3:
toRoll = self.interface.chooseDice()
示例3: __init__
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
class PokerApp:
def __init__(self, interface):
self.dice = Dice()
self.money = 100
self.interface = interface
def processScore(self, score):
h = HighScores()
if h.isElgible(score):
nameentry = GraphWin("Name Entry", 200, 100)
entry = Entry(Point(50, 50), 10)
entry.draw(nameentry)
okbutton = Button(nameentry, Point(150, 50), 90, 50, "Save Name")
okbutton.activate()
while 1:
m = nameentry.getMouse()
if okbutton.clicked(m):
h.addToList(score, entry.getText())
nameentry.close()
return
def run(self):
while self.money >= 10:
result = self.interface.wantToPlay()
if result == "Roll Dice":
self.playRound()
elif result == "Help":
h = HelpScreen()
h.DoEvents()
elif result == "Quit":
self.processScore(self.money)
break
self.interface.close()
def playRound(self):
self.money = self.money - 10
self.interface.setMoney(self.money)
self.doRolls()
result, score = self.dice.score()
self.interface.showResult(result, score)
self.money = self.money + score
self.interface.setMoney(self.money)
def doRolls(self):
self.dice.rollAll()
roll = 1
self.interface.setDice(self.dice.values())
toRoll = self.interface.chooseDice()
while roll < 3 and toRoll != []:
self.dice.roll(toRoll)
roll = roll + 1
self.interface.setDice(self.dice.values())
if roll < 3:
toRoll = self.interface.chooseDice()
示例4: start
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def start(self):
sleep(1)
print("Game is about to start!")
sleep(2)
while len(self.winners) < 1:
sleep(1)
print("---------- ROUND " + str(self.round) + " ----------")
for player in self.players:
results = []
for i in range(player.dice):
result = Dice.roll()
results.append(result)
if result == 6:
player.dice -= 1
print(player.name + " rolled the numbers " + str(results))
print(player.name + " has " + str(player.dice) + " dice remaining.")
if player.dice < 1:
self.winners.append(player)
self.round +=1
print("--------------------------")
print("Game Over!")
sleep(1)
for player in self.winners:
print(player.name + " has " + str(player.dice) + " remaining dice and won the game!")
示例5: Player
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
class Player(object):
def __init__(self, game, point_config='STD_CONFIG', uid=1, max_turns=3):
self.game = game
self.id = uid
self.turn = 0
self.points = Points(config=point_config)
self.dice = Dice()
self.max_turns = max_turns
def save_dice(self, values):
self.dice.save(values)
def entry_points(self, field, column, values, preview=False):
score = self.points.entry(field, column, values, self.game, preview=preview)
if not preview:
self.game.next_player()
self.turn = 0
if all([all([i[1] for i in column.points.values()]) for column in self.points.columns]):
raise PlayerFinishedException()
return score
def roll_dice(self):
if self.turn >= self.max_turns:
raise NoTurnsLeftException()
self.dice.roll()
self.turn += 1
def delete(self):
if self.game.active_player == self:
self.game.next_player()
del self.game.players[self.game.players.index(self)]
@classmethod
def generate_players(cls, game, count, point_config):
return [cls(game, point_config=point_config, uid=i) for i in range(1, count+1)]
示例6: parse_roll_command
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def parse_roll_command(text):
# print 'Parsing roll command "{0}" ... '.format(text)
regex = re.compile(ur'(?P<roll_command>^[!]\w+)\s*'
ur'(?P<number_of_dice>\d+)[d](?P<dice_sides>\d+)\s*'
ur'(?P<modifier>(?P<modifier_operator>[-+*/])\s*(?P<modifier_value>\d+))*', re.IGNORECASE)
match = re.search(regex, text)
if match:
number_of_dice = match.group('number_of_dice')
dice_sides = match.group('dice_sides')
modifier_operator = match.group('modifier_operator')
modifier_value = match.group('modifier_value')
# print 'Match: {0}'.format(match.group())
return Dice.roll(number_of_dice, dice_sides, modifier_operator, modifier_value)
else:
print 'Invalid roll command syntax'
return None
示例7: gen_siblings
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def gen_siblings(self):
d = Dice()
roll = d.roll(1, 10)
self.relations = []
self.siblings = []
self.gender_table = []
self.gender_table.append('Male')
self.gender_table.append('Female')
self.read_file('lifepath/family/family_siblings.txt', self.relations)
little_num = 1
big_num= 1
if roll>0 and roll<8:
for i in range(0, roll):
gender = choice(self.gender_table)
first=self.contr.get_r_name('first', gender)
second=self.contr.get_r_name('second', gender)
last=self.contr.datasets['last name']
nick = self.contr.get_r_name('nick', gender)
name = first + ' ' + second + ' ' + nick + ' ' + last.get()
age=int(self.contr.datasets['age'].get())
relative_age = d.Roll(1,2)
if relative_age ==1:
age= age-little_num
little_num = little_num +1
else:
age= age + big_num
big_num = big_num +1
relation = choice(self.relations)
member = family_member(name, relation, gender, age)
self.siblings.append(member)
self.sibling_var.set('you have ' +str(roll) + ' siblings')
self.contr.datasets['siblings'] = self.siblings
else:
self.sibling_var.set('you are the only child')
member = family_member('you are the only child','none','none',0)
self.siblings.append(member)
self.contr.datasets['siblings'] = self.siblings
示例8: Dice
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
import prompt
import predicate
win_count = 0 #Win/Lose/Dice Statistics
lose_count = 0
dice = Dice([6,6])
game_timer = Stopwatch()
games_to_play = prompt.for_int('Enter # of games to play', is_legal=predicate.is_positive, error_message='an int, but not > 0')
game_timer.start()
dice.standard_rolls_for_debugging()
for game in irange(1, games_to_play): #Each iteration plays one game
first_roll = dice.roll().pip_sum() #Roll the dice and record their pip sum
#Based on firstRoll, decide how to continue:
# immediate win/loss or trying to make point
if first_roll == 7 or first_roll == 11:
win_count += 1 #Win on the first roll with 7 or 11
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
lose_count += 1 #Lose on the first roll with 2, 3, or 12
else: #Try to make the point as the game continues
point = first_roll #point will never store 7, 11, 2, 3, or 12
while(True): #Roll until roll point (win) or 7 (lose)
roll = dice.roll().pip_sum()
示例9: roll
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def roll(self):
dice = Dice(self.defaultMinValue, self.defaultMaxValue)
dice.roll()
示例10: __init__
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
# (C) 2014
#
# GPL v3 License
#
from dice import Dice
class Entry:
def __init__(self, attrs):
self.ac = attrs.get('AC', ('', 0))
def AC(self):
return self.ac
entries = [
Entry({'AC' : ('deflection bonus', 1)}),
Entry({'AC' : ('deflection bonus', 2)}),
]
if __name__ == '__main__':
e = entries[0]
print e.AC()
for i in range(10):
d = Dice('3d6+8')
print d, d.roll()
d = Dice('d2-5')
print d, d.roll()
d = Dice('d%')
print d, d.roll()
示例11: Map
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
class Map(object):
def __init__(self, width=DEFAULT_MAP_CELLS_X, height=DEFAULT_MAP_CELLS_Y):
self.map = []
self.viewport = []
self.width, self.height = width, height
self.playableArea = Rect(Position(1, 1), width - 2, height - 2)
self.batch = pyglet.graphics.Batch()
self.mapGroup = pyglet.graphics.OrderedGroup(0)
self.monsterGroup = pyglet.graphics.OrderedGroup(1)
self.playerGroup = pyglet.graphics.OrderedGroup(2)
self.player = Player(map=self, pos=Position(), batch=self.batch, group=self.playerGroup)
self.dice = Dice()
self.initViewport()
self.initGameMap()
self.initBSP()
self.drawTunnels()
def initGameMap(self):
for x in range(self.width):
lst = []
for y in range(self.height):
lst.append(MapCell(Position(x, y), self.batch, self.mapGroup))
self.map.append(lst)
def initBSP(self):
bsp = BSP(self.playableArea)
self.rooms = []
for r in bsp.rects:
if self.dice.roll("1d10") > 3:
roomrect = self.makeRandRoom(r)
self.rooms.append(roomrect)
def drawTunnels(self):
lastroom = None
for i in self.rooms:
if not lastroom is None:
pos1 = lastroom.getPoint()
pos2 = i.getPoint()
self.randTunnel(pos1, pos2)
lastroom = i
else:
pos = i.getPoint()
self.player.moveOrAttack(self, pos)
self.map[pos.x + 1][pos.y + 1].objects.append(
Kobold(Position(pos.x + 1, pos.y + 1), self, self.batch, self.monsterGroup)
)
lastroom = i
def getCellAtPos(self, pos):
return self.map[pos.x][pos.y]
def debugPrint(self):
import sys
for x in range(len(self.map)):
for y in range(len(self.map[x])):
if self.map[x][y].type == DUNGEON_WALL:
sys.stdout.write("#")
elif self.map[x][y].visible == True:
sys.stdout.write(" ")
elif self.map[x][y].type == DUNGEON_FLOOR:
sys.stdout.write("~")
print "\n",
def initViewport(self):
for i in range(VIEWPORT_W):
self.viewport.append([0] * VIEWPORT_H)
for x in range(len(self.viewport)):
for y in range(len(self.viewport[x])):
self.viewport[x][y] = Sprite(
sheet["dungeon"][81], x=x * SPRITE_SIZE, y=y * SPRITE_SIZE, batch=self.batch, group=self.mapGroup
)
def getViewportPos(self, width, height):
startX = self.player.pos.x - width / 2
startY = self.player.pos.y - height / 2
endX = startX + width
endY = startY + height
mapLenX = len(self.map)
mapLenY = len(self.map[0])
if endX > mapLenX - 1:
endX = mapLenX - 1
if endY > mapLenY:
endY = mapLenY - 1
if startX < 0:
startX = 0
if startY < 0:
startY = 0
if endX - startX < VIEWPORT_W - 1:
if startX < VIEWPORT_W:
startX, endX = 0, VIEWPORT_W
else:
startX, endX = mapLenX - VIEWPORT_W, mapLenX
#.........这里部分代码省略.........
示例12: get_rent
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def get_rent(self):
dice = Dice()
if len(self.owner.utilities_owned) == 1:
return dice.roll() * 4
return dice.roll() * 10
示例13: Stats
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
class Stats(object):
def __init__(self, parent, hpRoll=10,
Str=12, Dex=12,
Con=12, Int=12,
Wis=12, Cha=12):
self.parent = parent
self.mbox = msgBox()
self.dice = Dice()
self.Str = Str
self.Dex = Dex
self.Con = Con
self.Int = Int
self.Wis = Wis
self.Cha = Cha
self.baseAttack = 2
self.baseDefense = 2
self.attackRoll
self.hp = hpRoll + bonus[str(Con)]
self.maxHP = self.hp
self.mp = baseMP + bonus[str(Int)]
self.maxMP = self.mp
self.xp = 0
self.xpForNextLevel = 1000
def dmg(self):
damage = self.dice.roll('1d6+' + str(bonus[str(self.Str)]))
# damage = randint(1,6 + bonus[str(self.Str)])
if damage < 1:
damage = 1
return damage
def attackOther(self, other):
if other.dead:
return
if isinstance(self.parent, player.Player):
self.parent.map.objectUpdateRequired = 1
if self.attackRoll() >= other.stats.defenseRoll():
self.doHit(other)
else:
pass
def attackRoll(self):
return self.baseAttack + \
bonus[str((self.Str + self.Dex) / 2)] + self.dice.roll('1d20')
def defenseRoll(self):
return self.baseDefense + bonus[str(self.Dex)] + self.dice.roll('1d20')
def doHit(self, other):
damage = self.dmg()
other.stats.gotHit(self.parent, damage)
if isinstance(self.parent, player.Player):
self.mbox.addMsg(
'You hit %s for %i damage!' % (other.name, damage))
self.mbox.addMsg(
'%s hp: %i/%i' % (other.name,
other.stats.hp,
other.stats.maxHP))
def gotHit(self, other, damage):
self.hp -= damage
if self.hp < 0:
self.hp = 0
if isinstance(self.parent, player.Player):
self.mbox.addMsg(
'You got hit for %i damage by %s' % (damage,other.name))
self.mbox.addMsg(
'Current hp: %i/%i' % (self.hp,self.maxHP))
if self.hp == 0:
self.gotKilled(other)
def gotKilled(self, other):
self.parent.dead = True
self.parent.blocked = False
self.parent.image = getCorpseSprite()
if isinstance(self.parent, player.Player):
self.mbox.addMsg('You got killed by a %s!' % other.name)
else:
other.stats.xp += 150
other.statuswindow.updateStats()
示例14: test
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
def test(self):
rolls = []
for i in range(100):
rolls.append(Dice.roll())
self.assertFalse(0 in rolls and 7 in rolls)
示例15: TestDiceClass
# 需要导入模块: from dice import Dice [as 别名]
# 或者: from dice.Dice import roll [as 别名]
class TestDiceClass(unittest.TestCase):
def setUp(self):
self.dice = Dice()
self.roll_list = self.dice.roll_list("100d100")
def tearDown(self):
pass
def testLen_roll_list(self):
self.assertEqual(100, len(self.roll_list))
def testNone_roll_list(self):
self.assertEqual(None, self.dice.roll_list("aaaa"))
def testNumber_roll_list(self):
for member in self.roll_list:
assert(1 <= member and member <= 100)
def testSimple_roll(self):
result = self.dice.roll("1d100")
assert(1 <= result and result <= 100)
def testSimple2_roll(self):
self.assertEqual(150, self.dice.roll("2d100", [100,50]))
def testNone_roll(self):
self.assertEqual(None, self.dice.roll("aaaa"))
def testPlus_roll(self):
result = self.dice.roll("1d100+1")
assert(2 <= result and result <= 101)
def testPlus2_roll(self):
self.assertEqual(151, self.dice.roll("2d100+1", [100,50]))
def testMinus_roll(self):
result = self.dice.roll("1d100-1")
assert(0 <= result and result <= 99)
def testMinus2_roll(self):
self.assertEqual(149, self.dice.roll("2d100-1", [100,50]))
def testMulti_roll(self):
result = self.dice.roll("1d100*2")
assert(2 <= result and result <= 200)
assert(result % 2 == 0)
result = self.dice.roll("1d100x2")
assert(2 <= result and result <= 200)
assert(result % 2 == 0)
def testMulti2_roll(self):
self.assertEqual(300, self.dice.roll("2d100*2", [100,50]))
self.assertEqual(300, self.dice.roll("2d100x2", [100,50]))
def testDiv_roll(self):
result = self.dice.roll("1d100/2")
assert(1 <= result and result <= 50)
def testDiv2_roll(self):
self.assertEqual(75, self.dice.roll("2d100/2", [100,50]))
def testDiv3_roll(self):
self.assertEqual(1, self.dice.roll("1d4/2", [1]))
def testBest_roll(self):
self.assertEqual(100, self.dice.roll("3d100b1", [25, 100,50]))
self.assertEqual(150, self.dice.roll("3d100b2", [25, 100,50]))