class DieRollTest(unittest.TestCase): """Test the functionality of the Die class' roll function.""" def setUp(self): self.possible_values = [1, 2, 3, "Dog", "Cat", "Hippo"] self.new_die = Die(self.possible_values) def tearDown(self): del self.possible_values del self.new_die def test_roll_once(self): """Roll the die once and ensure the returned value is in possibleValues""" self.assertIn(self.new_die.roll(), self.possible_values, "Rolled value was not in possibleValues of Die") def test_rolled_value_changes(self): """Roll the die a number of times and make sure it changes value""" holding_value = self.new_die.roll() for i in range(10): if self.new_die.roll() != holding_value: self.assertTrue(True) return self.assertTrue(False, "Die Value did not change from Holding Value " "for 10 rolls") def test_currentValue_is_updated_to_rolled_value(self): """Make sure that the Die's currentValue is updated to match what is rolled.""" self.new_die.currentValue = 5 self.assertEqual(self.new_die.roll(), self.new_die.currentValue, "Current Value was not different from rolled")
def test_roll_one_die(self): """Roll one die using the roll_the_dice function.""" angry_game = AngryDiceGame() single_die = Die([1,2,3,"Dog"]) single_die.currentValue = 7 angry_game.roll_the_dice([single_die]) self.assertNotEqual(single_die.currentValue, 7, "Die was not rolled")
def __init__(self, start=True): """ input start:boolean defaults to True. If set to false the game will not start. """ self.dice_a = Die(*self.DICE_FACE_VALUES) self.dice_b = Die(*self.DICE_FACE_VALUES) self.current_stage = 1 self.current_dice_a_value = "" self.current_dice_b_value = "" self.game_over = False if start: self.game_controller()
def __init__(self, conf={}): conf = self.get_conf_values() self.die = Die(no_of_faces=conf['no_of_faces_of_die']) self.board = Board(no_of_rows=conf['no_of_rows'], no_of_columns=conf['no_of_columns'], snakes_conf=conf['snakes'], ladders_conf=conf['ladders'], die=self.die)
def main(): theDie = Die() count = eval(input("How many times should I roll the die? ")) c1 = 0 c2 = 0 c3 = 0 c4 = 0 c5 = 0 c6 = 0 for i in range(count): theDie.roll() val = theDie.getFaceValue() if val == 1: c1 = c1 + 1 elif val == 2: c2 = c2 + 1 elif val == 3: c3 = c3 + 1 elif val == 4: c4 = c4 + 1 elif val == 5: c5 = c5 + 1 elif val == 6: c6 = c6 + 1 else: print ("Error - value of die was", val) c1Percent = float(c1)/count * 100 c2Percent = float(c2)/count * 100 c3Percent = float(c3)/count * 100 c4Percent = float(c4)/count * 100 c5Percent = float(c5)/count * 100 c6Percent = float(c6)/count * 100 print ("Value 1 came up:", c1, "or a percentage of", c1Percent) print ("Value 2 came up:", c2, "or a percentage of", c2Percent) print ("Value 3 came up:", c3, "or a percentage of", c3Percent) print ("Value 4 came up:", c4, "or a percentage of", c4Percent) print ("Value 5 came up:", c5, "or a percentage of", c5Percent) print ("Value 6 came up:", c6, "or a percentage of", c6Percent)
class DieRollTest(unittest.TestCase): """Test the roll functionality of the Die class' roll function.""" def setUp(self): self.possible_values = ["John Snow", "Tyrion Lannister", "Brienne of Tarth", 1, 2] self.new_die = Die(*self.possible_values) print(self.shortDescription()) def test_roll_once(self): """roll the dice once and ensure the value is in possibleValues""" self.assertIn(self.new_die.roll(), self.possible_values, "Asserted rolled value not in possible_values") def test_rolled_value_changes(self): """tests that the dice's returned value does actually change.""" holding_value = self.new_die.roll() for i in range(10): if self.new_die.roll() != holding_value: print("Rolled Die value {} is different than Holding Value" .format( self.new_die.currentValue, holding_value )) self.assertTrue(True) return error_message = "Holding value was the same for 10 rolls." self.assertTrue(False, error_message) def test_currentValue_is_updated_to_rolled_value(self): """Make sure that the roll function does update self.currentValue""" # make sure new initialized die, has a currentValue of 0 self.assertEqual('', self.new_die.currentValue) new_roll = self.new_die.roll() self.assertEqual(new_roll, self.new_die.currentValue, "The rolled value doesn't equal currentValue")
def main(): trisha = Die(-5) ## trisha.roll() print("Trisha", trisha.getFaceValue()) print(trisha) ## sheldon = Die() ## for i in range(10): ## trisha.roll() ## sheldon.roll() ## tValue = trisha.getFaceValue() ## sValue = sheldon.getFaceValue() ## if sValue <= tValue: ## sheldon.setFaceValue(5.5) ## sValue = sheldon.getFaceValue() ## print("Trisha: " + str(tValue), end = " ") ## print("Sheldon: " + str(sValue)) ## if tValue > sValue: ## print ("Trisha won!") ## elif tValue == sValue: ## print("Tie") ## else: ## print("Sheldon won!") print ("Done!")
def __init__(self): self.board = Board() self.move_manager = MoveManager(self.board) self.players = [PlayerMoveFirstPawn(p, self.board) for p in Players] self.current = Players.black self.die = Die() self._retry_counter = 0 # save finishers self.finishers = [] self.event_ready = threading.Event() self.event_finished = threading.Event() # Look to serialize canvas drawings self.lock = threading.Lock() # Thread for tk mainloop, this runs until the program gets exited self.tk_thread = threading.Thread(target=self._tk_mainloop)
class LuckyPython(object): def __init__(self, conf={}): conf = self.get_conf_values() self.die = Die(no_of_faces=conf['no_of_faces_of_die']) self.board = Board(no_of_rows=conf['no_of_rows'], no_of_columns=conf['no_of_columns'], snakes_conf=conf['snakes'], ladders_conf=conf['ladders'], die=self.die) def get_board(self): return self.board.get_board() def get_changed_player(self): return self.board.get_active_player() def get_score(self): score = self.die.get_score() return score def add_player(self, object): return self.board.add_player(object) def set_board_status(self, object): if object['status'] == 'start': self.board.msg = 'Starting the game' self.board.status = 'P' #start play def set_score(self, score_object): return self.board.set_score(score_object) def get_turn(self): return self.board.get_turn() def get_conf_values(self): """ get from user """ #FIXME conf_dict = {'no_of_columns': 10, 'no_of_rows': 10, 'snakes': ((20, 10), (40, 6), (66, 33), (98, 18)), 'ladders': ((5, 14), (32, 62), (46, 58), (60, 84)), 'no_of_faces_of_die': 6} return conf_dict
def load_sprites(self): self.player_group = CameraSpriteGroup() self.player_bullet_group = CameraSpriteGroup() self.player_max_hp = 20 self.player_healthbar = HealthBar(self.player_max_hp, self.player_max_hp, "res/player_healthbar.png", (128, 16)) self.player_healthbar.rect.x = -55 self.player_healthbar.rect.y = 10 self.player_hb_group = CameraSpriteGroup() self.player_hb_group.add(self.player_healthbar) self.enemy_group = CameraSpriteGroup() self.enemy_bullet_group = CameraSpriteGroup() self.health_bar_sprites = CameraSpriteGroup() self.max_badguys = 0 self.guys_killed = 0 self.levels = [{"img":"res/levels/level1.png", "badguys":2, "goal":6}, {"img":"res/levels/level2.png", "badguys":5, "goal":10}] self.cur_level = 0 self.load_level(0) self.menu = Menu() self.win = Win() self.die = Die()
from die import Die import pygal die = Die() results = [] for roll_num in range(100): results.append(die.roll()) print(results) frequencies = [] for value in range(1,die.num_slides+1): frequencies.append(results.count(value)) print(frequencies) hist = pygal.Bar() hist.title = "Results of rolling one D6 1.000 times" hist.x_labals = ['1','2','3','4','5','6'] hist.x_title = "Result" hist.y_title = "Frequency of result" hist.add("D6",frequencies) hist.render_to_file('die_visual.svg')
def roll_set(): dice = [] for x in range(1, 7): new_die = Die(x) dice.append(new_die) return dice
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create two D6 dice. die_1 = Die() die_2 = Die(10) # Make some rolls, and store the 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)) # Plotly doesn't accept results of range() function data = [Bar(x=x_values, y=frequencies)] x_axis_config = { 'title': 'Result', 'dtick': 1 } # Dtick:1 tels Plotly to label every tick mark since it begins to stop with more x values
class Player(object): def __init__(self): """Has a pair of dice and an empty rolls list.""" self._die1 = Die() self._die2 = Die() self._rolls = [] def __str__(self): """Returns the string rep of the history of rolls.""" result = "" for (v1, v2) in self._rolls: result = result + str((v1, v2)) + " " + \ str(v1 + v2) + "\n" return result def get_number_of_rolls(self): """Returns the number of the rolls in one game.""" return len(self._rolls) def play(self): """Plays a game, saves the rolls for that game, and returns True for a win and False for a loss.""" self._rolls = [] self._die1.roll() self._die2.roll() (v1, v2) = (self._die1.get_value(), self._die2.get_value()) self._rolls.append((v1, v2)) initial_sum = v1 + v2 if initial_sum in (2, 3, 12): return False elif initial_sum in (7, 11): return True while True: self._die1.roll() self._die2.roll() (v1, v2) = (self._die1.get_value(), self._die2.get_value()) self._rolls.append((v1, v2)) sum = v1 + v2 if sum == 7: return False elif sum == initial_sum: return True
def setUp(self): self.possible_values = ["John Snow", "Tyrion Lannister", "Brienne of Tarth", 1, 2] self.new_die = Die(*self.possible_values) print(self.shortDescription())
#Done by Carlos Amaral (21/07/2020) #Rolling two dice from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create two D6 Dice. die_1 = Die() die_2 = Die() #Make some rolls, and store the results in a list. results = [] for roll_num in range(1000): result = die_1.roll() + die_2.roll() #Roll the dice and calculate the sum of the two dice for each roll. results.append(result) #Analyse the results frequencies = [] max_result = die_1.num_sides + die_2.num_sides #largest possible result (12), is the sum of both dices and is stored at max_result. for value in range(2, max_result +1): #When analyse, count the no. of results for each value between 2(min) and maximum(12). 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)]
def __init__(self): self.die1 = Die() self.die2 = Die()
# Author: Bojan G. Kalicanin # Date: 24-Dec-2016 # 15-10. Practicing with Both Libraries: Try using matplotlib to make a # die-rolling visualization, and use Pygal to make the visualization for # a random walk. import matplotlib.pyplot as plt from die import Die # Create two D6 dice. die_1 = Die() die_2 = Die() # Make some rolls, and store results in a list. results = [] [results.append(die_1.roll() + die_2.roll()) for roll_num in range(1000)] # Analyze the results. frequencies = [] max_result = die_1.num_sides + die_2.num_sides [ frequencies.append(results.count(value)) for value in range(2, max_result + 1) ] x_values = [i for i in range(2, max_result + 1)] plt.scatter(x_values, frequencies, edgecolor='none', s=10) plt.title("Rolling two dice results.", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Result", fontsize=14)
import pygal from die import Die # Create two D6 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(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # print(frequencies) # Visualize the results. hist = pygal.Bar() hist.title = "Results of rolling two D6 1000 times." hist.x_labels = Die.x_labels(2, max_result)
import pygal from die import Die d6 = Die() # Make some rolls and store the results in a list. results = [d6.roll() for _ in range(1000)] # Analyze the results frequencies = [] for value in range(1, d6.num_sides + 1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results hist = pygal.Bar() hist.title = "Results of rolling one D6 1000 times." hist.x_labels = [str(x) for x in range(1, d6.num_sides + 1)] hist._x_title = "Result" hist.y_title = "Frequecy of Result" hist.add('D6', frequencies) hist.render_to_file('die_visual_.svg')
def __init__(self): """Has a pair of dice and an empty rolls list.""" self._die1 = Die() self._die2 = Die() self._rolls = []
class Player(object): def __init__(self): """Has a pair of dice and an empty rolls list.""" self._die1 = Die() self._die2 = Die() self._rolls = [] def __str__(self): """Returns a string representation of the list of rolls.""" result = "" for (v1, v2) in self._rolls: result = result + str((v1, v2)) + " " + str(v1 + v2) + "\n" return result def getNumberOfRolls(self): """Returns the number of the rolls.""" return len(self._rolls) def play(self): """Plays a game, saves the rolls for that game, and returns True for a win and False for a loss.""" self._rolls = [] self._die1.roll() self._die2.roll() (v1, v2) = (self._die1.getValue(), self._die2.getValue()) self._rolls.append((v1, v2)) initialSum = v1 + v2 if initialSum in (2, 3, 12): return False elif initialSum in (7, 11): return True while True: self._die1.roll() self._die2.roll() (v1, v2) = (self._die1.getValue(), self._die2.getValue()) self._rolls.append((v1, v2)) sum = v1 + v2 if sum == 7: return False elif sum == initialSum: return True
def setUp(self): self.possible_values = [1, 2, 3, "Dog", "Cat", "Hippo"] self.new_die = Die(self.possible_values)
# Implement the Die class. from die import Die import pygal # Create a six-sided die (also known as a D6). my_die = Die() # Make some rolls and store them in a list. my_rolls = [] rolls = input("How many times would you like to roll the die? ") for roll in range(1, int(rolls) + 1): my_rolls.append(my_die.roll_die()) # If we want to analyze the results, we can do this. frequencies = [] for value in range(1, my_die.sides + 1): frequency = my_rolls.count(value) frequencies.append(frequency) print(frequencies) # Make a histogram to visualize the results. hist = pygal.Bar() hist.title = "Results of rolling a D" + str(my_die.sides) + ", " hist.title += str(rolls) + " times." hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.x_title = "Result" hist.y_title = "Frequency of Result"
import pygal from die import Die # 投骰子生成结果 num_sides = 6 die_1 = Die(num_sides) die_2 = Die(num_sides) results = [die_1.roll() + die_2.roll() for i in range(10000)] # 统计每个点数出现的词数 frequencies = [results.count(value) for value in range(2, (num_sides * 2) + 1)] # 可视化统计结果(直方图) hist = pygal.Bar() hist.title = "Results of rolling one D6 10000 times." hist.x_labels = range(2, 13) hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add("D6+D6", frequencies) hist.render_to_file("die_visual.svg") print(frequencies)
import pygal from die import Die # Create three D6 dice. die_1 = Die() die_2 = Die() die_3 = Die() # Make some rolls, and store results in a list. results = [] for roll_num in range(50000): 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(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. hist = pygal.Bar() hist.title = "Results of rolling two D6 1000 times." hist.x_labels = [] current_label = 3 while current_label <= 18: hist.x_labels.append(current_label) current_label = current_label + 1
from die import Die import pygal """Create a D6""" die = Die() """Make some rolls, and store results in a list""" results = [] for roll_num in range(1000): result = die.roll() results.append(result) """Analyze the results""" frequencies = [] for value in range(1, die.num_sides + 1): frequency = results.count(value) frequencies.append(frequency) #print(frequencies) """Visualize the results.""" hist = pygal.Bar() hist.title = "Results of rolling on D6 1,000 times.""" hist.x_labels =['1', '2', '3', '4', '5', '6'] hist.x_title = "Result" hist.y_title = "Frquency of Result" hist.add('D6', frequencies) hist.render_to_file('die_visual.svg')
from pygal.style import Style red = Style(colors=('red', )) blue = Style(colors=('blue', )) gold = Style(colors=('gold', )) teal = Style(colors=('teal', )) turquoise = Style(colors=('turquoise', )) aquamarine = Style(colors=('aquamarine ', )) from die import Die from Jmodule import jfilename number_of_sides_1 = 6 number_of_sides_2 = 6 num_rolls = [100, 100] die_1 = Die(number_of_sides_1) die_2 = Die(number_of_sides_2) max_result = die_1.num_sides + die_2.num_sides #results = [ ( die_1.roll() + die_2.roll() ) for n in range(num_rolls[0])] #frequencies_1 = [ results.count(m) for m in range(1, max_result + 1 )] #norm_frequencies_1 = [ 100*frequency/sum(frequencies_1) for frequency in frequencies_1] results = [(die_1.roll() + die_2.roll()) for n in range(num_rolls[1])] frequencies_2 = [results.count(m) for m in range(1, max_result + 1)] #norm_frequencies_2 = [ 100*frequency/sum(frequencies_2) for frequency in frequencies_2] hist = pygal.Bar(style=blue) #hist.add("D%i + D%i" %(number_of_sides_1, number_of_sides_2), norm_frequencies)
from die import Die from plotly.graph_objs import Bar, Layout from plotly import offline # Create two D8s die_1 = Die() die_2 = Die() die_3 = Die() # Make some rolls, and store results in a list results = [die_1.roll() * die_2.roll() for roll_num in range(10_000)] # Analyse the results max_result = die_1.num_sides * die_2.num_sides frequencies = [results.count(value) for value in range(1, max_result + 1)] # Visualise 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 rolling two D6 10000 times and multiplying them together', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6^2.html')
# !/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = 'joedd' from die import Die import pygal # 将使用Python可视化包Pygal来生成可缩放的矢量图形文件 # 创建一个D6 die = Die(6) # 掷几次骰子,并将结果存储在一个列表中 # results = [] # for roll_num in range(1000): # result = die.roll() # results.append(result) # print(results) results = [die.roll() for roll_num in range(1000)] # 分析结果 # frequencies = [] # for value in range(1, die.num_sides+1): # frequency = results.count(value) # frequencies.append(frequency) frequencies = [results.count(value) for value in range(1, die.num_sides + 1)] print(frequencies) #对结果进行可视化 hist = pygal.Bar()
# A program for rolling two dice. from die import Die import pygal # Create two D6 dice. die_1 = Die() die_2 = Die() # Roll some times and store it in a list. results = [] rolls = input("How many times would you like to roll the die? ") for roll in range(1, int(rolls) + 1): results.append(die_1.roll_die() + die_2.roll_die()) # Analyze the results. frequencies = [] max_result = die_1.sides + die_2.sides for value in range(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. hist = pygal.Bar() hist.title = "Results of rolling a D" + str(die_1.sides) + " and a D" hist.title += str(die_2.sides) + " die " + rolls + " times." hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] hist.y_title = "Result" hist.x_title = "Frequency of Result"
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create two D6 dice. die_1 = Die() die_2 = Die() # Make some rolls, and store results in a list (multiplication). 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': 'Results', 'dtick': 1} y_axis_config = {'title': 'Frequency of Result'} my_layout = Layout(title='Results of multiplying two D6 dice (1000 rolls)', xaxis=x_axis_config, yaxis=y_axis_config)
import pygal from die import Die # 创建一个 D6 die1 = Die() die2 = Die(10) # 投掷几次骰子并将结果存储在列表当中 results = [] for roll_num in range(1000): result = die1.roll() + die2.roll() results.append(result) # print(results) frequencies = [] max_result = die1.num_sides + die2.num_sides for value in range(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # print(frequencies) # 对结果进行可视化 hist = pygal.Bar() hist.title = "Results of rolling two D6 1000 times." # hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', # '13', '14', '15', '16'] hist.x_labels = range(2, max_result + 1) hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6', frequencies)
import matplotlib.pyplot as plt from die import Die values = [] die_1 = Die() die_2 = Die(8) nums = [] for a in range(1000): value = die_1.roll() + die_2.roll() values.append(value) for frequncy in range(2, die_1.num_sides + die_2.num_sides + 1): num = values.count(frequncy) nums.append(num) print(nums) x = list(range(2, die_1.num_sides + die_2.num_sides + 1)) plt.scatter(x, nums, c=nums, cmap=plt.cm.Blues, edgecolors='none', s=50) plt.title('frequncey of two dice', fontsize=15) plt.xlabel('value of two dice', fontsize=15) plt.ylabel('frequncy') plt.tick_params(axis='both', labelsize=20) plt.show()
import pygal from die import Die # 创建一个D6骰子 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) # 对结果进行可视化 hist = pygal.Bar() hist.title = 'Results of rolling one D6 1000 times.' hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.x_title = 'Result' hist.y_title = 'Frequency of Result' hist.add('D6', frequencies) hist.render_to_file('die_visual.svg')
def __init__(self, players_num, games_num): self.players = [Player(num) for num in range(1, players_num + 1)] self.games = [Game(self.players, Die()) for num in range(0, games_num)] self.CLI = True self.game_num = 0
from die import Die import pygal die_1 = Die() die_2 = Die() die_3 = Die() results = [ die_1.roll() + die_2.roll() + die_3.roll() for roll_num in range(1000) ] # for roll_num in range(1000): # result=die_1.roll()+die_2.roll() # results.append(result) max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides frequencies = [results.count(value) for value in range(3, max_result + 1)] # for value in range(2,max_result+1): # frequency=results.count(value) # frequencies.append(frequency) #对结果进行可视化 hist = pygal.Bar() hist.title = 'Results of rolling three D6 1000 times' hist.x_labels = [str(result) for result in range(3, max_result + 1)] hist.x_title = 'Result' hist.y_title = 'Frequency of Result' hist.add('D6+D6+D6', frequencies) hist.render_to_file('158_visual.svg')
from die import Die import pygal die1 = Die() die2 = Die() results = [] for roll_num in range(1000): result1 = die1.roll() result2 = die2.roll() results.append(result1 + result2) frequencies = [] for value in range(2, die1.num_sides + die2.num_sides + 1): frequency = results.count(value) frequencies.append(frequency) ''' count = 0 for i in range(len(frequencies)): count += frequencies[i] print(count) ''' hist = pygal.Bar() hist.title = "Results of rolling two d6 1000 times." #hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.x_labels =[str(i) for i in range(2, 13)] hist.x_title = "Result" hist.y_title = "Frequency of result"
#die_visual.py import pygal from die import Die # Create two D6 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) results = [ die_1.roll() + die_2.roll() for roll_num in range(1000) ] # Analyze the results. #frequencies = [] max_results = die_1.num_sides + die_2.num_sides #for value in range(2, max_results+1): # frequency = results.count(value) # frequencies.append(frequency) frequencies = [ results.count(value) for value in range(2, max_results+1) ] #print(results) print(frequencies) # Visualize the results. # A histogram is a bar chart showing how often certain results occur. hist = pygal.Bar() hist.title = "Results of rolling two D6 1000 times." #hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
"""Display the result of die rolls in this script.""" import pygal from die import Die # Create a two D6 die. die1 = Die() die2 = Die() # die3 = Die() # Make some rolls, and store results in a list. results = [] for roll_num in range(10000): result = die1.roll() * die2.roll() results.append(result) # Analyze the results. frequencies = [] min1 = ((die1.num_sides + 1) - die1.num_sides) min2 = ((die2.num_sides + 1) - die2.num_sides) # min3 = ((die3.num_sides + 1) - die3.num_sides) min_result = min1 + min2 max_result = die1.num_sides * die2.num_sides for value in range(min_result, max_result+1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. hist = pygal.Bar()
from die import Die import pygal # 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(50000): result = die_1.roll() + die_2.roll() results.append(result) # Analyze the results. frequencies = []
import pygal from die import Die # Create a D6 die = Die() # Make some rolls, and store results in a list. results = [] for roll_num in range(1000): result = die.roll() results.append(result) # Analyze the results. frequencies = [] for value in range(1, die.num_sides + 1): frequency = results.count(value) frequencies.append(frequency) # print(frequencies) # Visualize the results. hist = pygal.Bar() hist.title = "Results of rolling one D6 1000 times." hist.x_labels = Die.x_labels(1, 6) hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6', frequencies)
import pygal from die import Die die1 = Die() die2 = Die(10) results = [] for roll_num in range(5000): result = die1.roll() + die2.roll() results.append(result) frequencies = [] max_result = die1.num_sides + die2.num_sides for value in range(2, max_result+1): frequency = results.count(value) frequencies.append(frequency) # create a histogram hist = pygal.Bar() # histogram details/styling hist.title = "Results of rolling a D6 and a D10 50,000 times." hist.x_labels = list(range(2, max_result+1)) hist.x_title = "Result" hist.y_title = "Frequency of Result" # add a series of values to the chart hist.add('D6 + D10', frequencies) # render the chart to a SVG file hist.render_to_file('diff_die_visual.svg')
import matplotlib.pyplot as plt from die import Die count = 100 dies = [Die(), Die()] num = 1 def roll_all(dies): """所有骰子掷一次相加结果""" result = 1 for die in dies: result *= die.roll() return result def max_result(dies): """最大值""" result = 1 for die in dies: result *= die.num_sides return result #掷几次骰子,将结果存放在一个列表中 results = [roll_all(dies) for n in range(count)] frequencies = [results.count(v) for v in range(1, len(results) + 1)] print(len(results)) print(len(frequencies))
parser = argparse.ArgumentParser('Simple Dice Roller') parser.add_argument('--number_of_dice', '-n', dest='num_dice', type=int, default=1, help='Number of dice to roll; default 1') parser.add_argument('--sides', '-s', dest='sides', type=int, default=6, help='Sides of the die; default 6') args = parser.parse_args() print('Rolling {}d{}'.format(args.num_dice, args.sides)) results = [] for n in range(args.num_dice): my_die = Die(args.sides) result = my_die.roll() results.append(result) for result in results: print('Rolled: {}'.format(result)) total = sum(results) print('Sum: {}'.format(total))
pg.font.init() clock = pg.time.Clock() screen = pg.display.set_mode((rd_settings.scrWidth, rd_settings.scrHeight)) pg.display.set_caption("Romanian Dice Simulator") putin = pg.image.load('images/putin_8bit_final.png') blankDie = pg.image.load('images/blankDie.png').convert() eightBit = pg.font.Font('images/8bit.ttf', 128) chatBit = pg.font.Font('images/8bit.ttf', 64) start_button = Buttons(rd_settings, screen, "Start") die_1 = Die() ############################################################################### # Main Game Loop ############################################################################### while continueGame: gf.checkForEvents(rd_settings, screen, start_button) screen.fill(rd_settings.bg_color) #This draws the intro screen until the user hovers over the start if rd_settings.start_clicked == False: gf.introPutin(screen, putin, blankDie, eightBit, rd_settings)
import pygal from die import Die # 创建一个D6 die_1 = Die() die_2 = Die() # 掷几次骰子, 并将结果保存在列表中 results = [die_1.roll() * die_2.roll() for i in range(50000)] # for roll_num in range(1000): # result = die_1.roll() + die_2.roll() # results.append(result) # 分析结果 max_result = die_1.num_sides * die_2.num_sides frequencies = [results.count(i) for i in range(2, max_result + 1)] # for i in range(2, max_result+1): # frequency = results.count(i) # frequencies.append(frequency) # 对结果进行可视化 hist = pygal.Bar() hist.title = "Results of rolling {} D{} dice {} times".format('two', 6, 50000) hist.x_labels = map(str, range(2, max_result + 1)) hist.x_title = "Result" hist._y_title = "Frequency of Result" hist.add('D6 * D6', frequencies) hist.render_to_file('dice_mul_visual.svg')
#die_visual.py import pygal from die import Die # Create a D6. die = Die() # Make some rolls, and store results in a list. #results = [] #for roll_num in range(1000): # result = die.roll() # results.append(result) results=[ die.roll() for result in range(1000) ] # Analyze the results. #frequencies = [] #for value in range(1, die.num_sides+1): # frequency = results.count(value) # frequencies.append(frequency) frequencies = [ results.count(value) for value in range(1, die.num_sides+1) ] #print(results) print(frequencies) # Visualize the results. # A histogram is a bar chart showing how often certain results occur. hist = pygal.Bar() hist.title = "Results of rolling one D6 1000 times." #hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.x_labels = [ num for num in range(1, 7) ] hist.x_title = "Result" hist.y_title = "Frequency of Result"
# !/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = 'joedd' from die import Die import pygal # 将使用Python可视化包Pygal来生成可缩放的矢量图形文件 # 创建两个D6 die_1 = Die(6) die_2 = Die(6) # 掷几次骰子,并将结果存储在一个列表中 # results = [] # for roll_num in range(1000): # result = die_1.roll() + die_2.roll() # results.append(result) # print(results) #列表解析:自动生成这种列表的循环 results = [die_1.roll() + die_2.roll() for roll_num in range(1000)] # 分析结果 # 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) frequencies = [results.count(value) for value in range(2, max_result + 1)]
def __init__(self): Die.__init__(self, 6)
import pygal from die import Die MAX_R = 50000 # SNUM = 8 # Create three D6 dices die1 = Die() die2 = Die() die3 = Die() # Make some rolls, and store results in a list. # list comprehension added results = [die1.roll() + die2.roll() + die3.roll() for r in range(MAX_R)] # Analyze the results. max_result = die1.num_sides + die2.num_sides + die3.num_sides # list comprehension added frequencies = [results.count(value) for value in range(3, max_result + 1)] # Visualize the results. hist = pygal.Bar() hist.title = "Results of rolling three D6 dice %s times." % MAX_R # list comprehension added hist.x_labels = [str(n) for n in range(3, max_result + 1)] hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6 + D6 + D6', frequencies) hist.render_to_file('./dices_visual12.svg')
import pygal from die 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(50000): 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) # print(frequencies) # Visualize the results. hist = pygal.Bar() hist.title = "Results of rolling a D6 and a D10 50,000 times." hist.x_labels = Die.x_labels(2, max_result)
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create a die with 6 sides = D6 die_1 = Die() # instace of Die class die_2 = Die(10) # Make some rolls, and store results in a list. results = [] # A list of results for roll_num in range(50_000): result = die_1.roll() + die_2.roll() results.append(result) # Analize 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) # .count return number of ocurrences of a value frequencies.append(frequency) # Visualize the results in a Bar Chart (GRAFICO DE BARRA) # Generating bar chart x_values = list( range(2, max_result + 1)) # Plotly doesn't accept range() so I covert the range to a list data = [Bar(x=x_values, y=frequencies)] # Configurating layout. Especifically the title and the axises.
class LD26Main: def __init__(self, width=800,height=600): pygame.init() self.width = width self.height = height self.screen = pygame.display.set_mode((self.width, self.height)) self.state = "menu" pygame.display.set_caption("Shoot Guys") def load_sprites(self): self.player_group = CameraSpriteGroup() self.player_bullet_group = CameraSpriteGroup() self.player_max_hp = 20 self.player_healthbar = HealthBar(self.player_max_hp, self.player_max_hp, "res/player_healthbar.png", (128, 16)) self.player_healthbar.rect.x = -55 self.player_healthbar.rect.y = 10 self.player_hb_group = CameraSpriteGroup() self.player_hb_group.add(self.player_healthbar) self.enemy_group = CameraSpriteGroup() self.enemy_bullet_group = CameraSpriteGroup() self.health_bar_sprites = CameraSpriteGroup() self.max_badguys = 0 self.guys_killed = 0 self.levels = [{"img":"res/levels/level1.png", "badguys":2, "goal":6}, {"img":"res/levels/level2.png", "badguys":5, "goal":10}] self.cur_level = 0 self.load_level(0) self.menu = Menu() self.win = Win() self.die = Die() def load_level(self, levelnum): if levelnum >= len(self.levels): self.state = "win" else: leveldict = self.levels[levelnum] self.player = Player((self.width, self.height)) self.player_group.add(self.player) self.level = Level((self.width, self.height), leveldict["img"]) self.bdrop1 = Backdrop(self.level.dims, 1) self.bdrop2 = Backdrop(self.level.dims, 2) self.max_badguys = leveldict["badguys"] self.guys_killed = 0 self.kill_goal = leveldict["goal"] self.player_healthbar.set_hp(self.player_max_hp) def go(self): self.load_sprites() self.clock = pygame.time.Clock() while 1: self.clock.tick(60) self.screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == K_ESCAPE: if self.state == "game": self.state = "menu" else: sys.exit() elif event.key == K_RETURN: if self.state == "menu": self.state = "game" elif self.state == "win" or self.state == "die": self.load_level(0) self.state = "game" if self.state == "menu": self.do_menu() elif self.state == "game": self.do_main_game() elif self.state == "win": self.do_win() else: self.do_die() pygame.display.flip() def do_die(self): self.die.update() self.die.draw(self.screen) def do_win(self): self.win.update() self.win.draw(self.screen) def do_menu(self): self.menu.update() self.menu.draw(self.screen) def do_main_game(self): if self.guys_killed > self.kill_goal: self.cur_level += 1 self.player.kill() self.load_level(self.cur_level) offset = (self.width / 2) - self.player.rect.x, (self.height / 1.5) - self.player.rect.y while len(self.enemy_group) < self.max_badguys: xpos = random.randint(0, self.width-64) - offset[0] ypos = random.randint(0, self.height-64) - offset[1] h = HealthBar(4, 4, "res/healthbar.png", (32, 4)) b = BadGuy((self.width, self.height), 4, h, (xpos, ypos)) self.health_bar_sprites.add(h) self.enemy_group.add(b) keys = pygame.key.get_pressed() if keys[pygame.K_d]: self.player.move(pygame.K_d) elif keys[pygame.K_a]: self.player.move(pygame.K_a) if keys[pygame.K_SPACE] or keys[pygame.K_UP]: self.player.move(pygame.K_SPACE) if keys[pygame.K_RIGHT]: if self.player.can_shoot(): bullet = Bullet("right", self.level.size, self.player.rect) self.player_bullet_group.add(bullet) self.player.shoot(pygame.K_RIGHT) elif keys[pygame.K_LEFT]: if self.player.can_shoot(): bullet = Bullet("left", self.level.size, self.player.rect) self.player_bullet_group.add(bullet) self.player.shoot(pygame.K_LEFT) for guy in self.enemy_group: if guy.is_shooting(): bullet = Bullet(guy.shoot_dir, self.level.size, guy.rect) self.enemy_bullet_group.add(bullet) # remove bullets that hit terrain pygame.sprite.groupcollide(self.enemy_bullet_group, self.level, True, False) pygame.sprite.groupcollide(self.player_bullet_group, self.level, True, False) damaged_guys = pygame.sprite.groupcollide(self.enemy_group, self.player_bullet_group, False, True) for d in damaged_guys: d.damage(1) if d.hp == 0: self.guys_killed += 1 d.kill() if pygame.sprite.groupcollide(self.player_group, self.enemy_bullet_group, False, True): self.player_healthbar.set_hp(self.player_healthbar.cur_hp-1) if self.player_healthbar.cur_hp <= 0: self.state = "die" self.player.kill() guys = self.enemy_group.sprites() + self.player_group.sprites() for guy in guys: if guy.rect.top > self.level.bottom(): guy.kill() if isinstance(guy, Player): self.state = "die" else: guy.collide_with(self.level.collisions_for(guy)) self.bdrop2.update() self.bdrop2.draw(self.screen, (offset[0]/4, offset[1]/4)) self.bdrop1.update() self.bdrop1.draw(self.screen, (offset[0]/2, offset[1]/2)) self.player_bullet_group.update() self.player_bullet_group.draw(self.screen, offset) self.enemy_bullet_group.update() self.enemy_bullet_group.draw(self.screen, offset) self.enemy_group.update(self.player.rect) self.enemy_group.draw(self.screen, offset) self.player_group.update() self.player_group.draw(self.screen, offset) self.health_bar_sprites.update() self.health_bar_sprites.draw(self.screen, offset) self.level.update() self.level.draw(self.screen, offset) self.player_hb_group.update() self.player_hb_group.draw(self.screen)
@Time : 2019/04/06 21:56:06 @Author : leacoder @Version : 1.0 @Contact : [email protected] @License : @Desc : 模拟掷骰子并柱状图显示点数出现次数 ''' # here put the import lib from die import Die import pygal # 创建两个D6 die_1 = Die(8) die_2 = Die(8) # 掷几次骰子, 并将结果存储在一个列表中 results = [] for roll_num in range(50000): result = die_1.roll() + die_2.roll() results.append(result) # 分析结果 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)
from die import Die import pygal die_1 = Die() die_2 = Die() results = [] for roll_num in range(100): results.append(die_1.roll() + die_2.roll()) frequencies = [] max_result = die_1.num_slides + die_2.num_slides for value in range(2,die_1.num_slides+ die_2.num_slides): frequencies.append(results.count(value)) hist = pygal.Bar() hist.title = "Results of rolling two D6 1.000 times" hist.x_labels = ['1','2','3','4','5','6','7','8','9','10','11','12'] hist.x_title = "Result" hist.y_title = "Frequency of result" hist.add("D6 + D6",frequencies) hist.render_to_file('dice_visual.svg')
max_result = 1 for die in dices: max_result *= die.num_sides return max_result def get_roll_result(dices): """Get roll results.""" result = 1 for die in dices: result *= die.roll() return result # Create two D6s. dices = [Die(), Die()] max_result = get_max_result(dices) # Make some rolls, and store results in a list. results = [] for roll_num in range(50000): result = get_roll_result(dices) results.append(result) # Analyze the results. frequencies = [] for value in range(1, max_result + 1): frequency = results.count(value) frequencies.append(frequency)
class AngryDice: """ A class that represents the game Angry dice """ # Class constants, that might make life easier for scope change. DICE_FACE_VALUES = [1, 2, "ANGRY", 4, 5, 6] STAGE = {1: [1, 2], 2: ['ANGRY', 4], 3: [5, 6]} WINNER_STRING = "You've won! Calm down!" def __init__(self, start=True): """ input start:boolean defaults to True. If set to false the game will not start. """ self.dice_a = Die(*self.DICE_FACE_VALUES) self.dice_b = Die(*self.DICE_FACE_VALUES) self.current_stage = 1 self.current_dice_a_value = "" self.current_dice_b_value = "" self.game_over = False if start: self.game_controller() def game_instructions(self): """ need to give user instructions need to prompt user to start """ instructions = \ ("Welcome to Angry Dice! Roll the two dice until you get thru the 3 Stages!\n" "Stage 1 you need to roll 1 & 2\n" "Stage 2 you need to roll ANGRY & 4\n" "Stage 3 you need to roll 5 & 6\n" "You can lock a die needed for your current stage\n" "and just roll the other one, but beware!\n" "If you ever get 2 ANGRY's at once, you have to restart to Stage 1!\n" "Also, you can never lock a 6! That's cheating!\n\n" "To roll the dice, simply input the name of the die you want to roll. Their names are a and b.\n") print(instructions) begin = True # we wait for exit or enter to be pressed. while begin: start = input("Press ENTER to start!") if start == '': begin = False elif start == 'exit': begin = False def parse_input(self): """ Cleans input string, so we have upto two single die to use. """ dice_to_roll = [] input_string = input("Roll dice:") if "exit" in input_string: dice_to_roll.append("exit") self.game_over = True return dice_to_roll if "a" in input_string: dice_to_roll.append("a") if "b" in input_string: dice_to_roll.append("b") return dice_to_roll def get_roll(self): """ need to ask user what dice they want to roll """ still_rolling = True while still_rolling: dice_to_roll = self.parse_input() # we leave this is a string, for exit condition. if "exit" in dice_to_roll: # user typed exit, we throw game_over self.game_over = True return dice_to_roll elif len(dice_to_roll) != 0 and \ "a" in dice_to_roll or "b" in dice_to_roll: still_rolling = False return dice_to_roll def print_roll(self, cheater): """ input: boolean, if true, we print the cheater notice prints current roll, output should match: You rolled: a = [ 5 ] b = [ ANGRY ] You are in Stage # """ if cheater: cheater = ("You're cheating! You cannot lock a 6!" "You cannot win until you reroll it!\n") else: cheater = "" roll_text = "You rolled: \n" + " a = [ {} ]\n" + " b = [ {} ]" roll_turn = "\nYou are in Stage {}" statement = cheater + roll_text + roll_turn print(statement.format(self.current_dice_a_value, self.current_dice_b_value, self.current_stage)) def is_cheat(self, to_roll): """ input a list of dice to roll (this should really be 1.) return true if user is holding on a 6, or attempting to hold a dice that's not part of current_stage exit criteria """ if type(to_roll) == list: # Just in case we get more that 1 item in our list for roll in to_roll: # check for holding 6 on a "a" dice if self.current_dice_a_value == 6 and roll == "b": return True # check for holding 6 on a "b" dice elif self.current_dice_b_value == 6 and roll == "a": return True # check for holding any value which is # not part of next stage criteria elif self.current_dice_a_value not in \ self.STAGE[self.current_stage] and roll == "b": return True # check for holding any value which is # not part of next stage criteria elif self.current_dice_b_value not in \ self.STAGE[self.current_stage] and roll == "a": return True # Hoooray we're not a cheat else: return False else: raise TypeError def check_roll(self): """ checks current roll values first checks if we've reached angry status if we've met all conditions for the stage we move to the next stage """ # we cast to sets for easy comparisons current_values = {self.current_dice_a_value, self.current_dice_b_value} stage_complete_values = set(self.STAGE[self.current_stage]) # if the two sets are equivalent, we get are returned a list of len 0 # thusly we've met stage exit criteria. if len(stage_complete_values ^ current_values) == 0: self.current_stage += 1 return self.current_stage else: return self.current_stage def check_angry(self): """ Checks if user has reached Angry! Resets user to stage 1 returns True if they've reached angry status """ if self.current_dice_a_value == "ANGRY" and \ self.current_dice_b_value == "ANGRY": self.current_stage = 1 print("WOW, you're ANGRY!\n" + "Time to go back to Stage 1!") return True else: return False def game_controller(self): """ Game controller handles the flow the game. This is equivalent to main() """ self.game_instructions() while not self.game_over: to_roll = self.get_roll() attempted_cheat = False # check for holding on a non value allowed for stage, force roll if len(to_roll) != 2 and self.is_cheat(to_roll): attempted_cheat = True to_roll = ["a", "b"] for dice in to_roll: if dice == "a": self.current_dice_a_value = self.dice_a.roll() elif dice == "b": self.current_dice_b_value = self.dice_b.roll() if not self.check_angry(): self.check_roll() if self.current_stage == 4: # we have a winner because we've incremented # the current stage beyond the game print(self.WINNER_STRING) self.game_over = True else: self.print_roll(attempted_cheat)
class Game: def __init__(self): self.board = Board() self.move_manager = MoveManager(self.board) self.players = [PlayerMoveFirstPawn(p, self.board) for p in Players] self.current = Players.black self.die = Die() self._retry_counter = 0 # save finishers self.finishers = [] self.event_ready = threading.Event() self.event_finished = threading.Event() # Look to serialize canvas drawings self.lock = threading.Lock() # Thread for tk mainloop, this runs until the program gets exited self.tk_thread = threading.Thread(target=self._tk_mainloop) def start_tk_visualization(self): self.tk_thread.start() # Wait for completion of canvas initialization self.event_ready.wait() def next_move(self): # while True: # number = self.die.roll() # self.players[self.current].move(number) # if number is not 6: # break # print(self.current, "rolls again!") number = self.die.roll() return self._execute_move(number) def _execute_move(self, number): moves = self.move_manager.get_valid_moves(self.current, number) if not self._let_player_execute_move(moves): return False # roll again when having max number of points if number == MAX_DICE_NUMBER_OF_POINTS: return True if self._retry_counter == 0: self._go_to_next_player() return True def _let_player_execute_move(self, moves): move = self.players[self.current].choose_move(moves) if move is not None: self._retry_counter = 0 self.move_manager.perform_move(self.current, move) if self.move_manager.check_if_finished(self.current): assert self.current not in self.finishers self.finishers.append(self.current) if len(self.finishers) == len(Players): return False else: if (self.move_manager.board.can_player_only_emerge(self.current) and self._retry_counter < MAX_THROWS-1): self._retry_counter += 1 else: self._retry_counter = 0 return True def update_canvas(self): tasks = [] # iterate over every pawn for player in Players: for pawn in range(PAWN_COUNT): tasks.append({'type': "move", 'data': (player, pawn, self.board.pawns[player][pawn][0], self.board.pawns[player][pawn][2])}) # update every pawn on canvas list(map(self.board_drawer.job_queue.put_nowait, tasks)) def _go_to_next_player(self): assert len(self.finishers) < len(Players) while True: self.current = Players.next(self.current) if self.current not in self.finishers: break def _tk_mainloop(self): # print board on tk canvas self.board_drawer = BoardDrawer() # set ready event for main thread to continue initialization self.event_ready.set() # call mainloop() self.board_drawer.show_board() self.event_finished.wait() # delete tkinter canvas explicitly in THIS thread del self.board_drawer