def play(self): board = Board().populate(self.snakes, self.ladders) dice = Dice() while self.winner == None: for player in self.players: dice_value = dice.roll() player.move(dice_value) encounter = board[player.position] if encounter: end = encounter.end print(f"{encounter.message}") player.move(end, encounter=True) if player.is_winner: self.winner = player break input() print("\n*************** GAME OVER ***************") print(f"Player {self.winner.name} won the game.") print("*************** GAME OVER ***************\n")
def __init__(self, player1, player2, width=860, height=560, fps=50, title="112 Term Project: Backgammon"): pygame.init() self.player1 = player1 self.player2 = player2 self.width = width self.height = height self.fps = fps self.title = title self.bgColor = (255, 255, 255) self.boardImage = pygame.image.load("board.png") self.boardRect = self.boardImage.get_rect() self.margin = 30 self.xcoords = [ 800, 738, 676, 613, 550, 485, 373, 308, 247, 182, 121, 60, 60, 121, 182, 247, 308, 373, 485, 550, 613, 676, 738, 800 ] self.isGameOver = False self.textFont = pygame.font.SysFont('calibri', 12, bold=True, italic=False) self.selected = None self.possibleMoves = [] self.dice = Dice() self.gameState = GameState.INITIAL_ROLL self.gsMessage = "Initial Roll" self.gsText = self.textFont.render(self.gsMessage, True, WHITE, BLACK) self.gsRect = self.gsText.get_rect() (self.gsRect.centerx, self.gsRect.centery) = (self.width // 2, self.margin // 2)
def __init__(self): self.nb_maison_dispo = 32 self.nb_hotel_dispo = 12 self.dice = Dice() # instanciation des cartes self.carte_chance = Carte_chance() self.carte_communaute = Carte_communaute() # instanciation des cases propriété self.proprietes = [] for i in proprietes_data: self.proprietes.append(Propriete(i)) # for p in self.proprietes: p.fiche() # instanciation des cases gare self.gares = [] for i in gares_data: self.gares.append(Gare(i)) # for g in self.gares: g.fiche() # instanciation des cases compagnie self.compagnies = [] for i in compagnies_data: self.compagnies.append(Compagnie(i)) # for c in self.compagnies: c.fiche() # instanciation de la prison self.prison = Prison() # tableau des joueurs self.joueurs = [] # initialisation graphique du plateau self.display = Display()
def generator_dice(style = None, num = None, lv = 1): while gfw.world.count_at(gfw.layer.dice) < 25: if num == None: num = random.randrange(25) if style == None: style = random.choice(dicestyle) if boardstate[num] == 0: d = Dice((get_canvas_width() // 2 - 118.6 + move * (num%5), get_canvas_height()//2 + 155.9 - move * (num//5)), style, num, lv) gfw.world.add(gfw.layer.dice, d) boardstate[num] = 1 newdice.play() return True else: num = None continue return False
def first_roll(): # First roll should just initiate 5 dice. dice = {} for i in range(1, 6): die = Dice() dice[i] = die for key, value in dice.items(): print(" _____ ") print("| |") print("| %d |" % value.value) print("|_____|") responses = {} responses['kept'] = {} responses['reroll'] = {} for key, value in dice.items(): keep = input("Would you like to keep Die %d ? (Y or N) " % key) if keep == "Y" or keep == "y": print("we'll keep the value") responses['kept'][key] = value.value elif keep == "N" or keep == "n": print("You can roll this again.") responses['reroll'][key] = value.value print(responses) return responses
def startGame(self): self.gameStarted = True if self.timeoutId.active(): self.timeoutId.cancel() self.logger("Game started") self.uiUpdateChannel({'type':1}) self.gamesCompleted = 0 self.PLAY_ORDER = list(self.agents.keys()) shuffle(self.PLAY_ORDER) self.winner = None self.dice = Dice() self.chest = Cards(communityChestCards) self.chance = Cards(chanceCards) self.state = State(self.PLAY_ORDER) self.mortgagedDuringTrade = [] # used during JailDecision self.diceThrown = False # used with Phase.BUY to decide which agent MORTGAGE & SELL_HOUSES # should be called for self.bsmAgentId = self.PLAY_ORDER[0] self.auctionStarted = False self.tradeCounter = 0 self.mapper = Mapper(self) for agentId in self.PLAY_ORDER: uri = self.endpoints['RESPONSE'].format(self.gameId, agentId) sub = yield self.subscribe(partial(self.mapper.response,agentId), uri) self.agents[agentId]['subKeys'].append(sub) self.mapper.request()
def __init__(self, player): super().__init__() Character.__init__(self) all_monsters = [ 'a Banshee', 'the Bogeyman', 'a Chimera', 'a large Cyclopse', 'a Red Dragon', 'a Demon', 'a Gorgon', 'a Hydra', 'a Hobgoblin', 'an Imp', 'a Mermaid', 'a Nymph', 'a Sprite', 'a Unicorn', 'a Vampire', 'a Zombie', 'a Werewolf', 'a Wraith', 'a Sphinx', 'a Shade', 'an Ogre', 'a Minotaur' ] monster = random.choice(all_monsters) # print monster self.name = monster self.health_max = random.randint(1, 3) self.health = self.health_max if self.health == 1: self._dice = [Dice(6)] if self.health == 2: self._dice = [Dice(6), Dice(6)] else: self._dice = [Dice(6), Dice(6), Dice(6)]
from dice import Dice import pygal d6_1 = Dice() d6_2 = Dice() results = [] for roll_num in range(100000): result = d6_1.roll() * d6_2.roll() results.append(result) frequencies = [] for value in range(1, 37): if results.count(value): frequency = results.count(value) frequencies.append(frequency) x_data = [] for value in range(1, 37): if value in results: x_data.append(value) hist = pygal.Bar() hist.title = "Results of rolling two D6 100000 times." hist.x_labels = x_data hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6*D6', frequencies) hist.render_to_file("dice_visual.svg") print(frequencies)
## 5/16/01: R. Pattis - Changed identifiers to conform to Java style ## 3/ 6/13: R. Pattis - Converted to Python ## ############################################################################## ############################################################################## from goody import irange from dice import Dice from stopwatch import Stopwatch import prompt import predicate win_count = 0 #Win/Lose/Dice Statistics lose_count = 0 dice = Dice([6, 6]) game_timer = Stopwatch() games_to_play = prompt.for_int('Enter # of games to play', is_legal=predicate.is_positive, error_message='an int, but not > 0') game_timer.start() dice.standard_rolls_for_debugging() count = 0 for game in irange(1, games_to_play): #print('game',game) #Each iteration plays one game first_roll = dice.roll().pip_sum() #print(first_roll) #Roll the dice and record their pip sum #Based on firstRoll, decide how to continue: # immediate win/loss or trying to make point
import pygal from dice import Dice # 统计同时抛两个面数不一样的骰子 dice_1 = Dice() dice_2 = Dice(10) results = [] for roll_num in range(50000): result = dice_1.roll() + dice_2.roll() results.append(result) frequencies = [] max_result = dice_1.num_sides + dice_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 a D6 and a D10 50,000 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 of Result' hist.add('D6 + D10', frequencies) hist.render_to_file('dice_visual.svg')
if __name__ == '__main__': board = Board() player_list = [] dice_list = [] player_win = 0 with open('input.txt', 'r') as f: snakes_count = int(f.readline()) for i in range(snakes_count): snake_head, snake_tail = f.readline().strip().split(" ") board.add_snakes(snake_head = snake_head, snake_tail = snake_tail) ladders_count = int(f.readline()) for i in range(ladders_count): ladder_bottom, ladder_top = f.readline().strip().split(" ") board.add_ladder(ladder_bottom = ladder_bottom, ladder_top = ladder_top) players_count = int(f.readline()) board.set_player_count(players_count) for i in range(players_count): player_list.append(Player(name=str(f.readline()).strip())) for dice_number in range(DICE_COUNT): dice_list.append(Dice()) while player_win < players_count-1: for player_turn in player_list: player_turn.play_dice(dice_list[0], board) if board.is_winner(player_turn): player_win += 1 print(player_turn.name + " won the game at position: " + str(player_win)) player_list.remove(player_turn)
from dice import Dice dice = Dice(8) print(dice.roll()) # Dice.printPossibleTypes() tenRolls = dice.rollTenTimes() for r in tenRolls: print("Wyrzucono {}".format(r))
from dice import Dice import pygal dice = Dice() dice2 = Dice(10) #存储摇到的骰子点数 results = [] for roll_num in range(50000): result = dice.roll() + dice2.roll() results.append(result) #存储分析结果 analysis_results = [] max_result = dice.num_sides + dice2.num_sides for value in range(2, max_result + 1): analysis = results.count(value) analysis_results.append(analysis) print(analysis_results) #结果可视化 hist = pygal.Bar() hist.title = 'Count two dice 50000 times' hist.x_labels = map(str, range(2, max_result + 1)) hist.x_title = 'points' hist.y_title = 'count results' hist.add('D6 + D10', analysis_results) hist.render_to_file('count_results3.svg') #文件后缀必须是.svg
def throwDice(self): dice = Dice() self.n = dice.drawDice() self.Verify = True self.diceImage = dice.dice self.VerifyDice = True
def setUp(self): """Run at the beginning of the test.""" self.game = Game() self.dice = Dice() self.intelligence = Intelligence("easy") self.game.player = Player("intell_class", True)
def __init__(self, dices): assert type(dices) == list and all(len(dice) == 6 for dice in dices) self._dices = [Dice(dice) for dice in dices]
def programs_array() -> List[Program]: return [Program(Dice()) for i in range(1000)]
from dice import Dice position_initiale = int(input("valeur initiale du dé :")) position_finale = int(input("position finale du dé :")) nombre_lancer = 0 de = Dice(position_initiale) while position_finale != de.get_position(): de.roll() nombre_lancer += 1 print("Il a fallut : ", nombre_lancer, "lacers")
from dice import Dice, randint roll_die = Dice() #roll_die.roll_d4() #roll_die.roll_d6() #roll_die.roll_d8() #roll_die.roll_d10() #roll_die.roll_d12() while True: roll_die.roll_d20() #roll_die.roll_d100()
from dice import Dice import matplotlib.pyplot as plt import pygal dice = Dice() res = [] for i in range(1000): r = dice.roll() res.append(r) print(type(res)) # 计算每个点出现的次数 count = [] for i in range(1, dice.num_sides + 1): c = res.count(i) count.append(c) print(count) # plt.scatter(range(1, dice.num_sides + 1), count) # plt.tick_params(axis='both',which='major',labelsize=14) # plt.show() hist = pygal.Bar() hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.add('D6', count) hist.render_to_file('dice_visual.svg')
def __init__(self, interface): self.dice = Dice() self.money = 100 self.interface = interface
from appJar import gui from dice import Dice model = { "dice": [Dice(), Dice(), Dice()], "somme": 3 } des_valeurs = ["\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"] def press_roll(): for i in range(3): if app.getCheckBox("check" + str(i)): model["dice"][i].roll() app.setLabel("valeur" + str(i), des_valeurs[model["dice"][i].get_position() - 1]) model["somme"] = model["dice"][0].get_position() + model["dice"][1].get_position() + model["dice"][2].get_position() app.setLabel("somme", str(model["somme"])) app = gui() app.setSize(400, 200) app.setTitle("lancé de dé") app.startFrame("left", row=0, column=0) for i in range(3): app.addLabel("valeur" + str(i), des_valeurs[model["dice"][i].get_position() - 1], 0, i) app.getLabelWidget("valeur" + str(i)).config(font="Time 100") app.addNamedCheckBox("", "check" + str(i), 1, i) app.addButton("lancer", press_roll, 2, 1)
def dice() -> Dice: return Dice()
from dice import Dice import pygal from functools import reduce # Create two D6 dice number_dice = 100 # Number of rolls number_rolls = 10000 # list of dice my_dice = [] for i in range(number_dice): my_dice.append(Dice()) # Make some rolls, and store results in a list results = [] for roll in range(number_rolls): result = 0 for i in my_dice: result += i.roll() results.append(result) # analyze the results frequencies = [] max_result = number_dice * 6 for value in range(number_dice, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results hist = pygal.Bar()
def test_roll_dice(mock_randint): dice = Dice(1, 6) dice.roll() mock_randint.assert_called_once_with(1, 7)
def test_get_dice(self): """Tests the returned value after rolling a die.""" dice = Dice() exp = dice.get_dice() self.assertIn(exp, self.faces)
def test_init(self): """Test the created instance.""" dice = Dice() self.assertIsInstance(dice, Dice)
def run_game(heuristic_name, player, domain_file_name, problem_file_name, gen_flag): # Start the first round: roll a dice, and build the first problem, and creates the first # plan # Update the file names heuristic = max_level if heuristic_name == "sum": heuristic = level_sum dice_obj = Dice(gen_flag) start = time.process_time() domain_file_name = dc.create_domain_file(domain_file_name, player.type) problem_file_name = problem_file_name.format(player.type) dice_val = dice_obj.roll_dice() player.dice_value = dice_val player.build_problem() print(ROLLING % player.dice_value + "MONEY: " + str(player.money)) prob = PlanningProblem(domain_file_name, problem_file_name, None, None) plan = a_star_search(prob, heuristic=heuristic) for p in plan: print(p) turns, expanded = 0, [] print(player.goal) # All the moves the player does in the game moves = [START % player.cell] moves.append("Amount of money: %s " % player.money) past_moves = [player.cell] with open("logs\log-{}.txt".format(str(datetime.datetime.now()).replace(":", "")), "w") as logs: while len(plan) != 0 and plan != 'failed': # Each plan most start with a movement from one cell to other cell # Move- move from one cell to the other, according to the dice if 'Move' in plan[0].name: turns, moves = play_for_move(turns, plan, moves, logs, player) # Move from one cell to "orange" cell, and pay 150, if it is achievable according to the dice elif 'pay_150' in plan[0].name: turns, plan, isContinue = play_for_pay_150(turns, plan, moves, logs, player) if isContinue: continue # Jump to a certain entrance if you don't have enough money to pay, or if you don't hold the # requested certificate elif 'jump' in plan[0].name: turns, plan, moves, isContinue = play_for_jump(turns, plan, moves, logs, player) if isContinue: continue # Go back to a cell already visited, if the player has the certificate/money to pay elif 'Goto' in plan[0].name: plan, moves, isContinue = play_for_goto(plan, moves, logs, player) if isContinue: continue else: # A plan can only start with a move from one cell to another print_exit(logs, plan, moves) # Starting a new round- creating a new problem.txt file # New round- roll the dice, and build a new plan according to the previous move write_current_move_logs(past_moves, player, turns, logs) actions = prob.get_actions() propositions = prob.get_propositions() player.dice_value = dice_obj.roll_dice() loc, last_dice = find_last_dice(plan) player.build_problem() expanded.append(str(prob.expanded)) print(ROLLING % player.dice_value) prob = PlanningProblem(domain_file_name, problem_file_name, actions, propositions) if last_dice == player.dice_value and last_dice is not None and len(player.need_pay_spots) == 0: plan = plan[loc:] else: plan = a_star_search(prob, heuristic=heuristic) print_plan(plan, logs) if len(plan) == 0: write_to_log("## LAST ##", logs) write_to_log("@@@@@@@@@@@PROPOSITIONS@@@@@@@@@@@", logs) for state in prob.initialState: write_to_log(state.name, logs) elapsed = time.process_time() - start if moves is not None and plan != "failed": prints_game_over(moves, logs, player, elapsed, turns, expanded) else: print("Could not find a plan in %.2f seconds" % elapsed) write_to_log("Could not find a plan in %.2f seconds" % elapsed, logs) return elapsed, expanded, turns
#! /usr/bin/env python3.7 # -*- coding: utf-8 -*- import pygal from dice import Dice dice6 = Dice() dice6_2 = Dice() results = [] for x in range(1000): result = dice6.roll() + dice6_2.roll() results.append(result) #分析结果 frequencies = [] for x in range(2, dice6.num_sides + dice6_2.num_sides +1): frequency = results.count(x) frequencies.append(frequency) #可视化每个点的频率 hist = pygal.Bar() hist.title = "Results of rolling two D6 1000 times." hist.x_labels = list(range(2, dice6.num_sides + dice6_2.num_sides +1)) hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6 + D6', frequencies) hist.render_to_file('dice_2_visual.svg')
textRect.center = (centerX, centerY) screen.blit(text, textRect) pg.display.flip() def whichStack(x, y): if y < HEIGHT // 2: return x // DIFF_X else: return 23 - x // DIFF_X size = 40 mid = HEIGHT // 2 - 22 dices = [] dices.append(Dice(0, mid - size // 2)) dices.append(Dice(0, mid + size // 2)) def main(): pg.font.init() message_display('for a regular game, press 1', WIDTH // 2, 200) message_display('to choose the start situation, press 2', WIDTH // 2, 400) chosen = False while not chosen: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_1: regularStart() chosen = True elif event.key == pg.K_2: