Exemplo n.º 1
0
 def attack(self):
     attack_value=self.base_attack
     for item in self.equipped_items:
         attack_value+=item.attack_value
     dice=Die()
     attack=dice.roll(attack_value, 6)
     return attack
Exemplo n.º 2
0
    def __init__(self, root):
        self.root = root
        self.dice = Die()

        self.label_sides = Label(self.root, text='Side number:')
        self.label_sides.pack()

        self.entry_side = Entry(self.root)
        self.entry_side.pack()

        self.label_throw = Label(self.root, text='Number of dice rolls:')
        self.label_throw.pack()

        self.entry_throw = Entry(self.root)
        self.entry_throw.pack()

        self.label_dice = Label(self.root, text='Number of dices:')
        self.label_dice.pack()

        self.entry_dice = Entry(self.root)
        self.entry_dice.pack()

        self.button_generate = Button(self.root,
                                      text='Generate',
                                      command=self.taking)
        self.button_generate.pack()

        self.button_show = Button(self.root,
                                  text='Show created File',
                                  command=self.show)
        self.button_show.pack()
def encounter(character_1, character_2):
    strength_modifier = calculate_attribute_modifier(
        character_1.get_strength(), character_2.get_strength())
    skill_modifier = calculate_attribute_modifier(character_1.get_skill(),
                                                  character_2.get_skill())

    print "Stength modifier: %d" % strength_modifier
    print "Skill modifier: %d" % skill_modifier

    die = Die(6)
    die_score_1 = die.roll()
    die_score_2 = die.roll()

    print "Die score 1: %d, die score 2: %d" % (die_score_1, die_score_2)

    if die_score_1 == die_score_2:
        print "Tie!"
    else:
        if die_score_1 > die_score_2:
            print "Player 1 wins!"
            character_1.set_strength(character_1.get_strength() +
                                     strength_modifier)
            character_1.set_skill(character_1.get_skill() + skill_modifier)
            character_2.set_strength(character_2.get_strength() -
                                     strength_modifier)
            character_2.set_skill(character_2.get_skill() - skill_modifier)
        else:
            print "Player 2 wins!"
            character_1.set_strength(character_1.get_strength() -
                                     strength_modifier)
            character_1.set_skill(character_1.get_skill() - skill_modifier)
            character_2.set_strength(character_2.get_strength() +
                                     strength_modifier)
            character_2.set_skill(character_2.get_skill() + skill_modifier)
Exemplo n.º 4
0
def main():
    print("The Dice Roller program")
    for i in range(1, 7):
        die = Die()
        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.list:
            print(die.image)
        print()
        print("TOTAL:", dice.getTotal())
        print()

        choice = input("Roll again? (y/n): ")
        if choice != "y":
            print("Bye!")
            break
Exemplo n.º 5
0
def main():
    print("The Dice Roller program")
    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: ", end="")
        for die in dice.getTuple():
            print(die.getValue(), end=" ")
        print("\n")

        choice = input("Roll again? (y/n): ")
        if choice != "y":
            print("Bye!")
            break
Exemplo n.º 6
0
    def __init__(self, num_players: int, player_names: List[str]):
        LOG.info("Call to GameBoard.__init__")

        self.red_deck = CardDeck(
            "People"
        )  # Are these the right color to category mappings?  If we want to stick with colors, that's fine
        self.white_deck = CardDeck("Events")
        self.blue_deck = CardDeck("Places")
        self.green_deck = CardDeck("Independence Day")

        self.die = Die(num_sides=6)
        self.game_positions = GamePositions()

        self.players = []
        self.current_player = None  # It might be useful to have this property to easily access the player whose turn it is
        self.direction = ""  # The direction the player has chosen to move (not yet sure what values this can take)

        self.pixel_to_position_scaling_factor = 78  # Multiple a game_position location (in matrix) by this number to get the pixel location equivalent
        self.pixel_to_position_offset = (
            12, 12
        )  # add these x and y values to the scaled pixel location to get starting square (since it isn't in top left corner)

        colors = ['red', 'white', 'blue', 'green']
        for player_num in range(0, num_players):
            self.players.append(
                Mover(name=player_names[player_num],
                      mover_color=colors[player_num],
                      start_pos_x=0,
                      start_pos_y=0))
Exemplo n.º 7
0
 def test_die(self):
     print("test_die")
     print(
         "Testing a six-sided die by creating and rolling.  The result must be between 1 and 6 (inclusive)."
     )
     die = Die(6)
     face_value = die.roll()
     self.assertGreater(face_value, 0)
     self.assertLessEqual(face_value, 6)
Exemplo n.º 8
0
 def __init__(self, size = 30):
     ### Author: Dustin Hup
     ### DAet: 02-06-2014
     ### Purpose: To initalize the dmion cass
     ### Input: Size, the size of the die.n
     ### Output: None
     self.size = size
     self.lstDice = [Die(size = self.size), Die(size = self.size)]
     self.value = int(str(self.lstDice[0].value) + str(self.lstDice[1].value))
def get_attribute_level():
    initial_value = 10
    
    die_12 = Die(12)
    score_of_12 = die_12.roll()
    die_4 = Die(4)
    score_of_4 = die_4.roll()
    change = floor(score_of_12 / score_of_4)
    
    return int(initial_value + change)
Exemplo n.º 10
0
 def __init__(self, Name, hp_dice, base_attack, base_defense, xp_value, renown_value):
     self.Name=Name
     self.xp_value=xp_value
     self.renown_value=renown_value
     dice = Die()
     self.hpmax=dice.roll(hp_dice, 6)
     self.current_hp = self.hpmax
     self.base_attack=base_attack
     self.base_defense=base_defense
     self.equipment=[]
     self.equipped_items=[]
     self.gold=dice.roll(5, 6)
Exemplo n.º 11
0
 def __init__(self, name, level):
     self.level=level
     self.name=name
     die = Die()
     self.hpmax=die.roll(15, 6)
     self.current_hp = self.hpmax
     self.base_attack=3
     self.base_defense=2
     self.equipment=[]
     self.equipped_items=[]
     self.gold=50
     self.xp=0
     self.renown=0
     self.next_levelup = 100
Exemplo n.º 12
0
 def __init__(self):
     self.turn = 1
     self.score = 0
     self.scoreThisTurn = 0
     self.isTurnOver = False
     self.isGameOver = False
     self.die = Die()
Exemplo n.º 13
0
def main():
    print("The Dice Roller Program")
    print()

    # get number of dice from user
    count = int(input("Enter the number of dice to roll: "))

    # Dice object and add Die objects to it
    dice = Dice()
    for i in range(count):
        die = Die()
        dice.addDie(die)

    while True:
        # roll the dice
        dice.rollAll()
        print("Your Roll: ", end="")
        for die in dice.list:
            print(die.value, end=" ")
        print("\n")

        choice = input("Roll again? (y/n): ")
        if choice != "y":
            print("Bye!")
            break
Exemplo n.º 14
0
    def from_file(cls, file):
        line_number = 1
        rows = []
        text = None
        with codecs.open(file, encoding='utf-8') as f:
            for line in f:
                if line_number == 1:
                    identifier = line.strip()
                elif line_number == 2:
                    parts = line.split(PART_SEPARATOR)
                    dice_part = parts[0]
                    if re.search(r"d\*", dice_part):
                        dice = None
                    else:
                        dice = Dice.from_string(parts[0])
                    title = parts[1].strip()
                    if len(parts) > 2:
                        text = parts[2].strip()
                else:
                    try:
                        rows.append(RollTableRow.from_string(line.strip()))
                    except MalformedRowError:
                        rows.append(
                            RollTableRow.from_string('{}{}{}'.format(
                                line_number - 2, PART_SEPARATOR,
                                line.strip())))
                line_number += 1

        if len(rows) == 0:
            raise Exception('Empty file: {}'.format('file'))

        if dice is None:
            dice = Dice([Die(len(rows))])
        table = cls(dice, rows, title, text)
        return (identifier, table)
Exemplo n.º 15
0
def main():
    print("The Dice Roller program")
    print()

    # get the number of dice from user
    count = int(input('Enter the number of dice to roll: '))

    # create Dice object and add Die objects to it
    dice = Dice()
    for i in range(count):
        die = Die()
        dice.addDie(die)

    while True:
        # roll the dice
        dice.rollAll()
        print("YOUR ROLL: ", end="")
        for die in dice.list:
            print(die.value, end=" ")
        print("\n")

        choice = input("Roll again? (y/n): ").lower()
        if choice != 'y':
            print("Bye!")
            break
Exemplo n.º 16
0
    def parse(self, diceString):
        def raiseValueError():
            raise ValueError("Invalid diceString value: {0}".format(diceString))

        if not diceString: raiseValueError()
        
        match = re.match(r"(\d*)d(\d+)([\+\-]\d+)?\s*(?:\(([\+\-]?\d+)\))?", diceString.strip())

        if not match: raiseValueError()

        dice, sides, modifier, showing = match.groups()

        sides = int(sides)

        if not dice: dice = 1
        else: dice = int(dice)

        if not modifier: modifier = 0
        else: modifier = int(modifier)


        if showing:
            showing = int(showing)

            if showing > sides * dice + modifier:
                raiseValueError()

            if showing < dice + modifier:
                raiseValueError()

            if sides > 1:
                numberAtMax = (showing - modifier - dice) / (sides - 1)
                remainder = (showing - modifier) - (numberAtMax * sides) - (dice - numberAtMax - 1)

                def getShowing(index):
                    if index < numberAtMax:
                        return sides
                    if index == numberAtMax:
                        return remainder
                    return 1

                return Pool([Die(sides=int(sides),
                    showing=getShowing(index)) for index in range(dice)], modifier=modifier, rolled=True)


        return Pool([Die(sides=int(sides)) for d in range(dice)], modifier=modifier)
Exemplo n.º 17
0
class YahtzeeGame:
    def __init__(self, num_of_dice: int = 5):
        self.num_of_dice = num_of_dice
        self.die = Die()

    def roll(self, num: int) -> [int]:
        '''Rolls num amount of dice'''
        return [self.die.roll() for i in range(num)]
Exemplo n.º 18
0
 def roll(self, numberOfDies=6):
     if not self.diceRolling:
         rollNum = numberOfDies
     else:
         rollNum = self.diceRolling
     aRoll = ''
     for die in range(rollNum):
         aRoll = str(Die()) + ' ' + aRoll
     self.currentRoll = aRoll[:]
Exemplo n.º 19
0
def fight():
    from enemylist import enemylist
# PICKS AN ENEMY FROM ENEMYLIST FILE
    opponent=random.choice(enemylist)


    print "You are fighting "+opponent.Name, "\n\tOpponent's max HP:", opponent.hpmax, "\n\tYour HP:", playerone.current_hp

    while opponent.current_hp > 0 or playerone.current_hp > 0:
        dice = Die()
        player_initiative = dice.roll(1, 21)
        opponent_initiative = dice.roll(1, 21)
        
        if player_initiative > opponent_initiative:
            print "Player goes first."


            player_attacks(playerone, opponent)

            if opponent.current_hp <= 0:
                won_fight(playerone, opponent)
                break

            enemy_attacks(opponent, playerone)
            if playerone.current_hp <= 0:
                playerone.current_hp = playerone.hpmax
                print "You were defeated. Returning to main menu"
                break
            print "Your hp: ", playerone.current_hp, "Enemy's hp: ", opponent.current_hp
        
        elif opponent_initiative>player_initiative:
            print "Opponent goes first."
            enemy_attacks(opponent, playerone)
            if playerone.current_hp <= 0:
                playerone.current_hp = playerone.hpmax
                print"You were defeated. Returning to main menu"

            player_attacks(playerone, opponent)
            if opponent.current_hp <= 0:
                won_fight(playerone, opponent)
                break
            print "Your hp: ", playerone.current_hp, "Enemy's hp: ", opponent.current_hp
        print "END OF TURN\n-----------------------------"
Exemplo n.º 20
0
def main():
    print("The Dice Roller program")
    # Declare i as 6
    i = 6
    # Use a loop to create a Die object until i equals 0
    while i != 0:
        # Create a Die object by using i as the value
        d = Die(i)
        # Call the image function to draw the die's picture
        d.image
        # Decrement i byy 1
        i -= 1
    # Print an empty line
    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(None)
        dice.addDie(die)

    while True:        
        # roll the dice
        dice.rollAll()
        print("YOUR ROLL: ")
        for die in dice.list:
            # Call the image function from Die class to draw picture of the value
            die.image
        print("\n")
        # Call the getTotal function from the Dice class and assign it to tot
        tot = dice.getTotal()
        # print tot
        print("Total: " + str(tot))
        # Call the getAvg function from the Dice class and assign it to avg
        avg = dice.getAvg()
        # print avg
        print("Average: " + str(avg) + "\n")
        choice = input("Roll again? (y/n): ")
        if choice != "y":
            print("Bye!")
            break
def encounter(character_1, character_2):
    strength_modifier = calculate_attribute_modifier(
        character_1.get_strength(),
        character_2.get_strength())
    skill_modifier = calculate_attribute_modifier(
        character_1.get_skill(), character_2.get_skill())
    
    print "Stength modifier: %d" % strength_modifier
    print "Skill modifier: %d" % skill_modifier
    
    die = Die(6)
    die_score_1 = die.roll()
    die_score_2 = die.roll()
    
    print "Die score 1: %d, die score 2: %d" % (die_score_1,
                                                die_score_2)
    
    if die_score_1 == die_score_2:
        print "Tie!"
    else:
        if die_score_1 > die_score_2:
            print "Player 1 wins!"
            character_1.set_strength(character_1.get_strength() + 
                                     strength_modifier)
            character_1.set_skill(character_1.get_skill() + 
                                  skill_modifier)
            character_2.set_strength(character_2.get_strength() - 
                                     strength_modifier)
            character_2.set_skill(character_2.get_skill() - 
                                  skill_modifier)
        else:
            print "Player 2 wins!"
            character_1.set_strength(character_1.get_strength() - 
                                     strength_modifier)
            character_1.set_skill(character_1.get_skill() - 
                                  skill_modifier)
            character_2.set_strength(character_2.get_strength() + 
                                     strength_modifier)
            character_2.set_skill(character_2.get_skill() + 
                                  skill_modifier)
Exemplo n.º 22
0
def main():
    myTimer = timer.begin_timer()
    stringer.show_welcome(NAME)
    print()

    while True:
        print()

        try:
            number = val.get_int("Enter number of dice to roll: ", 10,
                                 0)  # use validation module to set max 10 dice

            #create Dice object to hold the dice
            dice = Dice()
            for i in range(number):
                die = Die()
                dice.addDie(die)

            #roll dem bones!
            dice.rollAll()

            print("YOUR ROLL: ")
            # use itertor from class Dice
            for die in dice:
                print(die.getImage())
            print()

        except Exception as e:
            print("There was an Error processing your roll.", e)
            break

        choice = input("Roll again? (y/n): ").lower()
        if choice != "y":
            break

    # end while loop

    timer.stop_timer(myTimer)
    print("Bye!")
Exemplo n.º 23
0
def main():
    print("The Dice Roller program")
    print(" _____ \n" + \
          "|o   o|\n" + \
          "|o   o|\n" + \
          "|o___o|")
    print(" _____ \n" + \
          "|o   o|\n" + \
          "|  o  |\n" + \
          "|o___o|")
    print(" _____ \n" + \
          "|o   o|\n" + \
          "|     |\n" + \
          "|o___o|")
    print(" _____ \n" + \
          "|o    |\n" + \
          "|  o  |\n" + \
          "|____o|")
    print(" _____ \n" + \
          "|o    |\n" + \
          "|     |\n" + \
          "|____o|")
    print(" _____ \n" + \
          "|     |\n" + \
          "|  o  |\n" + \
          "|_____|")
    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.list:
            print(die.image)
        print("\n")

        choice = input("Roll again? (y/n): ")
        if choice != "y":
            print("Bye!")
            break
def get_attribute_level():
    initial_value = 10
    
    die_12 = Die(12)
    score_of_12 = die_12.roll()
    die_4 = Die(4)
    score_of_4 = die_4.roll()
    change = floor(score_of_12 / score_of_4)
    
    return int(initial_value + change)
Exemplo n.º 25
0
 def __init__(self, num_of_dice: int = 5):
     self.num_of_dice = num_of_dice
     self.die = Die()
Exemplo n.º 26
0
from dice import Die, D6
from hands import Hand

d1 = Die()
print(d1.value)
d2 = Die(6)
print(d2.value)
d3 = D6()
print(d3.value)

print(int(d2))
print(6 + d2)
print(d2 > 3)

h1 = Hand(4, D6)
print(h1)
print(h1[0].value)
Exemplo n.º 27
0
 def __init__(self, name):
     self.name = name
     self.round = 1
     self.die1 = Die()
     self.die2 = Die()
Exemplo n.º 28
0
from plotly.graph_objs import Bar, Layout
from plotly import offline
from dice import Die

# Create a D6 and a D10
die_1 = Die()
die_2 = Die(10)

# Make some rolls, and store results in a list
results = []
for roll_num in range(50_000):
    result = die_1.roll() + die_2.roll()
    results.append(result)
# Analyze the results
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)
#Visualize the results
x_values = list(range(2, max_result + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling D6 and D10 50,000 times',
                   xaxis=x_axis_config,
                   yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6_d10.html')
Exemplo n.º 29
0
 def test_die_roll_in_range(self):
     die = Die(rnd.randint(1,101)) 
     self.assertIn(die.roll(), range(1, die.sides+1))
Exemplo n.º 30
0
class Angry_dice:
    """
    Class that controls the flow of an Angry Dice player.

    Arguments:
    stage = Whetherhich stage the player is currently in.
    die_a = The first Die object.
    die_b = The second Die object.
    cheating = Whether or not the player held a 6 (bool).
    """

    def __init__(self):
        self.stage = 1
        self.die_a = Die(["1", "2", "ANGRY", "4", "5", "6"])
        self.die_b = Die(["1", "2", "ANGRY", "4", "5", "6"])
        self.cheating = False

    def play(self):
        """Controls the actual flow of the game."""

        input("""
Welcome to Angry Dice! Roll the two dice until you get thru the 3 Stages!
Stage 1 you need to roll 1 & 2
Stage 2 you need to roll ANGRY & 4
Stage 3 you need to roll 5 & 6
You can lock a die needed for your current stage
and just roll the other one, but beware!
If you ever get 2 ANGRY's at once, you have to restart to Stage 1!
Also, you can never lock a 6!  That's cheating!

To rol the dice, simply input the name of the die you want to roll.
Their names are a and b.

Press ENTER to start!
        """)
        self.cheating = self.roll_parse("ab")
        done = False
        while not done:
            self.print_hand()
            decision = input("Roll dice: ")
            self.cheating = self.roll_parse(decision)
            done = self.advance_check()
        self.print_hand()
        print("You've won!  Calm down!")

    def roll_parse(self, string):
        """
        Takes an input string and rolls the appropriate dice.  Returns
        whether or not the player was cheating with that roll (bool).

        Arguments:
        string = an input string from the user.
        VALUES = values you're allowed to hold in each stage.
        """
        VALUES = [["1", "2"], ["ANGRY", "4"], ["5"]]
        cheating = False
        if "a" not in string:
            self.die_a.held = True
            if self.die_a.value not in VALUES[self.stage - 1]:
                cheating = True
        else:
            self.die_a.held = False
        if "b" not in string:
            self.die_b.held = True
            if self.die_b.value not in VALUES[self.stage - 1]:
                cheating = True
        else:
            self.die_b.held = False
        if not self.die_a.held:
            self.die_a.roll()
        if not self.die_b.held:
            self.die_b.roll()
        return cheating

    def print_hand(self):
        """
        Prints to dice currently held, and whether or not the
        player has cheated.

        Arguments: none
        """
        if self.cheating:
            print("You're cheating!")
            print("until you reroll it!")
        print("""
You rolled:
a = [  {}  ]
b = [  {}  ]

You are in Stage {}
        """.format(self.die_a, self.die_b, self.stage))

    def advance_check(self):
        """Checks conditions of each stage."""
        values = [self.die_a.value, self.die_b.value]
        if self.stage == 3:
            if not self.cheating and "5" in values and "6" in values:
                return True
        if self.stage == 2 and "ANGRY" in values and "4" in values:
            self.stage = 3
        if self.stage == 1 and "1" in values and "2" in values:
            self.stage = 2
        if self.die_a.value == self.die_b.value == "ANGRY":
            print("WOW, you're ANGRY!")
            self.stage = 1
        return False
Exemplo n.º 31
0
from plotly.graph_objs import Bar, Layout
from plotly import offline
from dice import Die

# Create a 2 D8 dice
die_1 = Die(8)
die_2 = Die(8)

# Make some rolls, and store results in a list
results = []
for roll_num in range(1000):
    result = die_1.roll() + die_2.roll()
    results.append(result)
# Analyze the results
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result+1):
    frequency = results.count(value)
    frequencies.append(frequency)
#Visualize the results
x_values = list(range(2, max_result+1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick':1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling two D8 1,000 times', xaxis = x_axis_config, yaxis = y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d8_d8.html')

Exemplo n.º 32
0
from plotly.graph_objs import Bar, Layout
from plotly import offline
from dice import Die

# Create a D6 and a D10
die_1 = Die()
die_2 = Die()
die_3 = Die()

# Make some rolls, and store results in a list
results = []
for roll_num in range(1000):
    result = die_1.roll() + die_2.roll() + die_3.roll()
    results.append(result)
# Analyze the results
frequencies = []
max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides
for value in range(3, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)
#Visualize the results
x_values = list(range(3, max_result + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling three D6 1,000 times',
                   xaxis=x_axis_config,
                   yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6_d6.html')
Exemplo n.º 33
0
from tank_factory import create_tank
from dice import Die

d100 = Die(100)

target_range = {"P": 90, "S": 70, "M": 50, "L": 30, "E": 10}

# TODO
# Input attacker, defender.
# Input angle of attack.
# Input target range.
# Check if the target range is greater than attackers extreme range. If it does return to previous step.
# Find appropriate target roll in target range dict.
# Roll dice. If the roll is equal or less than the target roll check if attackers gun penetrates defender's armor.
# Implement hit logic.

def bg_direct_fire_step(shooter, defender):

    # Create both tanks.
    attk = create_tank(shooter)
    dfnd = create_tank(defender)

    # Input shot relevant data.
    aoa = input('Input angle of attack (front/rear): ')
    rng = int(input("Input range to defender unit: "))

    # Check if the target is out of range.
    if rng > attk.off_info.r_e:
        print(f"Incorrect range, input value between 1 and {attk.off_info.r_e}.")
        rng = int(input("Input range to defender unit: "))
Exemplo n.º 34
0
from dice import Die
d = Die()
d.roll_die()
for number in range(10):
    d.roll_die()
print("\n")
d2 = Die(10)
d3 = Die(12)
for number in range(0, 10):
    d2.roll_die()
print("\n")
for number in range(0, 10):
    d3.roll_die()
Exemplo n.º 35
0
from dice import Die

d6 = Die(6)


class Tank:
    def __init__(self, name, gun, armor, health=10):
        self.name = name
        self.health = health
        self.gun = gun
        self.armor = armor

    def __repr__(self):
        return f"{self.name}, {self.health}, {self.gun}, {self.armor}"

    def attack(self, defender):
        attackDamage = self.gun.damage + d6.roll_dice()
        defenderDamage = defender.takeHit(attackDamage)
        if defender.isAlive():
            print(f"{defender.name} is still alive")
        else:
            print("BOOM, you killed it!")

    def takeHit(self, attack):
        hitAmount = attack - self.armor.protection
        if hitAmount > 0:
            self.health -= hitAmount
            print(f"damage: {hitAmount}")
            return hitAmount
        else:
            return 0
Exemplo n.º 36
0
class Player:
    def __init__(self, name):
        self.name = name
        self.round = 1
        self.die1 = Die()
        self.die2 = Die()

    def roll_round(self):
        self.die1.roll()
        self.die2.roll()
        self.display_dice()
        query = input('Would you like to hold die A or B or press Enter to continue? ')
        if query.upper() == 'A':
            if self.die1.held == True:
                self.die1.held = False
            else:
                if self.die1.value != 6:
                    self.die1.held = True
                else:
                    print('You can not hold a 6.')
        elif query.upper() == 'B':
            if self.die2.held:
                self.die2.held = False
            else:
                if self.die2.value != 6:
                    self.die2.held = True
                else:
                    print('You can not hold a 6.')

    def display_dice(self):
        separator = ' | '
        spaces = ' ' * int(len(self.die1.art[0]) / 2)
        print(spaces + "A" + spaces + separator + spaces + "B")
        print(self.die1.art[0] + separator + self.die2.art[0])
        print(self.die1.art[1] + separator + self.die2.art[1])
        print(self.die1.art[2] + separator + self.die2.art[2])
        print(self.die1.art[3] + separator + self.die2.art[3])
        print(self.die1.art[4] + separator + self.die2.art[4])
        if self.die1.held:
            print("  HELD   " + separator + spaces + " ")
        elif self.die2.held:
            print("         " + separator + "  HELD   ")

    def check_win(self):
        if self.die1.value  == 3 and self.die2.value == 3:
            print("Why so angry? Go back to round One")
            self.round = 1
            self.die1.held = False
            self.die2.held = False

        elif self.round == 1:
            if self.die1.value + self.die2.value == 3:
                print("Welcome to round 2, {}".format(self.name))
                self.round = 2
                self.die1.held = False
                self.die2.held = False

        elif self.round == 2:
            if self.die1.value == 3 and self.die2.value == 4 or self.die1.value == 4 and self.die2.value == 3:
                print("Welcome to round 3, {}".format(self.name))
                self.round = 3
                self.die1.held = False
                self.die2.held = False

        elif self.round == 3:
            if self.die1.value + self.die2.value == 11:
                print("You win, {}!".format(self.name))
                quit()
Exemplo n.º 37
0
import pygal
from dice import Die

#Utworzenie kości typu D6 i D10.
die_1 = Die()  #1.
die_2 = Die(10)  #2.

#Wykorzystanie pewnej liczby rzutów i umieszczenie wyników na liście.
results = []
for roll_num in range(50000):  #2
    result = die_1.roll() + die_2.roll()
    results.append(result)

#Analiza wyników.
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

#Wizualizacja wyników
hist = pygal.Bar()
hist.force_uri_protocol = 'http'

hist.title = "Wynik rzucania pojedyńczą kością D6 i D10 pięćdziesiąt tysięcy razy."
hist.x_labels = [
    '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
    '16'
]
hist.x_title = "Wynik"
hist.y_title = "Częstotliwość występowania wartości"
Exemplo n.º 38
0
from plotly.graph_objs import Bar, Layout
from plotly import offline
from dice import Die

# Create a 2 D8 dice
die_1 = Die()
die_2 = Die()

# Make some rolls, and store results in a list
results = []
for roll_num in range(1000):
    result = die_1.roll() * die_2.roll()
    results.append(result)
# Analyze the results
frequencies = []
max_result = die_1.num_sides * die_2.num_sides
for value in range(1, max_result+1):
    frequency = results.count(value)
    frequencies.append(frequency)
#Visualize the results
x_values = list(range(1, max_result+1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick':1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of multiplying the rolling two D6 1,000 times', xaxis = x_axis_config, yaxis = y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6xd6.html')

Exemplo n.º 39
0
from dice import Die
from plotly.graph_objs import Bar, Layout
from plotly import offline

die = Die()
results = []

for roll_num in range(1000):
    result = die.roll()
    results.append(result)

frequencies = []
for value in range(1, die.num_sides + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

x_values = list(range(1, die.num_sides + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result'}
y_axis_config = {'title': 'Frequency'}

my_layout = Layout(title='My Graph', xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')
# Import module and the Die Class.
import random
from dice import Die

# Instansiates (creats) new objects from the Die Class.
# These will be our three new dice (Red, Green and Blue dice).
red_die = Die("Red", [0, 0, 4, 4, 8, 8], [])
green_die = Die("Green", [2, 2, 3, 3, 7, 7], [])
blue_die = Die("Blue", [1, 1, 5, 5, 6, 6], [])

# A string variable for calling the winner.
the_winner = "Wait what, no winner??"

# Input from user;
numberofdice = int(input("Choose number of players(2 or 3): "))
numberofrolls = int(input("Choose number of rolls: "))


# Defines a function for using 2 color dice.
def roll_die_2():
    i = 0
    num = numberofrolls
    # Setting variables to global, so we can reuse them outside the function.
    global first_player, second_player

    # Sets the color for the first player.
    if (choose_player1.lower() == "red"):  # lower(); convert to lowercase.
        first_player = red_die
    elif (choose_player1.lower() == "green"):
        first_player = green_die
    elif (choose_player1.lower() == "blue"):
Exemplo n.º 41
0
 def __init__(self):
     self.stage = 1
     self.die_a = Die(["1", "2", "ANGRY", "4", "5", "6"])
     self.die_b = Die(["1", "2", "ANGRY", "4", "5", "6"])
     self.cheating = False