def main(): theDie = Die() go = raw_input("Roll the die? <enter> for yes, no for stopping: ") theDie.roll() while go == "": theDie.roll() print theDie.getValue() print "die = " + str(theDie) go = raw_input("Roll the die? <enter> for yes, no for stopping: ")
class Yahtzee: def __init__(self): self.chosen = () self.d1 = Die(6) self.d2 = Die(6) self.d3 = Die(6) self.d4 = Die(6) self.d5 = Die(6) self.cup_of_dice = [self.d1, self.d2, self.d3, self.d4, self.d5] def score(self, numbers): return 50 # figure out if numbers which is a list of 5 numbers between 1 and 6 # if they are all the same and return 50 if that is the case # if not, return the sum of all the numbers def roll(self): if len(self.chosen) == 0: rolled_dice = [self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll()] return rolled_dice else: for v in self.chosen: self.cup_of_dice[v].active = False rolled_dice = [self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll()] return rolled_dice def choose(self, choice): self.chosen = choice
def main(): #make a die obj d = Die() print d.roll() b = Board() print b.toString() s1 = Square(57, "Snake", 40) s2 = Square(26, "Ladder", 84) s3 = Square(2, "Plain", 2) print s1.toString() print s2.toString() print s3.toString()
class Roller: """A class for doing various rolling operations related to Dungeons and dragons""" def __init__(self): self.d20 = Die(20) self.d12 = Die(12) self.d8 = Die(8) self.d6 = Die(6) self.d4 = Die(4) def advantage(self): roll1 = self.d20.roll() roll2 = self.d20.roll() return max(roll1, roll2) def disadvantage(self): roll1 = self.d20.roll() roll2 = self.d20.roll() return min(roll1, roll2) def advdis(self): dis1 = self.disadvantage() dis2 = self.disadvantage() return max(dis1, dis2) def disadv(self): adv1 = self.advantage() adv2 = self.advantage() return min(adv1, adv2) def advdisadv(self): disadv1 = self.disadv() disadv2 = self.disadv() return max(disadv1, disadv2) def disdisadv(self): disadv1 = self.disadv() disadv2 = self.disadv() return min(disadv1, disadv2) def advadvdis(self): advdis1 = self.advdis() advdis2 = self.advdis() return max(advdis1, advdis2) def disadvdis(self): advdis1 = self.advdis() advdis2 = self.advdis() return min(advdis1, advdis2)
def set_possible_damage(self): total = 0 # print(self.weapon_obj.effect_obj.items()) for key, value in self.weapon_obj.damage_dict.items(): if value[0] == 1 and self.versatile_use_2handed is True: d = Die(ctx=self.ctx, sides=self.weapon_obj.versatile_2hnd_die) self.die_used = self.weapon_obj.versatile_2hnd_die self.rolls_used = self.weapon_obj.versatile_2hnd_mod total += d.roll(rolls=self.weapon_obj.versatile_2hnd_mod) else: d = Die(ctx=self.ctx, sides=value[2]) total += d.roll(rolls=value[1]) self.die_used = value[2] self.rolls_used = value[1] return total
def get_alignment(self, db): """ Preferred racial alignment is based on a percentage. So, generate a random percentage and pick the alignment that percentage belongs in. """ d = Die(ctx=self.ctx, sides=100) rnd_pct = d.roll() sql = (f"select count(alignment) from dnd_5e.v_alignment_preference " f"where race = '{self.race}';") cnt_result = db.query(sql) if cnt_result[0][0] > 0: use_race = self.race else: use_race = self.subrace_of sql = (f"select count(alignment) from dnd_5e.v_alignment_preference " f"where race = '{use_race}';") cnt_result = db.query(sql) if cnt_result[0][0] > 0: sql = (f"select b.abbreviation, b.value as alignment " f"from dnd_5e.v_alignment_preference as a " f"join lu_alignment as b on a.alignment = b.abbreviation " f"where race = '{use_race}' " f"and lowerbound < {rnd_pct} and upperbound >= {rnd_pct};") alignment_results = db.query(sql) return { "abbreviation": alignment_results[0][0], "alignment": alignment_results[0][1] }
class Yahtzee(): def __init__(self): self.chosen = () self.d1 = Die(6) self.d2 = Die(6) self.d3 = Die(6) self.d4 = Die(6) self.d5 = Die(6) self.cup_of_dice = [self.d1, self.d2, self.d3, self.d4, self.d5] self.choices = {"Yahtzee": False, "Chance": False, "Large Straight": False, "Small Straight": False, "Ones": False, "Twos": False, "Threes": False, "Fours": False, "Fives": False, "Sixes":False} def scores(self, numbers): d = {} if (self.choose("Yahtzee", numbers)): d["Yahtzee"]=50 return d if (self.choose("Ones", numbers)): d["Ones"]=5 return d def score(self, numbers): a = numbers.count(numbers[0]) if a == 5: return 50 else: return numbers[0] + numbers[1] + numbers[2] + numbers[3] + numbers[4] def roll(self): if len(self.chosen) == 0: rolled_dice = [self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll()] return rolled_dice else: for v in self.chosen: self.cup_of_dice[v].active = False rolled_dice = [self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll()] return rolled_dice def select(self, choice): self.chosen = choice def choose(self, key, myroll): if key == "Yahtzee": if myroll.count(myroll[0]) != 5: return False if myroll.count(myroll[0]) == 5: if self.choices[key] == True: return False else: self.choices[key] = True return True else: if self.choices[key] == True: return False else: self.choices[key] = True return True
def test_d8_droplowest(): ctx = Ctx(app_username='******') d = Die(ctx=ctx, sides=8, debug_ind=True) r = d.roll(rolls=2, droplowest=True) details = d.get_details()[-1] assert(len(details.base_roll) == 2) assert(details.die_total_used == r) assert(8 >= r >= 1)
def roll_attack(self): d = Die(ctx=self.ctx, sides=20) if self.vantage == 'Advantage': r = d.roll_with_advantage() elif self.vantage == 'Disadvantage': r = d.roll_with_disadvantage() else: r = d.roll() return r
def _populate(self): """ Populate a candidate array of Ability Scores """ # standard = [15, 14, 13, 12, 10, 8] # point_buy_even = [13, 13, 13, 12, 12, 12] # point_buy_one_max = [15, 12, 12, 12, 11, 11] # point_buy_two_max = [15, 15, 11, 10, 10, 10] # point_buy_three_max = [15, 15, 15, 8, 8, 8] if self.array_type == "Predefined": self.candidate_array = self.raw_array elif self.array_type == "standard": self.candidate_array = self.const_array_standard elif self.array_type == "point_buy_even": self.candidate_array = self.const_array_point_buy_even elif self.array_type == "point_buy_one_max": self.candidate_array = self.const_array_point_buy_one_max elif self.array_type == "point_buy_two_max": self.candidate_array = self.const_array_point_buy_two_max elif self.array_type == "point_buy_three_max": self.candidate_array = self.const_array_point_buy_three_max else: d = Die(ctx=self.ctx, sides=6) for i in range(0, 6): if self.array_type == "strict": pr = d.roll(rolls=3, droplowest=False) else: pr = d.roll(rolls=4, droplowest=True) self.candidate_array.append(pr) # set the raw_array to whatever we started with for candidate values self.raw_array = self.candidate_array[:] # self.class_eval[-1]["raw_array"] = self.raw_array[:] jdict = {"raw_array": self.raw_array[:]} self.ctx.crumbs[-1].add_audit(json_dict=jdict) self.set_ability_array()
class Game: def __init__(self): print(" -- Welcome to die game called 'oczko'! -- ") self.__die = Die(6) self.__playerScore = 0 self.__computerScore = 0 self.__on = True def start(self): # Game loop while self.__on: self.__turn() self.__show_score() print("You win." if self.__playerScore > self.__computerScore else "You've lost." if self.__playerScore < self. __computerScore else "It's draw.") def __turn(self): print("\nDo you want to roll a die? (y/n)") play_more = input() for throw in range(4): self.__die.roll() if throw <= 1: self.__computerScore += self.__die.get_value() else: print(f"You roll {self.__die.get_value()}.") self.__playerScore += self.__die.get_value() if play_more == 'n' or self.__playerScore >= 21: self.__on = False def __show_score(self): if not self.__on: print("\n------------ Summary -------------\n") print(f"Computer score is {self.__computerScore} points.") print(f"Your score is {self.__playerScore} points.")
def set_possible_effect(self): # possible_effect = {"effect_type": {"effect_category": , "possible_amount": , # "effect_modifier": , "die_used": , "rolls_used": ,}} self.possible_effect = {} for effect in self.effect_obj.keys(): t_obj = self.effect_obj[effect] d = Die(ctx=self.ctx, sides=t_obj['effect_die']) tmp_rec = { "effect_category": t_obj['effect_category'], "possible_amount": d.roll(rolls=t_obj['effect_modifier']), "die_used": t_obj['effect_die'], "rolls_used": t_obj['effect_modifier'] } self.possible_effect[effect] = tmp_rec
def game(): '''decathlon_400_meters() -> int plays a solitare version of Reiner Knizia's 400 Meters returns final score''' # initializes rerolls, score, and dice score = 0 rerolls = 5 d1 = Die(6, [1, 2, 3, 4, 5, -6]) d2 = Die(6, [1, 2, 3, 4, 5, -6]) # play 4 rounds for gameround in range(1, 5): print("Your total score so far is " + str(score)) print("Round " + str(gameround) + " -- you have " + \ str(rerolls) + " rerolls left.") while True: # roll the dice input("Press enter to roll.") d1.roll() d2.roll() roundscore = d1.getTop() + d2.getTop() print("You rolled " + str(d1.getTop()) + " and " + \ str(d2.getTop()) + " for a total of " + str(roundscore)) # if the player has no rerolls, they're stuck with this if rerolls == 0: print("You're out of rerolls so you have to keep this.") break # see if they want to reroll response = 'x' while response.lower() not in ['y', 'n']: response = input("Do you want to reroll (y/n)? ") if response.lower() == 'n': break # keeping this roll, move on the the next roll # they're using a reroll rerolls -= 1 print("OK, you have " + str(rerolls) + " rerolls left.") score += roundscore # update the score return score
def roll_die(): global dice_roll sides = int(request.form['sides']) quantity = int(request.form['quantity']) title = 'Results:' die = Die(sides) results = [] for roll_num in range(quantity): result = die.roll() results.append(result) return render_template('rollresults.html', the_title=title, the_results=results)
class Yahtzee(): def __init__(self): self.chosen = () self.d1 = Die(6) self.d2 = Die(6) self.d3 = Die(6) self.d4 = Die(6) self.d5 = Die(6) self.cup_of_dice = [self.d1, self.d2, self.d3, self.d4, self.d5] self.choices = {"Yahtzee": False} def score(self, numbers): a = numbers.count(numbers[0]) if a == 5: return 50 else: return numbers[0] + numbers[1] + numbers[2] + numbers[3] + numbers[4] # figure out if numbers which is a list of 5 numbers between 1 and 6 # if they are all the same and return 50 if that is the case # if not, return the sum of all the numbers def roll(self): if len(self.chosen) == 0: rolled_dice = [self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll()] return rolled_dice else: for v in self.chosen: self.cup_of_dice[v].active = False rolled_dice = [self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll()] return rolled_dice def choose(self, choice): self.chosen = choice def newchoose(self, key, myroll): if myroll.count(myroll[0]) == 5: if self.choices[key] == True: return False else: self.choices[key] = True return True else: return False
def assign_hit_points(self): if not self.hit_point_adjustment: self.hit_point_adjustment = 0 if self.hit_point_generator == 'Max': ret_val = ((self.hit_point_modifier * self.hit_point_die) + self.hit_point_adjustment) elif self.hit_point_generator == 'Standard': ret_val = self.standard_hit_points else: d = Die(self.hit_point_die) ret_val = (d.roll(self.hit_point_modifier) + self.hit_point_adjustment) jdict = { "hit_point_generator": self.hit_point_generator, "hit_point_modifier": self.hit_point_modifier, "hit_point_die": self.hit_point_die, "hit_point_admustment": self.hit_point_adjustment } self.ctx.crumbs[-1].add_audit(json_dict=jdict) return ret_val
def test_die(self): d = Die(6) v = d.roll() self.assertGreater(v, 0) self.assertLess(v, 7)
class Yahtzee(): def __init__(self): self.chosen = () self.d1 = Die(6) self.d2 = Die(6) self.d3 = Die(6) self.d4 = Die(6) self.d5 = Die(6) self.cup_of_dice = [self.d1, self.d2, self.d3, self.d4, self.d5] self.choices = { "Yahtzee": False, "Chance": False, "Large Straight": False, "Small Straight": False, "Ones": False, "Twos": False, "Threes": False, "Fours": False, "Fives": False, "Sixes": False, "Three of a Kind": False, "Four of a Kind": False, "Full House": False, "Small Straight": False, "Large Straight": False } self.total = 0 def scores(self, numbers): d = {} sum = reduce(lambda a, b: a + b, numbers) if numbers.count(numbers[0]) == 5: d["Yahtzee"] = 50 else: d["Yahtzee"] = 0 d["Ones"] = numbers.count(1) d["Twos"] = numbers.count(2) * 2 d["Threes"] = numbers.count(3) * 3 d["Fours"] = numbers.count(4) * 4 d["Fives"] = numbers.count(5) * 5 d["Sixes"] = numbers.count(6) * 6 d["Chance"] = sum if self.three_of_a_kind(numbers): d["Three of a Kind"] = sum else: d["Three of a Kind"] = 0 if self.four_of_a_kind(numbers): d["Four of a Kind"] = sum else: d["Four of a Kind"] = 0 if self.full_house(numbers): d["Full House"] = 25 else: d["Full House"] = 0 if self.small_straight(numbers): d["Small Straight"] = 30 else: d["Small Straight"] = 0 if self.large_straight(numbers): d["Large Straight"] = 40 else: d["Large Straight"] = 0 return (d) def three_of_a_kind(self, numbers): for n in numbers: if numbers.count(n) >= 3: return True return False def four_of_a_kind(self, numbers): for n in numbers: if numbers.count(n) >= 4: return True return False def full_house(self, numbers): for n in numbers: if numbers.count(n) == 2: for n2 in numbers: if numbers.count(n2) == 3: return True return False def small_straight(self, numbers): numbers.sort() if numbers[:4] == [1, 2, 3, 4] or numbers[:4] == [2, 3, 4, 5]: return True return False def large_straight(self, numbers): numbers.sort() if numbers == [1, 2, 3, 4, 5] or numbers == [2, 3, 4, 5, 6]: return True return False def score(self, numbers): a = numbers.count(numbers[0]) if a == 5: return 50 else: return numbers[0] + numbers[1] + numbers[2] + numbers[3] + numbers[ 4] # figure out if numbers which is a list of 5 numbers between 1 and 6 # if they are all the same and return 50 if that is the case # if not, return the sum of all the numbers def roll(self): if len(self.chosen) == 0: for d in self.cup_of_dice: d.active = True rolled_dice = [ self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll() ] return rolled_dice else: for v in self.chosen: self.cup_of_dice[v].active = False rolled_dice = [ self.d1.roll(), self.d2.roll(), self.d3.roll(), self.d4.roll(), self.d5.roll() ] return rolled_dice def select(self, choice): self.chosen = choice def choose(self, key, myroll): if key == "Yahtzee": if myroll.count(myroll[0]) != 5: return False if self.choices[key]: return False else: self.choices[key] = True self.total = self.total + self.scores(myroll)[key] return True
# Test the Die class: from Die import Die die = Die() print("Roll die once:") print(die.roll()) print('-' * 70) # Challenge: from collections import Counter rolls = [] for i in range(100000): roll = die.roll() rolls.append(roll) c = Counter(rolls) c_sorted = sorted(c.items()) print('''Count the number of times each side occurred with 100,000 rolls:''') print(c_sorted) print('-' * 70)
import pygal from Die import Die # Create a D6 die = Die() # Make some rolls, then store results in a list results = [] for num_roll 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 1 die 1000 times" hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.x_title = "Result" hist.y_title = "Frequency" hist.add('D6', frequencies) hist.render_to_file('die_visual.svg')
import pygal from Die import Die # Create a D6 die_1 = Die() die_2 = Die(10) # Make some rolls, then store results in a list results = [] for num_roll 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) hist = pygal.Bar() hist.title = "Results of rolling 2 D6 dice 1000 times" hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16'] hist.x_title = "Result" hist.y_title = "Frequency" hist.add('D6 + D10', frequencies) hist.render_to_file('dice_visual.svg')
def test_2d8(): ctx = Ctx(app_username='******') d = Die(ctx=ctx, sides=8) r = d.roll(rolls=2) assert(16 >= r >= 2)
from Die import Die import pygal die_one = Die() # 骰子1 die_two = Die(12) # 骰子2 results = [] for roll_num in range(5000): result = die_one.roll() + die_two.roll() results.append(result) frequencies = [] # 最后需要被可视化的数据 for value in range(2, 19): frequency = results.count(value) frequencies.append(frequency) # Visualize the results hist = pygal.Bar() hist.title = "Results of rolling 6-side die" hist.x_labels = [] for i in range(2, 19): hist.x_labels.append(str(i)) hist.y_labels = "结果" hist.add('6-side dice and 10-side dice', frequencies) hist.render_to_file('die_visible_4.svg')
num_sides = input('How many sides should the die have? ') try: num_sides = int(num_sides) except ValueError: print('Sorry, that wasn\'t a number!') continue if num_sides >= 3: num_rolls = input('How many times do you want to roll the die? ') try: num_rolls = int(num_rolls) except ValueError: print('Sorry, that wasn\'t a number!') continue if num_rolls >= 1: die1 = Die(num_sides) die1.roll(num_rolls) die1.roll_stats() print(die1.list_of_rolls) for i, freq in zip(range(len(die1.freq_list)), die1.freq_list): print(f'{i+1}:{freq}', end='\t') else: print('Sorry, you have to roll the die at least once!') else: print('Sorry, the die must have at least 3 sides!') elif choice == str(2): num_flips = input('How many times do you want to flip the coin? ') try: num_flips = int(num_flips) except ValueError: print('Sorry, that wasn\'t a number!') continue
def test_2(): ctx = Ctx(app_username='******') d = Die(ctx=ctx, sides=2) r = d.roll(rolls=1) assert(2 >= r >= 1)
from Die import Die from Roller import Roller import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['lines.markersize'] = 5 numtrials = 1000000 d20 = Die(20) dm = Roller() norm = (1 / numtrials) * 100 rolls = [d20.roll() for i in range(1, numtrials)] adv = [dm.advantage() for i in range(1, numtrials)] dis = [dm.disadvantage() for i in range(1, numtrials)] advdis = [dm.advdis() for i in range(1, numtrials)] disadv = [dm.disadv() for i in range(1, numtrials)] # advadvdis = [dm.advadvdis() for i in range(1,numtrials)] # advdisadv = [dm.advdisadv() for i in range(1,numtrials)] # disadvdis = [dm.disadvdis() for i in range(1,numtrials)] # disdisadv = [dm.disdisadv() for i in range(1,numtrials)] print("Expected values: ") print(f"D20: {sum(rolls)/len(rolls)}") print(f"Adv: {sum(adv)/len(adv)}") print(f"Dis: {sum(dis)/len(dis)}") print(f"AdvDis: {sum(advdis)/len(advdis)}") print(f"DisAdv: {sum(disadv)/len(disadv)}") bins = [x - 0.5 for x in np.arange(1, 22)] bin_length = len(bins)
def test_3d6(): ctx = Ctx(app_username='******') d = Die(ctx=ctx, sides=6) r = d.roll(rolls=3) assert(18 >= r >= 3)
def get_name(self, db, gender): d = Die(ctx=self.ctx, sides=2) if self.race == 'Half-Elf': rndpick = d.roll() if rndpick == 1: tmprace = 'Human' else: tmprace = 'Elf' else: sql = (f"select count(id) from dnd_5e.lu_racial_first_name " f"where race = '{self.race}' ") results = db.query(sql) if results[0][0] > 0: tmprace = self.race else: tmprace = self.subrace_of f_nbr = self.table_ref_random(db=db, tablename='dnd_5e.lu_racial_first_name', columnname='race', value=tmprace, gender=gender) sql = (f"with tb as (select value, row_number() over " f"(partition by race order by id) " f"as orderBy from dnd_5e.lu_racial_first_name " f"where lower(race) = lower('{tmprace}') ") if gender == "U": genderstr = " = 'U'" else: genderstr = f" in ('{gender}','U')" sql = (f"{sql} and gender {genderstr} )" f"select value, orderby from tb where orderby = {f_nbr};") f_res = db.query(sql) first_name = f_res[0][0] if self.race == 'Half-Elf': rndpick = d.roll() if rndpick == 1: tmprace = 'Elf' else: tmprace = 'Human' l_nbr = self.table_ref_random(db=db, tablename='dnd_5e.lu_racial_last_name', columnname='race', value=tmprace, gender=gender) sql = (f"with tb as (select value, row_number() over " f"(partition by race order by id) " f"as orderBy from dnd_5e.lu_racial_last_name " f"where lower(race) = lower('{tmprace}') ") if gender == "U": genderstr = " = 'U'" else: genderstr = f" in ('{gender}','U')" sql = (f"{sql} and gender {genderstr} )" f"select value, orderby from tb where orderby = {l_nbr};") lres = db.query(sql) if lres[0][0] == "None": retstr = first_name else: retstr = f"{first_name} {lres[0][0]}" return retstr
################################################################################ # Assignment7 Yahtzee in Python # # # # PROGRAMMER: Ben McEwen # # CLASS: CS102 # # ASSIGNMENT: Assignment 7 # # INSTRUCTOR: Dean Zeller # # SUBMISSION DATE: 4/5/2018 # # # # DESCRIPTION: # # This program is a copy of some of the yahtzee assignments # # translated to Python # # # # COPYRIGHT: # # This program is (c) 2018 Ben McEwen and Dean Zeller. This is original work, # # without use of outside sources. # ################################################################################ from Die import Die cube = Die("Cube", 6, 1) print("\nTest 1: Six-sided die (D6)") print("\t Range 1 to", cube.getSides()) cube.roll(cube.sides) print("\t Single number Test:", cube.value) print("\t Multiple number test:") for x in range(0, 5): cube.roll(cube.sides) print("\t ", cube.getValue()) print()
class Nannon: """A class that implements the Nannon game""" board = None #: The board the game is played on die = None #: The die used to play the game points = {-1:0,1:0} #: How many points each side has. Note, -1 is used to represent white, and 1 black games = 0 #: Games played current = 0 #: The current player. 0 at start of game intToColor = lambda self, x: "white" if x == -1 else "tied" if x == 0 else "black" def __init__(self): """ #Use: s = Nannon() #Pre: None #Post: s is a new Nannon game """ self.board = Board() self.die = Die() self.points = {-1:0,1:0} self.games = 0 self.current = 0 def roll(self,current=0): """ #Use: k = s.roll(j) #Pre: s is a Nannon game. #Post: Alea iacta est. The dies are cast for the initial throw if current is 0, or just rolled if current is something else/not provided """ if current == 0: whiteDie = self.die.roll() blackDie = self.die.roll() if whiteDie == blackDie: return self.roll() else: self.current = 1 if whiteDie < blackDie else -1 return abs(whiteDie-blackDie) else: return self.die.roll() def getInput(self,lv=None): """ #Use: ch = s.getInput(i) #Pre: i is an integer, s is a Nannon object #Post: ch is an integer from stdin in [0,...,lv] """ try: ch = raw_input("Choice: ") if len(ch) == 0: ch = 0 ch = int(ch) if lv is not None: if ch not in range(lv): raise ValueError return ch except ValueError: print "Invalid choice!" return self.getInput(lv) def newGame(self,auto=False): """ #Use: s.newGame(a) #Pre: a is boolean #Post: The gameboard has been set up for a new game, and a messaged printed if the optional auto is false """ if not auto: print "New game, game %d \n\n" % (self.games) self.board = Board([-1,-1,0,0,1,1],{-1:1,1:1}) self.current = 0 self.gameOver = False def gameLoop(self,gamesToPlay = 1, auto = False): """ #Use: s.gameLoop(i,a) #Pre: i is an integer, a is boolean, both optional #Post: The game has been played for i rounds, 1 if i not provided, automatically if auto is True """ while self.games < gamesToPlay: self.newGame(auto) while self.gameOver is False: self.current = self.current*-1 roll = self.roll(self.current) v = self.board.validMoves(roll,self.current) if v == []: if not auto: print "It's %s's turn. The roll was %d." % (self.intToColor(self.current), roll) print "No available moves." print continue if not auto: print "It's %s's turn. The roll was %d." % (self.intToColor(self.current), roll) print self.board print "Choose from the following moves (default 0):" self.printMoves(v,self.current) ch = self.getInput(len(v)+1) if not auto else 0 #Biased for black, len(v)-1 is biased for white fr,to = v[int(ch)] self.gameOver = self.board.move(fr,to) if not auto: print self.points[self.current] = self.points[self.current]+1 if not auto: print "The winner of this round is %s!" % (self.intToColor(self.current)) self.printScore self.games = self.games+1 def printScore(self): """ #Use: s.printScore() #Pre: s i s a Nannon object #Post: The current score has been printed """ winner = -1 if self.points[-1] > self.points[1] else 0 if self.points[-1] == self.points[1] else 1 pointString = (self.points[winner],self.points[winner*-1]) if winner != 0 else (self.points[1],self.points[1]) print "The score is %s with %s points, after %d games." % (self.intToColor(winner), "%d to %d" % pointString ,self.games) def printMoves(self,moves,color): """ #Use: s.printMoves(m,c) #Pre: s is a nannon object, m is a list of valid moves, color is the color of the player who can preform the moves #Post: The current score has been printed """ for i,r in enumerate(moves): f,t = r rangelist = [k for k in range(-6,14) if k != 0 and k != 7] chart = dict(zip(rangelist,map(lambda x: x if x in range(1,7) else "safety",rangelist))) chart[self.board.home(color)] = "home" chart[self.board.safety(color)] = "safety" print " %d: Move %s checker from %s to %s" %(i,self.intToColor(color),str(chart[f]),str(chart[t])) for k in range(i,2): print
# Test Die class: from Die import Die from collections import Counter die = Die() for i in range(100000): roll = die.roll() c = Counter(die.rolls) c_sorted = sorted(c.items()) print("Die class keeps track of roll history:") print(c_sorted) print('-' * 70)