Пример #1
0
    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]
            }
Пример #2
0
 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
Пример #3
0
    def __init__(self):
        print(" -- Welcome to die game called 'oczko'! -- ")

        self.__die = Die(6)
        self.__playerScore = 0
        self.__computerScore = 0
        self.__on = True
Пример #4
0
def test_4d6_withresistance():
    ctx = Ctx(app_username='******')
    d = Die(ctx=ctx, sides=6, debug_ind=True)
    r = d.roll_with_resistance(rolls=4)
    details = d.get_details()[-1]
    assert(len(details.base_roll) == 4)
    assert(details.die_total_used == r)
    assert(12 >= r >= 2)
Пример #5
0
 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]
Пример #6
0
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)
Пример #7
0
 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
Пример #8
0
 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}
Пример #9
0
def test_d20_withdisadvantage():
    ctx = Ctx(app_username='******')
    d = Die(ctx=ctx, sides=20, debug_ind=True)
    r = d.roll_with_disadvantage()
    details = d.get_details()[-1]
    assert(len(details.base_roll) == 2)
    assert(details.die_total_used == r)
    assert(min(details.base_roll) == r)
    assert(20 >= r >= 1)
Пример #10
0
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()
Пример #11
0
    def createStartingDie(self, topNum, rightNum, playerStr):
        d = Die()
        die = [0] * 6
        keyPiece = False

        # Die[top, bottom, left, right, front, back]
        # When creating a key piece set the keypiece bool to true
        if(topNum == 1 and rightNum == 1):
            die[0] = 1
            die[1] = 1
            die[2] = 1
            die[3] = 1
            die[4] = 1
            die[5] = 1
            keyPiece = True
        else:
            die[0] = topNum
            die[1] = 7 - topNum
            die[2] = 7 - rightNum
            die[3] = rightNum
            die[4] = 4
            die[5] = 3
        d.setDie(die)
        d.setKeyPiece(keyPiece)
        d.setPlayer(playerStr)
        return d
Пример #12
0
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
Пример #13
0
 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
Пример #14
0
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)
Пример #15
0
def player_turn(player, hand):
	'''
	Logic of one player's turn
	'''

	# Declare player n's turn

	print('\n' + player.name + "'s turn! \n")

	# Create 6 dice named A-F

	dice_letters = ['A', 'B', 'C', 'D', 'E', 'F']
	dice = []
	for letter in dice_letters:
		dice.append(Die())
	dice_dict = dict(zip(dice_letters, dice))

	# Roll and keep values until player's hand has 6 values

	while len(hand.rolls) < 6:
		input(">> Press Enter to roll. ")
		temp_rolls = {}

		# Show rolled dice with letter names

		dice_header = ''
		for die in dice_dict.keys():
			dice_header += ('    ' + die + '       ')
			temp_roll = dice_dict[die].roll()
			temp_rolls[die] = temp_roll
			#print(Roll(temp_roll))
		print(dice_header)
		display_funcs.ndice(*temp_rolls.values())	



		# Show player's hand

		print('Your hand: ')
		# print(hand)
		hand.display_hand()

		# Ask player which dice to keep

		kept = ask_keep(dice_letters)

		# Add kept dice to player's hand

		for die in set(kept):
			hand.keep_roll(temp_rolls[die])

			# Remove kept dice from ones that are "rollable"
			dice_letters.remove(die)
			del dice_dict[die]

		# Show updated hand and score

		hand.calc_score()
		hand.display_hand()
		print(player.name + "'s score: " + str(hand.score))
Пример #16
0
    def __init__(self):
        MAX_COL = 9
        MAX_ROW = 8
        self.gameboard = [[Die() for j in range(MAX_COL)] for i in range(MAX_ROW)]
        # Computer Starting Positions
        self.gameboard[7][0] = self.createStartingDie(5, 6, "C")
        self.gameboard[7][1] = self.createStartingDie(1, 5, "C")
        self.gameboard[7][2] = self.createStartingDie(2, 1, "C")
        self.gameboard[7][3] = self.createStartingDie(6, 2, "C")
        self.gameboard[7][4] = self.createStartingDie(1, 1, "C")
        self.gameboard[7][5] = self.createStartingDie(6, 2, "C")
        self.gameboard[7][6] = self.createStartingDie(2, 1, "C")
        self.gameboard[7][7] = self.createStartingDie(1, 5, "C")
        self.gameboard[7][8] = self.createStartingDie(5, 6, "C")

        # Human Starting Positions
        self.gameboard[0][0] = self.createStartingDie(5, 6, "H")
        self.gameboard[0][1] = self.createStartingDie(1, 5, "H")
        self.gameboard[0][2] = self.createStartingDie(2, 1, "H")
        self.gameboard[0][3] = self.createStartingDie(6, 2, "H")
        self.gameboard[0][4] = self.createStartingDie(1, 1, "H")
        self.gameboard[0][5] = self.createStartingDie(6, 2, "H")
        self.gameboard[0][6] = self.createStartingDie(2, 1, "H")
        self.gameboard[0][7] = self.createStartingDie(1, 5, "H")
        self.gameboard[0][8] = self.createStartingDie(5, 6, "H")
Пример #17
0
 def dieSwitch(self, topNum, rightNum, player):
     # Die[top, bottom, left, right, front, back]
     d = Die()
     if(topNum == 1):
         if(rightNum == 1):
             d = self.createDie(topNum, rightNum, 1, 1, player)
         elif(rightNum == 2):
             d = self.createDie(topNum, rightNum, 3, 4, player)
         elif(rightNum == 3):
             d = self.createDie(topNum, rightNum, 5, 2, player)
         elif(rightNum == 4):
             d = self.createDie(topNum, rightNum, 2, 5, player)
         elif(rightNum == 5):
             d = self.createDie(topNum, rightNum, 4, 3, player)
     elif(topNum == 2):
         if(rightNum == 1):
             d = self.createDie(topNum, rightNum, 4, 3, player)
         elif(rightNum == 3):
             d = self.createDie(topNum, rightNum, 1, 6, player)
         elif(rightNum == 4):
             d = self.createDie(topNum, rightNum, 6, 1, player)
         elif(rightNum == 6):
             d = self.createDie(topNum, rightNum, 3, 4, player)
     elif(topNum == 3):
         if(rightNum == 1):
             d = self.createDie(topNum, rightNum, 2, 5, player)
         elif(rightNum == 2):
             d = self.createDie(topNum, rightNum, 6, 1, player)
         elif(rightNum == 5):
             d = self.createDie(topNum, rightNum, 1, 6, player)
         elif(rightNum == 6):
             d = self.createDie(topNum, rightNum, 5, 2, player)
     elif(topNum == 4):
         if(rightNum == 1):
             d = self.createDie(topNum, rightNum, 5, 2, player)
         elif(rightNum == 2):
             d = self.createDie(topNum, rightNum, 1, 6, player)
         elif(rightNum == 5):
             d = self.createDie(topNum, rightNum, 6, 1, player)
         elif(rightNum == 6):
             d = self.createDie(topNum, rightNum, 2, 5, player)
     elif(topNum == 5):
         if(rightNum == 1):
             d = self.createDie(topNum, rightNum, 3, 4, player)
         elif(rightNum == 3):
             d = self.createDie(topNum, rightNum, 6, 1, player)
         elif(rightNum == 4):
             d = self.createDie(topNum, rightNum, 1, 6, player)
         elif(rightNum == 6):
             d = self.createDie(topNum, rightNum, 4, 3, player)
     elif(topNum == 6):
         if(rightNum == 2):
             d = self.createDie(topNum, rightNum, 4, 3, player)
         elif(rightNum == 3):
             d = self.createDie(topNum, rightNum, 2, 5, player)
         elif(rightNum == 4):
             d = self.createDie(topNum, rightNum, 5, 2, player)
         elif(rightNum == 5):
             d = self.createDie(topNum, rightNum, 3, 4, player)
     return d
Пример #18
0
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)
Пример #19
0
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
Пример #20
0
def main():
    if len(sys.argv) == 1:
        print("No Rolling-Die-Puzzle file provided.  Now exiting")
        return
    for i in range(1, len(sys.argv)):
        filename = sys.argv[i]
        try:
            board = Board(filename)
            startLocation = board._dieLocation
            startDie = Die()

            for heuristicFunction in SequenceOfHeuristics:
                print("")
                raw_input("Press ENTER to continue to next heuristic")
                print("")
                print("Heuristic Function: " + heuristicFunction.__name__)
                print(board)
                closedCounter = Counter()  #global counter for node closing
                frontierCounter = Counter()  #global counter for node expansion
                emptyPath = tuple()
                startNode = BoardNode(board, startLocation, startDie,
                                      closedCounter, frontierCounter,
                                      emptyPath)
                path = aStarSearch(heuristicFunction, startNode)
                if path:  #if path is found
                    for direction in path:
                        board.moveDie(direction)
                        print(board)
                    print("")
                    print("Length: " + str(len(path)))
                else:  #if path not found
                    print("No Solution")
                print("Number Visited  : " + str(closedCounter.getCount()) +
                      " (including start state)")
                print("Number Generated: " + str(frontierCounter.getCount()))
                print("End of heuristic '" + heuristicFunction.__name__ + "'")
                ##reset board for next heuristic
                board._die = Die()
                board._dieLocation = startLocation

        except IOError as e:
            print(e)
        except NoStartError as e:
            print(e)
    return
Пример #21
0
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: ")
Пример #22
0
 def movePieceRight(self, row, col):
     tempBoard = self.getGameBoard()
     player = tempBoard[row][col].getPlayer();
     emptyDie = Die()
     if(player == 'H'):
         tempBoard[row][col].lateralRightMove()
     else:
         tempBoard[row][col].lateralLeftMove()
     tempBoard[row][col + 1] = tempBoard[row][col]
     tempBoard[row][col] = emptyDie
     self.setGameBoard(tempBoard)
    def initiative_check(
        NPC_Name
    ):  # Initiative determines which player will have the first move when fight scene begins

        #Initiative Bonus
        PC_initiative = PC["Stats"]["Initiative"]
        NPC_initiative = NPC[NPC_Name]["Dexterity"]["Modifier"]

        start = Die().initiative_roll(PC_initiative, NPC_initiative, NPC_Name)

        return start
Пример #24
0
 def movePieceDown(self, row, col):
     tempBoard = self.getGameBoard()
     player = tempBoard[row][col].getPlayer();
     emptyDie = Die()
     if(player == 'H'):
         tempBoard[row][col].backwardMove()
     else:
         tempBoard[row][col].frontalMove()
     tempBoard[row - 1][col] = tempBoard[row][col]
     tempBoard[row][col] = emptyDie
     self.setGameBoard(tempBoard)
Пример #25
0
    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()
Пример #26
0
    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
Пример #27
0
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.")
Пример #28
0
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: ")
Пример #29
0
    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 skill_check(
        parameters
    ):  # skill_check determines if a player is succesful at an attempt to perform a certain action.

        # multiple paramters will always be passed in the form of a tuple:

        skill = skills_main[parameters[0]]  # which skill will be checked
        difficulty = parameters[1]  # diffuclty of the task to be performed
        method = parameters[
            2]  # function which will be used after the check is complete.
        die = parameters[3]  # type of die used

        check_roll = Die().skill_roll(skill, difficulty, die)

        (method)(check_roll)
Пример #31
0
    def initializer(self):

        msg = "##################\n" \
            "# WELCOME TO PIG #\n" \
            "##################\n"

        print(msg)

        player1_name = input("Please enter player1 name: ")
        player2_name = input("Please enter player2 name: ")

        die = Die()

        self.p1 = Player(player1_name, die)
        self.p2 = Player(player2_name, die)

        self.game = Game(self.p1, self.p2, die)
Пример #32
0
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
Пример #33
0
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
Пример #34
0
 def moveSpace(self):
     self._currentSpace += Die.getCurrentFace()
Пример #35
0
def main():
    print("random",random.randint(0,6))
    # ALL THE STUFF!

    # Trade
    def trade(p1, p2):
        """
        :param p1: Player 1
        :param p2: Player 2
        :return: None
        """
        deal = input("Are properties being traded? (y/n) ")
        temp = None
        if deal == "y":
            print("---- PROPERTY NAMES ARE CASE SENSITIVE ----")
            deal = input("Is Player one giving a property? (y/n) ")
            if deal == "y":
                print("Player one's properties:")
                print(p1.getProperties())
                temp = input("What would you like to trade, Player one? ")
                p1.loseProperty(temp)
            deal = input("Is Player two giving a property (y/n) ")
            if deal == "y":
                print("Player two's properties:")
                print(p2.getProperties())
                if temp != None:
                    p2.gainProperty(temp)
                temp = input("What would you like to trade, Player two? ")
                p1.gainProperty(temp)
                p2.loseProperty(temp)
        money = input("Is there money involved in this trade? (y/n) ")
        if money == "y":
            money = input("Is player one giving money? (y/n) ")
            if money == "y":
                p2.gainMoney(int(input("How much money is Player one giving? $")))
            money = input("Is player two giving money? (y/n) ")
            if money == "y":
                p1.gainMoney(int(input("How much money is Player two giving? $")))
        return

    # Die
    Die1 = Die()
    Die2 = Die()

    # Properties:

    # Purple
    Mediterranean = Property("Mediterranean Avenue", "brown", 60, 50, 50, 30, [2, 10, 30, 90, 160, 250])
    Baltic = Property("Baltic Avenue", "brown", 60, 50, 50, 30, [4, 20, 60, 180, 320, 450])

    # Light Blue
    Oriental = Property("Oriental Avenue", "light blue", 100, 50, 50, 50, [6, 30, 90, 270, 400, 550])
    Vermont = Property("Vermont Avenue", "light blue", 100, 50, 50, 50, [6, 30, 90, 270, 400, 550])
    Connecticut = Property("Connecticut Avenue", "light blue", 120, 50, 50, 60, [8, 40, 100, 300, 450, 600])

    # Fuschia
    StCharles = Property("St. Charles Place", "fuschia", 140, 100, 100, 70, [10, 50, 150, 450, 625, 750])
    States = Property("States Avenue", "fuschia", 140, 100, 100, 70, [10, 50, 150, 450, 625, 750])
    Virginia = Property("Virginia Avenue", "fuschia", 160, 100, 100, 80, [12, 60, 180, 500, 700, 900])

    # Orange
    StJames = Property("St. James Place", "orange", 180, 100, 100, 90, [14, 70, 200, 550, 750, 950])
    Tennessee = Property("Tennessee Avenue", "orange", 180, 100, 100, 90, [14, 70, 200, 550, 750, 950])
    NewYork = Property("New York Avenue", "orange", 200, 100, 100, 100, [12, 80, 220, 600, 800, 1000])

    # Red
    Kentucky = Property("Kentucky Avenue", "red", 220, 150, 150, 110, [18, 90, 250, 700, 875, 1050])
    Indiana = Property("Indiana Avenue", "red", 220, 150, 150, 110, [18, 90, 250, 700, 875, 1050])
    Illinois = Property("Illinois Avenue", "red", 240, 150, 150, 120, [20, 100, 300, 750, 925, 1100])

    # Yellow
    Atlantic = Property("Atlantic Avenue", "yellow", 260, 150, 150, 130, [22, 1110, 330, 800, 975, 1150])
    Ventnor = Property("Ventnor Avenue", "yellow", 260, 150, 150, 130, [22, 1110, 330, 800, 975, 1150])
    Marvin = Property("Marvin Gardens", "yellow", 280, 150, 150, 140, [24, 120, 360, 850, 1025, 1200])

    # Green
    Pacific = Property("Pacific Avenue", "green", 300, 200, 200, 150, [26, 130, 390, 900, 110, 1275])
    NorthCarolina = Property("North Carolina Avenue", "green", 300, 200, 200, 150, [26, 130, 390, 900, 110, 1275])
    PennsylvaniaAve = Property("Pennsylvania Avenue", "green", 320, 200, 200, 160, [28, 150, 450, 1000, 1200, 1400])

    # Blue
    Park = Property("Park Place", "blue", 350, 200, 200, 175, [35, 175, 500, 1100, 1300, 1500])
    Boardwalk = Property("Boardwalk", "blue", 400, 200, 200, 30, [50, 200, 600, 1400, 1700])


    #Railroads:
    Pennsylvania = Railroad("Pennsylvania Railroad")

    Reading = Railroad("Reading Railroad")

    Short_Line = Railroad("Short Line")

    BO = Railroad("B. &. O. Railroad")  # lol

    # Utilities:
    Water = Utility("Water Works", Die1, Die2)
    Electric = Utility("Electric Company", Die1, Die2)

    # Extra Spaces:

    # Just Visiting
    # Nothing happens :D

    # Free Parking
    # Put in the turn code

    # Luxury Tax/Income Tax
    # Turn code
    # Variables

    hotels = 12

    houses = 32

    pieces = ["Dog","Top Hat", "Car", "Iron", "Boat", "Thimble", "Boot", "Wheelbarrow"]

    spaces = ["Go", Mediterranean, "Community Chest", Baltic, "Income Tax", Reading, Oriental,
              "Chance", Vermont, Connecticut, "Jail", StCharles, Electric, States, Virginia, Pennsylvania,
              StJames, "Community Chest", Tennessee, NewYork, "Free Parking", Kentucky, "Chance",
              Indiana, Illinois, BO, Atlantic, Ventnor, Water, Marvin, "Go To Jail", Pacific, NorthCarolina,
              "Community Chest", PennsylvaniaAve, Short_Line, "Chance", Park, "Luxury Tax", Boardwalk]
    print("debug", spaces[39])
    # Cards:

    # Community Chest:
    # kill me
    # textEffect, effect

    Chesta = CommunityChest("Life Insurance Matters - Collect $100",100)
    Chestb = CommunityChest("Income Tax Refund - Collect $20", 20)
    Chestc = CommunityChest("Receive for Services - Collect $25", 25)
    Chestd = CommunityChest("Pay Hospital $100", -100)
    Cheste = CommunityChest("Christmas Fund Matures - $100", 100)
    Chestf = CommunityChest("You have won second prize in a beauty contest! - Collect $10", 10)
    Chestg = CommunityChest("Doctors Fee! Pay $50", -50)
    Chesth = CommunityChest("From sale of stock you get $45", 45)
    Chesti = CommunityChest("Pay School Tax of $150", -150)
    Chestj = CommunityChest("Go To Jail", "Jail")
    Chestk = CommunityChest("Advance to Go", "go")
    Chestl = CommunityChest("You inherit $100", 100)
    Chestm = CommunityChest("Bank Error in Your Favor - Collect $200", 200)
    Chestn = CommunityChest("Get Out of Jail Free", "jail card")
    communityChestDeck = [Chesta, Chestb, Chestc, Chestd, Cheste, Chestf, Chestg, Chesth, Chesti, Chestj, Chestk, Chestl, Chestm, Chestn]

    # Chance Cards:
    # TextEffect, effect, type

    ChanceA = Chance("Your building and loan matures - Collect $150", "money", 150)
    ChanceB = Chance("Bank pays you dividend of $50", "money", 50)
    ChanceC = Chance("Advance token to nearest utility - if unowned, you may buy it from bank."
                     "If owned, throw dice and pay owner a total ten times the amount thrown","move",0)
    ChanceD = Chance("Advance to Illinois Ave","move",24)
    chanceDeck = [ChanceA, ChanceB, ChanceC, ChanceD]

    freeParking = 0  #Free Parking
    # TURN CODE
    # i want to die
    print("Welcome to MONOPOLY!!")  # this is more excited than I feel. I hate monopoly
    print("There are 4 people playing")

    # player inputs
    print("Hi players! What piece would you like to have? There are: ")
    for i in range(len(pieces)):
        print(pieces[i],end=" ")
    print("available! Please don't choose the same piece.")  # figure out how to make them not choose the same piece
    player1 = Player(input("Player 1! Input your piece here! "))
    #if player1.getPiece() not in pieces:
    #    print("This was not an acceptable piece to input. Try again")
    player2 = Player(input("Player 2! Input your piece here! "))
    player3 = Player(input("PLayer 3! Input your piece here! "))
    player4 = Player(input("Player 4! Input your piece here! "))

    print("Rolling die to see who goes first!")

    input("Player 1, roll the die!")
    p1d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p1d)
    print()

    input("Player 2, roll the die!")
    p2d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p2d)
    print()

    input("Player 3, roll the die!")
    p3d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p3d)
    print()

    input("Player 4, roll the die!")
    p4d = Die1.rollDie() + Die2.rollDie()
    print("You rolled:", p4d)

    print()

    playerOrder = []
    if max(p1d, p2d, p3d, p4d) == p1d:
        print("Player 1 goes first!")
        playerOrder = [player1, player2, player3, player4]
    elif max(p1d, p2d, p3d, p4d) == p2d:
        print("Player 2 goes first!")
        playerOrder = [player2, player3, player4, player1]
    elif max(p1d, p2d, p3d, p4d) == p3d:
        print("Player 3 goes first!")
        playerOrder = [player3, player4, player1, player2]
    else:
        print("Player 4 goes first!")
        playerOrder = [player4, player1, player2, player3]

    # Beginning the game
    while playerOrder[0].getMoney() > 0 or playerOrder[1].getMoney() > 0 or playerOrder[2].getMoney() > 0 or playerOrder[3].getMoney() > 0:
        cp = 0

        # Cycling around the order of players
        while cp < 4:

            # Making sure player not in jail
            if not playerOrder[cp].getInJail():
                print()
                print(playerOrder[cp].getPiece(), " Press enter to roll the die!")
                input()
                Die1.rollDie()
                Die2.rollDie()

                # Think about doing the doubles x3 to jail-- maybe not?
                print("You've rolled:", Die1.getCurrentFace(), "and", Die2.getCurrentFace())

                # Passing Go
                if playerOrder[cp].getSpace() + (Die1.getCurrentFace()+Die2.getCurrentFace()) > 39:
                    sp = (Die1.getCurrentFace()+Die2.getCurrentFace()) - (39 - playerOrder[cp].getSpace())
                    playerOrder[cp].setSpace(sp)
                    playerOrder[cp].gainMoney(200)
                    print("You passed GO! You've collected $200!")
                else:
                    playerOrder[cp].moveSpace(Die1.getCurrentFace(), Die2.getCurrentFace())

                # Community Chest
                if playerOrder[cp].getSpace() == 2 or playerOrder[cp].getSpace() == 17 or playerOrder[cp].getSpace() == 33:  #community chest
                    print("You've landed on community chest!")
                    randomnum = random.randint(1, 13)
                    print(communityChestDeck[randomnum].getTextEffect())
                    communityChestDeck[randomnum].drawCard(playerOrder[cp])
                    if isinstance(communityChestDeck[randomnum].getEffect(), int):
                        print("Money!")
                        communityChestDeck[randomnum].applyEffect()
                    else:
                        if communityChestDeck[randomnum].getEffect() == "go":
                            print("You have been sent to GO and have collected $200")
                            communityChestDeck[randomnum].applyEffect()
                        elif communityChestDeck[randomnum].getEffect() == "Jail":
                            print("Oh no! You've been sent to jail!")
                            communityChestDeck[randomnum].applyEffect()
                        else:
                            print("You have a Get Out Of Jail Free card now!")
                            communityChestDeck[randomnum].applyEffect()

                # Chance
                elif playerOrder[cp].getSpace() == 7 or playerOrder[cp].getSpace() == 22 or playerOrder[cp].getSpace() == 36: #chance
                    print("Chance! D:")
                    print(playerOrder[cp].getSpace())

                # Income Taxes
                elif playerOrder[cp].getSpace() == 4 or playerOrder[cp].getSpace() == 38:
                    if playerOrder[cp].getSpace() == 4:
                        print("You've landed on income tax! You lost $200.")
                        playerOrder[cp].loseMoney(200)
                        print("Your current balance is:", playerOrder[cp].getMoney())
                        freeParking += 200
                    else:
                        print("You've landed on luxury tax! You lost $100.")
                        playerOrder[cp].loseMoney(100)
                        print("Your current balance is:", playerOrder[cp].getMoney())
                        freeParking += 200
                    print("debug", playerOrder[cp].getSpace())

                # Go To Jail
                elif playerOrder[cp].getSpace() == 31:  # Go To Jail
                    print("Oh no! Go to jail!")
                    playerOrder[cp].getArrested()
                    print(playerOrder[cp].getSpace())

                # Railroads
                elif playerOrder[cp].getSpace() == 5 or playerOrder[cp].getSpace() == 15 or playerOrder[cp].getSpace() == 25 or playerOrder[cp].getSpace() == 35: #railroads

                    print("You landed on", spaces[playerOrder[cp].getSpace()])
                    print("Your balance is", playerOrder[cp].getMoney())
                    if spaces[playerOrder[cp].getSpace()].getOwner() == "Bank":
                        buy = input("Would you like to buy the railroad for $200? (y/n)")
                        if buy == "y":
                            playerOrder[cp].gainProperty(spaces[playerOrder[cp].getSpace()])
                            playerOrder[cp].loseMoney(spaces[playerOrder[cp].getSpace()].getPrice())
                            print("You bought the railroad! Your properties now are:",playerOrder[cp].getProperties())
                            print("Your balance now is:", playerOrder[cp].getMoney())
                            spaces[playerOrder[cp].getSpace()].buyRailroad(playerOrder[cp])

                        else:
                            print()
                    else:
                        print("Oh no! You landed on someone else's railroad! You have to pay the rent now!")
                        playerOrder[cp].loseMoney((spaces[playerOrder[cp].getSpace()]).getRent())
                        (spaces[playerOrder[cp].getSpace()].getOwner).gainMoney(
                            spaces[playerOrder[cp].getSpace()]).getRent()
                        print("Now your balance is", playerOrder[cp].getMoney())

                # Utilities
                elif playerOrder[cp].getSpace() == 12 or playerOrder[cp].getSpace() == 28:
                    print("debug",playerOrder[cp].getSpace())
                    if Electric.getOwner() == "Bank" or Water.getOwner() == "Bank":
                        print("Would you like to buy the Utility?")
                        buy = input("(Y/N)")
                        if buy == "y".lower():
                            if playerOrder[cp].getSpace() == 12:
                                Electric.buyUtility(playerOrder[cp])
                                playerOrder[cp].gainProperty(Electric)
                                playerOrder[cp].loseMoney(Electric.getPrice())
                            else:
                                Water.buyUtility(playerOrder[cp])
                                playerOrder[cp].gainProperty(Water)
                                playerOrder[cp].loseMoney(Water.getPrice())
                        else:
                            print("Ok.")
                    else:
                        if playerOrder[cp].getSpace() == 12:
                            playerOrder[cp].loseMoney(1)  # you should change this
                    print("Utilities! yay!")

                # Free Parking
                elif playerOrder[cp].getSpace() == 20:
                    if freeParking == 0:
                        print("You landed on Free Parking! Congratulations, you get 100 dollars!")
                        playerOrder[cp].gainMoney(100)
                    else:
                        print("You landed on Free Parking! Congratulations! You get",freeParking,"dollars!")
                        playerOrder[cp].gainMoney(freeParking)

                # Just Visiting
                elif playerOrder[cp].getSpace() == 10:
                    print("You've landed on Just Visiting!")

                # Properties
                else:
                    print(playerOrder[cp].getSpace())
                    print("You are on", spaces[playerOrder[cp].getSpace()])
                    print("You have", playerOrder[cp].getMoney(),"dollars")
                    if spaces[playerOrder[cp].getSpace()].getOwner() is None:
                        buy = input("Would you like to buy the property? (y/n)")
                        if buy == "y":
                            playerOrder[cp].gainProperty(spaces[playerOrder[cp].getSpace()])
                            playerOrder[cp].loseMoney(spaces[playerOrder[cp].getSpace()].getPrice())
                            print(playerOrder[cp].getProperties())
                            spaces[playerOrder[cp].getSpace()].buyProperty(playerOrder[cp].getPiece())
                            print("You bought the property! Your properties now are:", playerOrder[cp].getProperties())
                            print("Your balance now is:", playerOrder[cp].getMoney())
                            print(spaces[playerOrder[cp].getSpace()].buyProperty(playerOrder[cp].getPiece()))
                        else:
                            print("")
                    else:
                        print("Oh no! You landed on someone else's property! You have to pay the rent now!")
                        playerOrder[cp].loseMoney((spaces[playerOrder[cp].getSpace()]).getRent())
                        (spaces[playerOrder[cp].getSpace()].getOwner()).gainMoney(spaces[playerOrder[cp].getSpace()]).getRent()
                        print("Now your balance is",playerOrder[cp].getMoney())
                if Die1.getCurrentFace() == Die2.getCurrentFace():
                    if playerOrder[cp].getTimesDoubled() <= 3:
                        cp += 0
                        print("You rolled a double! Since you did, you get to go again!")
                    else:
                        print("You rolled doubles three times! You've been sent to jail!")
                        playerOrder[cp].getInJail()
                        cp += 1
                else:
                    cp += 1

            # Jail area
            else:
                count = 0
                if playerOrder[cp].getTimesJailed() <= 3:
                    while count < 3:
                        Die1.rollDie()
                        Die2.rollDie()
                        print("You rolled:",Die1.getCurrentFace(),"and",Die2.getCurrentFace())
                        if Die1.getCurrentFace() == Die2.getCurrentFace():
                            print("You rolled a double! Have fun out of jail!")
                            playerOrder[cp].outOfJail()
                        else:
                            print("Roll again!")
                            count += 1
                    print("Aw, you didn't roll a double in 3 rolls! Try again next time!")
                    playerOrder[cp].moreTimesInJail()
                    cp += 1
                else:
                    print("You've spent more than three turns in jail!")
                    print("You now have to pay $50")
                    playerOrder[cp].loseMoney(50)
                    print("Your current balance is", playerOrder[cp].getMoney())
                    playerOrder[cp].outOfJail()

    print("Monopoly is over. Hope you had fun.")
Пример #36
0
################################################################################
if __name__ == "__main__":
    print ("Unit test for BoardNode.py mechanics:  Should return no falses")
    
    class Test:
        pass
    
    class TestBoard:
        pass
    
    N=Directions.NORTH
    E=Directions.EAST
    S=Directions.SOUTH
    W=Directions.WEST
    
    bNode = Test()
    brd = TestBoard()
    brd._goalLocation = (3,4)
    die = Die()
    loc = (3,4)
    die.rotate(N)
    die.rotate(E)
    bNode.die = die
    bNode.location = (2,5)
    bNode.board = brd
    print (ManhattanDistanceAccountingOrientation(bNode)==2)
    bNode.die.rotate(S)
    bNode.location = (3,5)
    
    print ("This concludes tests for BoardNode.py")