class Generator(object): def __init__(self): self._hand = Dice() self._hand.addDie(sides = 6, count = 4) # init to 4d6 def __del__(self): pass def _rollBaseNumbers(self): return self._hand.roll(count = 6) def _generateScoreList(self): # roll 4d6 x 6 rolls = self._rollBaseNumbers() # drop lowest from each set and sum remaining rolls into output output = [] for rollset in rolls: rollset.remove(min(rollset)) output.append(sum(rollset)) return sorted(output, reverse = True) def generateScoreLists(self, count = 1): output = [] for i in range(count): output.append(self._generateScoreList()) return sorted(output, reverse = True)
def __init__(self): self.dice = Dice() self.score = 0 self.saved_dice = [] self.thrown_dice = [] self.qualified = False self.results = 0
def render(self): #Render asteroids and stars for object in self.objects: object.render() #Render powerups if len(self.powerups) > 0: for powerup in self.powerups: powerup.fallmove() if powerup.rect.y > self.screen.get_height(): self.powerups.remove(powerup) powerups_plain = pygame.sprite.RenderPlain(self.powerups) powerups_plain.draw(self.screen) #Render enemies if len(self.enemies) > 0: for enemy in self.enemies: enemy.render() #Render enemy projectiles enemy_shoot_chance = Dice() dice_roll = enemy_shoot_chance.roll() self.enemy_shoot(dice_roll) if len(self.enemy_projectiles) > 0: for enemy_projectile in self.enemy_projectiles: enemy_projectile.render() if enemy_projectile.rect.y > self.screen.get_height(): self.enemy_projectiles.remove(enemy_projectile) #Render explosions if len(self.explosions) > 0: for explosion in self.explosions: explosion.render_cycle() #Destroy asteroids and ufos inside explosion if type(explosion.object) is BombProjectile: for object in self.objects: if object.projectile_collided(explosion): self.explosions.append( Explosion(object.size, object.rect.x, object.rect.y, self.screen, explosion.object)) object.reset() self.score_checker() for enemy in self.enemies: if enemy.projectile_collided(explosion): self.explosions.append( Explosion(object.size, object.rect.x, object.rect.y, self.screen, explosion.object)) self.enemies.remove(enemy) self.score_checker() if explosion.over: self.explosions.remove(explosion)
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.scene = QGraphicsScene(self) self.scene2 = QGraphicsScene(self) self.pixmap = QtGui.QPixmap() self.pixmap.load(DicePicture.Dice[1]) self.pixmap2 = QtGui.QPixmap() self.pixmap2.load(DicePicture.Dice[1]) item = QGraphicsPixmapItem(self.pixmap) item2 = QGraphicsPixmapItem(self.pixmap2) self.scene.addItem(item) self.scene2.addItem(item2) self.ui.graphicsView.setScene(self.scene) self.ui.graphicsView_2.setScene(self.scene2) self.ui.RollDice.clicked.connect(self.roller) self.Dice = Dice(2, 6) self.show()
def setUp(self): fair_dice = Dice() biased_dice = Dice([0.1, 0.2, 0.3, 0.1, 0.1, 0.2]) self.casino = Casino(from_fair_to_biased_probability=0.1, from_biased_to_fair_probability=0.2, fair_dice=fair_dice, biased_dice=biased_dice)
def rollHP(self): die = Dice(1, 4) HP = die.roll() + abilityModifier.table.get( self.abilities.get('Stamina'))[0] if HP < 1: HP = 1 return HP
def getOccupation(self): die = Dice(1, 100) roll = die.roll() with open('occupations.csv', 'r') as occupations: reader = csv.reader(occupations) for row in reader: if roll == int(row[0]): return row[1].title().strip()
def checkSlingDart(self): d6 = Dice(1, 6) if self.inventory[len(self.inventory) - 1] == 'Sling': roll = d6.roll() self.inventory.append(f'{roll} Sling Stones') if self.inventory[len(self.inventory) - 1] == 'Dart': roll = d6.roll() self.inventory.append(f'{roll} Darts')
def __init__(self, airtankSize=25, mapSize=16): self.airtank = Airtank(airtankSize) self.players = [] self.currentPlayer = 0 self.currentRound = 0 self.maxNofRounds = 3 self.ui = Ui() self.dices = [Dice(3), Dice(3)] self.map = Map(mapSize)
def __init__(self, name, game): self._name = name self._game = game # Create a set of five dice self._diceset = set() self._diceset.add(Dice()) self._diceset.add(Dice()) self._diceset.add(Dice()) self._diceset.add(Dice()) self._diceset.add(Dice())
def init_game(self): """ Initialize the game """ self.logger.info("Initializing Database") self.database = DatabaseHandler() self.questionHandler = QuestionHandler() self.dice = Dice(6) self.logger.info("Polishing Dice") self.logger.info("Starting Game - Welcome to trivial purfuit")
def test_next_move(monkeypatch, test_humanplayer): board = Board() dice = Dice() dice.set_dice(2, 1) monkeypatch.setattr('builtins.input', lambda x: '13 11') assert test_humanplayer.next_move(board, dice) == Move(0, 13, 11) monkeypatch.setattr('builtins.input', lambda x: '24 23') assert test_humanplayer.next_move(board, dice) == Move(0, 24, 23) monkeypatch.setattr('builtins.input', lambda x: '6 5') assert test_humanplayer.next_move(board, dice) == Move(0, 6, 5)
def __init__(self, wounds, defense, **kwargs): self._wounds = wounds self._wound_integrity_max = WOUND_INTEGRITY_MAX self._integrity_die = Dice(faces=self._wound_integrity_max) self.defense_buffer = defense # Would only be used for reloading, don't expose in the normal signature self._wounds_taken = kwargs.get('wounds_taken', 0) self._current_wound_integrity = kwargs.get('current_wound_integrity', WOUND_INTEGRITY_MAX) self._out_of_action = self._wounds_taken >= self._wounds
def SkillCheck( self, skill, ability, DC ): #I even made a method to allow auto implementation of a single skill check. It uses the d20 method. roll = Dice(1, 20, skill.mod + ability.mod) if (roll.Check(DC) == True): return True #It rings true if the character is successful. else: return False #Otherwise it is falseself.
def assign_attributes(self, verbose): """ Assigns attributes at generation, based on player choice :return: nothing """ if verbose: print( "\nAttributes represent the overall physical and mental qualities of an individual." " They define the raw potential an individual has regardless of actual skill." ) print( "To define these Attributes, the computer will roll 4D6, dropping the lowest roll, and you" " will choose which score to assign to 3 Attributes:\n \u2022 Strength(STR)" "\n \u2022 Dexterity(DEX)\n \u2022 Mind(MIND)") outs = Dice(4, 6, 0).calculate_rolls() outs.remove(min(outs)) self.STR = int(input(f"Assign STR {outs[0]}, {outs[1]} or {outs[2]}")) outs.remove(self.STR) self.DEX = int(input(f"Assign DEX {outs[0]} or {outs[1]}")) outs.remove(self.DEX) print(f"Assigning {outs[0]} to MIND") self.MIND = outs[0]
def checkPushCart(self): d6 = Dice(1, 6) if self.inventory[len(self.inventory) - 1] == 'Pushcart': cartContents = { 1: 'Tomaters', 2: 'A Whole lotta Nuffin', 3: 'Straw', 4: 'Yer Dead', 5: 'Dirt', 6: 'Rocks' } roll = d6.roll() self.inventory[len(self.inventory) - 1] = f'Pushcart full o\' {cartContents.get(roll)}'
def test_rolltree(): board = Board() board.board = [[ 9, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0 ]] player = ComputerPlayer(1) dice = Dice() dice.set_dice(1, 1) rulebook = RuleBook(board, player, dice) rolltree = RollTree([], Move(1, 8, 7), rulebook, 1, 4) test_dice = Dice() test_dice.set_dice(1, 0) assert rolltree.rulebook.dice == test_dice rolltree.activate() assert len(rolltree.children) == 1 assert rolltree.traverse_roll_tree(rolltree, []) == [[ Move(1, 8, 7), Move(1, 7, 6), Move(1, 6, 5), Move(1, 5, 4) ]] rulebook.board.board = [[ 9, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ], [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0 ]] rolltree = RollTree([], Move(1, 2, 1), rulebook, 1, 4) rolltree.activate() assert rolltree.traverse_roll_tree(rolltree, []) == [[Move(1, 2, 1), Move(1, 1, 0)]] rulebook.board.board = [[ 9, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ], [ 3, 7, 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]] rulebook.dice.set_dice(1, 6) assert rulebook.generate_legal_ply_list() == [ [Move(1, 1, 0), Move(1, 5, 0)], [Move(1, 5, 4), Move(1, 4, 0)], [Move(1, 4, 3), Move(1, 5, 0)], [Move(1, 3, 2), Move(1, 5, 0)], [Move(1, 2, 1), Move(1, 5, 0)] ]
def __init__(self, faces, players, board_size, snakes, ladders): self.snakes = {} self.ladders = {} self.board_size = board_size self.dice = Dice(faces) for src, dest in snakes: self.snakes[src] = dest for src, dest in ladders: self.ladders[src] = dest self.board = Board(self.board_size, self.snakes, self.ladders) self.players = [Player(name, self.board) for name in players]
def checkIfFarmer(self): d8 = Dice(1, 8) if self.occupation == 'Farmer': farmerType = { 1: 'Potato', 2: 'Wheat', 3: 'Turnip', 4: 'Corn', 5: 'Rice', 6: 'Parsnip', 7: 'Radish', 8: 'Rutabaga' } roll = d8.roll() self.occupation = f'{farmerType.get(roll)} Farmer'
def rollAbilities(self): abilities = { 'Strength': 0, 'Agility': 0, 'Stamina': 0, 'Personality': 0, 'Intelligence': 0, 'Luck': 0 } dice = Dice(3, 6) for ability in abilities: abilities[ability] = dice.roll() return abilities
def attack( self, toHit ): #ac, profBonus, abilityBonus, advantage, damDiceNum, damDiceSize, critMult #d20=d.Dice.rolls(1,20,e.Enemy.getProfBonus(self)+e.Enemy.getAbilityMod(self)) d20 = d.rolls(1, 20) self.profBonus = str(e.getProfBonus(self)) print("Proficiency Bonus: " + self.profBonus) self.abilityMod = str(e.getAbilityMod(self)) print("Ability Modifier: " + self.abilityMod) #print("Ability Modifier: {}".format(e.getAbilityMod(self))) print("D20: {}".format(d20)) total = 0 if d20 == 1: total = "critical miss!" elif d20 == 20: total = "critical hit!" else: total = d20 + e.getProfBonus(self) + e.getAbilityMod(self) if total < toHit: print("Miss!") else: print("Hit!") print("Total: {}".format(total))
def initiative(self): """ returns initiative value :return: initiative """ return Dice(1, 20).calculate() + self.DEX
def test_bearoff(): board = Board() board.board = [[0, 2, 2, 3, 2, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]] player = HumanPlayer(0) dice = Dice() return RuleBook(board, player, dice)
def saving_throw(self, attribute): """ Calculate a saving throw :return: the value of the saving throw """ return Dice(1, 20).calculate() + self.calculate_attribute_bonus(attribute) + (0.5 * self.level)
def run(self): """Run the program and call Dice()""" dice = Dice() # Set a Boolean to check whether it can be rolled based on the dice time. is_next = True start_time = time.time() while True: if is_next: if dice.go_dice(self.__sense, None) is not None: is_next = False start_time = time.time() # if current time minus start time is greater than 1, then allow to roll again. if time.time() - start_time > 1: is_next = True
class Game: def __init__(self, faces, players, board_size, snakes, ladders): self.snakes = {} self.ladders = {} self.board_size = board_size self.dice = Dice(faces) for src, dest in snakes: self.snakes[src] = dest for src, dest in ladders: self.ladders[src] = dest self.board = Board(self.board_size, self.snakes, self.ladders) self.players = [Player(name, self.board) for name in players] def play(self): while (1): for player in self.players: from_position = player.position dice_value = self.dice.roll() player.move(dice_value) to_position = player.position print(player.name, "rolled a", dice_value, "and moved from", from_position, "to", to_position) if player.position == self.board_size: return player.name + " wins the game"
def addDice(self): """Returns the set of dice after one is added. Player cannot have more than five dice.""" if len(self._diceset) < 5: self._diceset.add(Dice()) return self._diceset
def generate_dice(self): while True: try: print('How many dice shall you roll?') how_many_dice = int(input(' > ')) except ValueError: print('You must enter an integer') continue break while True: try: print('What is the lowest die value?') min_roll_dice = int(input(' > ')) except ValueError: print('You must enter an integer') continue break while True: try: print('What is the highest die value?') max_roll_dice = int(input(' > ')) except ValueError: print("You must enter an integer") continue if max_roll_dice < min_roll_dice: print('Max can\'t be lower than min..') continue break new_dice = Dice(how_many_dice, max_roll_dice, min_roll_dice) return new_dice
def workhorse(): from Dice import Dice d = Dice() roll = (d.rolls(1, 20)) if roll == 20: print(str(roll) + "\nCritical hit!") damage = d.rolls(w1.damage_dice[0] * 5, w1.damage_dice[1]) print(str(damage) + " point(s) of " + w1.type + " damage.") elif roll >= 15: print(roll) print("You hit with a " + w1.name + "!") damage = d.rolls(w1.damage_dice[0], w1.damage_dice[1]) print(str(damage) + " point(s) of " + w1.type + " damage.") else: print(roll) print("You missed!")
def __init__(self, playerList): """ Description: Constructor Precondition: playerList is list of Player objects Postcondition: Yahtzee attributes are initialized """ self.__players = [player for player in playerList] self.__turns = 0 self.__dice = [Dice(6) for i in range(5)]
def main(): print("The Dice Roller program") #print an image of every possible roll die = Die() for i in range(1, 7): die.value = i print(die.image) print() # get number of dice from user count = int(input("Enter the number of dice to roll: ")) # create Die objects and add to Dice object dice = Dice() for i in range(count): die = Die() dice.addDie(die) while True: # roll the dice dice.rollAll() print("YOUR ROLL: ") for die in dice: print(die) print("\nTotal:\t" + str(dice.getTotal())) print("\n") choice = input("Roll again? (y/n): ") if choice != "y": print("Bye!") break
class TestDice(TestCase): def setUp(self): self.fair_dice = Dice() self.bribed_dice = Dice(sides_probabilities=[0.2, 0.1, 0.3, 0.1, 0.1, 0.2]) def test_check_if_fair_dice_roll_values_are_valid(self): for _ in range(1000): value = self.fair_dice.random_roll_value() self.assertGreaterEqual(value, 0) self.assertLessEqual(value, 6) def test_check_if_bribed_dice_roll_values_are_valid(self): for _ in range(1000): value = self.bribed_dice.random_roll_value() self.assertGreaterEqual(value, 0) self.assertLessEqual(value, 6) def test_expect_exception_if_probability_sum_is_not_equal_1(self): self.failUnlessRaises(ValueError, Dice, [0.2, 0.1, 0.3, 0.1, 0.1, 0.5])
class DiceGame: # Constructor def __init__(self): # 2 new instances of Dice object self.m_d1 = Dice() self.m_d2 = Dice() def play(self): self.m_d1.roll() self.m_d2.roll() print('m_d1: {}'.format(self.m_d1.getValue())) print('m_d2: {}'.format(self.m_d2.getValue())) return self.m_d1.getValue() + self.m_d2.getValue() == 7
def _getFirstPlayer(self, playerList): ''' Returns the first player based on rolling a dice.''' highestRollers = set() highestRoll = 0 dice = Dice() for player in playerList: print(player.getName() + " rolls a " + str(dice.getTop())) if dice.getTop() > highestRoll: highestRollers.clear() highestRollers.add(player) highestRoll = dice.getTop() elif dice.getTop() == highestRoll: highestRollers.add(player) dice.roll() if len(highestRollers) > 1: return self._getFirstPlayer(highestRollers) else: return highestRollers.pop()
from Dice import Dice from User import User dice = Dice(6) user1 = User(1, dice.getSideCount()) i = 0 while i < 100: print("Roll#: " + str(i)) roll = dice.rollDice() print("~ " + str(roll)) user1.addStats(roll) print("---------") i = i + 1 print("\nUser stats: ") user1.getStats()
def __init__(self): # 2 new instances of Dice object self.m_d1 = Dice() self.m_d2 = Dice()
def setUp(self): self.fair_dice = Dice() self.bribed_dice = Dice(sides_probabilities=[0.2, 0.1, 0.3, 0.1, 0.1, 0.2])
def __init__(self): self._hand = Dice() self._hand.addDie(sides = 6, count = 4) # init to 4d6
def setUp(self): self.fair_dice = Dice() self.biased_dice = Dice(probabilities=[0.2, 0.1, 0.3, 0.1, 0.1, 0.2])