예제 #1
0
class DiceTest(unittest.TestCase):
    def setUp(self):
        self.sut = Dice(1, 2, 3)

    def test_roll_the_dice(self):
        self.sut.set_seed(0)
        self.assertEqual("morale", self.sut.roll())
        self.sut.set_seed(1)
        self.assertEqual("attack", self.sut.roll())
        self.sut.set_seed(2)
        self.assertEqual("morale", self.sut.roll())
        self.sut.set_seed(3)
        self.assertEqual("defense", self.sut.roll())
        self.sut.set_seed(4)
        self.assertEqual("defense", self.sut.roll())

    def test_set_attack(self):
        self.sut.set_attack()
        self.assertEqual("attack", self.sut.get_value())

    def test_set_defense(self):
        self.sut.set_defense()
        self.assertEqual("defense", self.sut.get_value())

    def test_set_morale(self):
        self.sut.set_morale()
        self.assertEqual("morale", self.sut.get_value())
예제 #2
0
class PokerApp:
    def __init__(self, interface):
        self.dice = Dice()
        self.money = 100
        self.highscore = 0
        self.interface = interface

    def run(self):
        while self.money >= 10 and self.interface.wantToPlay():
            self.playRound()
        self.interface.close()

    def playRound(self):
        self.money = self.money - 10
        self.interface.setMoney(self.money)
        self.doRolls()
        result, score = self.dice.score()
        self.interface.showResult(result, score)
        self.money = self.money + score
        self.interface.setMoney(self.money)
        #追踪最高分
        if score > self.highscore:
            self.interface.High(score)

    def doRolls(self):
        self.dice.rollAll()
        roll = 1
        self.interface.setDice(self.dice.values())
        toRoll = self.interface.chooseDice()
        while roll < 3 and toRoll != []:
            self.dice.roll(toRoll)
            roll = roll + 1
            self.interface.setDice(self.dice.values())
            if roll < 3:
                toRoll = self.interface.chooseDice()
예제 #3
0
 def checkSlingDart(self):
     d6 = Dice(1, 6)
     if self.inventory[len(self.inventory) - 1] == 'Sling':
         roll = d6.roll()
         self.inventory.append(f'{roll} Sling Stones')
     if self.inventory[len(self.inventory) - 1] == 'Dart':
         roll = d6.roll()
         self.inventory.append(f'{roll} Darts')
예제 #4
0
    def render(self):
        #Render asteroids and stars
        for object in self.objects:
            object.render()

        #Render powerups
        if len(self.powerups) > 0:
            for powerup in self.powerups:
                powerup.fallmove()

                if powerup.rect.y > self.screen.get_height():
                    self.powerups.remove(powerup)

            powerups_plain = pygame.sprite.RenderPlain(self.powerups)
            powerups_plain.draw(self.screen)

        #Render enemies
        if len(self.enemies) > 0:
            for enemy in self.enemies:
                enemy.render()

        #Render enemy projectiles
        enemy_shoot_chance = Dice()
        dice_roll = enemy_shoot_chance.roll()
        self.enemy_shoot(dice_roll)

        if len(self.enemy_projectiles) > 0:
            for enemy_projectile in self.enemy_projectiles:
                enemy_projectile.render()

                if enemy_projectile.rect.y > self.screen.get_height():
                    self.enemy_projectiles.remove(enemy_projectile)

        #Render explosions
        if len(self.explosions) > 0:
            for explosion in self.explosions:
                explosion.render_cycle()

                #Destroy asteroids and ufos inside explosion
                if type(explosion.object) is BombProjectile:
                    for object in self.objects:
                        if object.projectile_collided(explosion):
                            self.explosions.append(
                                Explosion(object.size, object.rect.x,
                                          object.rect.y, self.screen,
                                          explosion.object))
                            object.reset()
                            self.score_checker()

                    for enemy in self.enemies:
                        if enemy.projectile_collided(explosion):
                            self.explosions.append(
                                Explosion(object.size, object.rect.x,
                                          object.rect.y, self.screen,
                                          explosion.object))
                            self.enemies.remove(enemy)
                            self.score_checker()

                if explosion.over:
                    self.explosions.remove(explosion)
예제 #5
0
class Generator(object):

  def __init__(self):
    self._hand = Dice()
    self._hand.addDie(sides = 6, count = 4) # init to 4d6

  def __del__(self):
    pass

  def _rollBaseNumbers(self):
    return self._hand.roll(count = 6)

  def _generateScoreList(self):
    # roll 4d6 x 6
    rolls = self._rollBaseNumbers()

    # drop lowest from each set and sum remaining rolls into output
    output = []
    for rollset in rolls:
      rollset.remove(min(rollset))
      output.append(sum(rollset))

    return sorted(output, reverse = True)

  def generateScoreLists(self, count = 1):
    output = []
    for i in range(count):
      output.append(self._generateScoreList())
    return sorted(output, reverse = True)
예제 #6
0
class Game:
    def __init__(self, faces, players, board_size, snakes, ladders):

        self.snakes = {}
        self.ladders = {}
        self.board_size = board_size
        self.dice = Dice(faces)

        for src, dest in snakes:
            self.snakes[src] = dest

        for src, dest in ladders:
            self.ladders[src] = dest

        self.board = Board(self.board_size, self.snakes, self.ladders)
        self.players = [Player(name, self.board) for name in players]

    def play(self):
        while (1):
            for player in self.players:
                from_position = player.position
                dice_value = self.dice.roll()
                player.move(dice_value)
                to_position = player.position
                print(player.name, "rolled a", dice_value, "and moved from",
                      from_position, "to", to_position)
                if player.position == self.board_size:
                    return player.name + " wins the game"
예제 #7
0
 def getOccupation(self):
     die = Dice(1, 100)
     roll = die.roll()
     with open('occupations.csv', 'r') as occupations:
         reader = csv.reader(occupations)
         for row in reader:
             if roll == int(row[0]):
                 return row[1].title().strip()
예제 #8
0
    def rollHP(self):
        die = Dice(1, 4)
        HP = die.roll() + abilityModifier.table.get(
            self.abilities.get('Stamina'))[0]
        if HP < 1:
            HP = 1

        return HP
예제 #9
0
class DiceGame:

    # Constructor
    def __init__(self):

        # 2 new instances of Dice object
        self.m_d1 = Dice()
        self.m_d2 = Dice()

    def play(self):

        self.m_d1.roll()
        self.m_d2.roll()

        print('m_d1: {}'.format(self.m_d1.getValue()))
        print('m_d2: {}'.format(self.m_d2.getValue()))

        return self.m_d1.getValue() + self.m_d2.getValue() == 7
예제 #10
0
class DiceGame:

    # Constructor
    def __init__(self):

        # 2 new instances of Dice object
        self.m_d1 = Dice()
        self.m_d2 = Dice()

    def play(self):

        self.m_d1.roll()
        self.m_d2.roll()

        print('m_d1: {}'.format(self.m_d1.getValue()))
        print('m_d2: {}'.format(self.m_d2.getValue()))

        return self.m_d1.getValue() + self.m_d2.getValue() == 7
예제 #11
0
 def _getFirstPlayer(self, playerList):
     ''' Returns the first player based on rolling a dice.'''
     highestRollers = set()
     highestRoll = 0
     dice = Dice()
     for player in playerList:
         print(player.getName() + " rolls a " + str(dice.getTop()))
         if dice.getTop() > highestRoll:
             highestRollers.clear()
             highestRollers.add(player)
             highestRoll = dice.getTop()
         elif dice.getTop() == highestRoll:
             highestRollers.add(player)
         dice.roll()
     if len(highestRollers) > 1:
         return self._getFirstPlayer(highestRollers)
     else:
         return highestRollers.pop()
예제 #12
0
파일: Game.py 프로젝트: mbrookes1304/Dudo
 def _getFirstPlayer(self, playerList):
     ''' Returns the first player based on rolling a dice.'''
     highestRollers = set()
     highestRoll = 0
     dice = Dice()
     for player in playerList:
         print(player.getName() + " rolls a " + str(dice.getTop()))
         if dice.getTop() > highestRoll:
             highestRollers.clear()
             highestRollers.add(player)
             highestRoll = dice.getTop()
         elif dice.getTop() == highestRoll:
             highestRollers.add(player)
         dice.roll()
     if len(highestRollers) > 1:
         return self._getFirstPlayer(highestRollers)
     else:
         return highestRollers.pop()
예제 #13
0
class TestDice(unittest.TestCase):

    def setUp(self):
        self.sides = 8
        self.dice = Dice(self.sides)
    def test_roll(self):
        for i in range(1000):
            self.assertLessEqual(self.dice.roll(), self.sides)
    def test_error(self):
        self.assertRaises(ValueError, Dice, 0)
예제 #14
0
class PokerApp:
    def __init__(self):
        self.dice = Dice()
        self.money = 100
        self.interface = PokerInterface(self.money)

    def run(self):
        while self.money >= 10 and self.interface.wantToPlay():
            self.playRound()

        self.interface.close()

    def playRound(self):
        self.money -= 10

        self.doRolls()

        result, score = self.dice.getPayoff()
        self.money += score

        self.interface.updateMoney(self.money)
        self.interface.showResults(result, score)

    def doRolls(self):
        self.dice.rollAll()
        roll = 1

        self.interface.updateDice(self.dice.getValues())

        while True:
            if roll < 3:
                diceToRoll = self.interface.chooseDice()

                if diceToRoll == []: break
                else:
                    self.dice.roll(diceToRoll)
                    self.interface.updateDice(self.dice.getValues())

                    roll += 1

            else:
                break
예제 #15
0
class PokerGame:
    """The player starts with \$100.
    Each round costs \$10 to play. This amount is subtracted from the player’s money at the start of the round.
    The player initially rolls a completely random hand (i.e. all the five dice are rolled).
    The player gets two chances to enhance the hand by re-rolling some or all of the dice."""
    def __init__(self, Interface):
        self.Dice = Dice()
        self.money = 100
        self.Interface = Interface

    def game_termination(self):

        # game terminates if player chooses to terminate or has more than $10
        while (self.money >= 10 and self.Interface.continue_play()):
            self.play_poker()
        self.Interface.terminate()

    def play_poker(self):

        # each round costs $10 dollars
        self.money = self.money - 10
        self.Interface.current_money_value(self.money)
        self.rolls()
        result, score = self.Dice.Score()
        self.Interface.show_results(result, score)
        self.money = self.money + score
        self.Interface.current_money_value(self.money)

    def rolls(self):

        self.Dice.roll(range(5))
        roll = 1
        self.Interface.dice_set_values(self.Dice.values())
        dice_to_be_rolled = self.Interface.choose_dice()
        while roll < 3 and dice_to_be_rolled != []:
            self.Dice.roll(dice_to_be_rolled)
            roll = roll + 1
            self.Interface.dice_set_values(self.Dice.values())
            if roll < 3:
                dice_to_be_rolled = self.Interface.choose_dice()
예제 #16
0
 def checkPushCart(self):
     d6 = Dice(1, 6)
     if self.inventory[len(self.inventory) - 1] == 'Pushcart':
         cartContents = {
             1: 'Tomaters',
             2: 'A Whole lotta Nuffin',
             3: 'Straw',
             4: 'Yer Dead',
             5: 'Dirt',
             6: 'Rocks'
         }
         roll = d6.roll()
         self.inventory[len(self.inventory) -
                        1] = f'Pushcart full o\' {cartContents.get(roll)}'
예제 #17
0
class Game():
    """
    Game class
    """
    def __init__(self):
        self.logger = logging.getLogger("Game")
        logging.basicConfig(
            format='%(asctime)s - %(name)s: %(levelname)s - %(message)s',
            level=logging.INFO)
        self.colors = ['red', 'white']
        self.init_game()

    def init_game(self):
        """
        Initialize the game
        """
        self.logger.info("Initializing Database")
        self.database = DatabaseHandler()
        self.questionHandler = QuestionHandler()
        self.dice = Dice(6)
        self.logger.info("Polishing Dice")
        self.logger.info("Starting Game - Welcome to trivial purfuit")

    def run(self):
        """
        Run loop for the game

        Raises:
            - sys.exit on keyboard interrupt
        """
        try:
            while (True):
                # simulate roll
                roll = self.dice.roll()
                self.logger.info("You rolled a {0}".format(roll))
                # simulate moving the piece
                self.logger.info("Moving your piece...")
                # simulate landing on a color
                color = random.choice(self.colors)
                self.logger.info("You landed on {0}".format(color))
                self.logger.debug("Selecting {0} question".format(color))
                # get a question from the color type
                question = self.database.select_color_question(color)
                # get an answer from the user
                answer = self.questionHandler.query_user(question)
                # evaluate the answer
                self.questionHandler.evaluate(question, answer)
                time.sleep(1)
        except KeyboardInterrupt:
            sys.exit()
예제 #18
0
class PokerApp:
    def __init__(self, interface):
        self.dice = Dice()
        self.money = 100
        self.interface = interface
        self.maxs = 100

    def run(self):
        while self.money >= 10 and self.interface.wantToPlay():
            self.playRound()
        self.interface.close()

    #玩一局
    def playRound(self):
        self.money = self.money - 10
        self.interface.setMoney(self.money)
        self.doRolls()
        result, score = self.dice.score()
        self.interface.showResult(result, score)
        self.money = self.money + score
        self.interface.setMoney(self.money)
        if (self.maxs < self.money):
            self.maxs = self.money
        self.interface.setMax(self.maxs)

    def doRolls(self):
        self.dice.rollAll()

        roll = 1
        self.interface.setDice(self.dice.values())
        toRoll = self.interface.chooseDice()
        while roll < 3 and toRoll != []:
            self.dice.roll(toRoll)
            roll = roll + 1
            self.interface.setDice(self.dice.values())
            if roll < 3:
                toRoll = self.interface.chooseDice()
예제 #19
0
 def checkIfFarmer(self):
     d8 = Dice(1, 8)
     if self.occupation == 'Farmer':
         farmerType = {
             1: 'Potato',
             2: 'Wheat',
             3: 'Turnip',
             4: 'Corn',
             5: 'Rice',
             6: 'Parsnip',
             7: 'Radish',
             8: 'Rutabaga'
         }
         roll = d8.roll()
         self.occupation = f'{farmerType.get(roll)} Farmer'
예제 #20
0
    def rollAbilities(self):
        abilities = {
            'Strength': 0,
            'Agility': 0,
            'Stamina': 0,
            'Personality': 0,
            'Intelligence': 0,
            'Luck': 0
        }
        dice = Dice(3, 6)

        for ability in abilities:
            abilities[ability] = dice.roll()

        return abilities
예제 #21
0
    def defend(self, damage_to_take: int):
        rng = Dice.roll()

        if rng < self._defense_rng:
            print("Clumsy attack! You miss!")
        elif rng < self._defense_rng:
            print("Opponent blocks your attack")
        else:
            damage_taken = self._armor - damage_to_take
            if damage_taken <= 0:
                print("Attack hits, but it cannot go through the armor")
            else:
                print(
                    f"Attack hits, and you manage to do {damage_taken} damage."
                )
                self._hp -= damage_taken
예제 #22
0
    def getTradeGoods(self):
        if self.occupation == 'Farmer':
            d6 = Dice(1, 6)
            animals = {
                1: 'Sheep',
                2: 'Goat',
                3: 'Cow',
                4: 'Duck',
                5: 'Goose',
                6: 'Mule'
            }
            return animals.get(d6.roll())

        with open('occupations.csv', 'r') as occupations:
            reader = csv.reader(occupations)
            for row in reader:
                if self.occupation == row[1].title().strip():
                    return row[3].title().strip()
예제 #23
0
def dice_menu():
    sides = raw_input(
        'Input number of sides or input "menu" to return to menu\n')

    if sides == "menu":
        init_game()
    else:
        rolls = raw_input('Number of rolls? (Default = 1)\n')
        # See if input is a number, throw error and have user try again if not
        try:
            if rolls == '':
                dice = Dice(sides)
            else:
                dice = Dice(sides, rolls)
            roll_result = dice.roll()
        except:
            print "Invalid User Input,\n"
            dice_menu()

        print "Result of {}d{}: {}".format(rolls, sides, roll_result)
        dice_menu()
예제 #24
0
from Dice import Dice

while True:
    a, b, c = Dice(6), Dice(6), Dice(6)
    s = [a.roll(), b.roll(), c.roll()]
    print(s)

    if s.count(s[0]) == 3:
        print('当たり!')
        break

예제 #25
0
from Dice import Dice

if __name__ == "__main__":
    # TODO remove the code below. The code below is scratch code. Not the actual main. That will be implemented later.
    print("Just a scratch")
    new_dice = Dice()
    roll_value = new_dice.roll()
    print("Let's roll the dice! \nYou rolled a {}".format(roll_value))
예제 #26
0
class GameScene:
    windowWidth = 0
    windowHeight = 0
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    YELLOW = (255, 255, 0)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    BlueXPos = 50
    RedXPos = 650
    LblYPos = 50
    inputString = ""
    num_chances = 1  #for now this will come through config file later

    DiceTextures = []

    def __init__(self, config=None, mode=None):
        self.config = config
        self.num_chances = int(config.get("Assignment", "num_Chances"))

        if mode == "auto":
            self.mode = mode
        else:
            self.mode = str(config.get("Assignment", "mode"))

        self.windowHeight = int(config.get("Assignment", "windowHeight"))
        self.windowWidth = int(config.get("Assignment", "windowWidth"))

        self._running = True
        self._gameOver = False
        self._display_surf = None
        self._rolling_dice = False
        self._startLoop = False
        self._outputSaved = False
        if self.mode != "auto":
            self._showInput = True
        else:
            self._showInput = False
        self.RedDiceResults = []
        self.BlueDiceResults = []
        self.MrRedWepons = []
        self.MrBlueWepons = []
        self.redPoints = 0
        self.bluePoints = 0

    #initialize the game
    def on_init(self):

        self.initPygame()
        self.loadResources()
        self.initScene()
        self._running = True

    def initPygame(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode(
            (self.windowWidth, self.windowHeight), pygame.HWSURFACE)
        pygame.display.set_caption('Battle MrRed Vs MrBlue')
        self.clock = pygame.time.Clock()
        self.timer = 0

    def loadResources(self):
        self.MrBlue_Texture = pygame.image.load(
            os.path.abspath(imgRes["mrBlueBody"]))
        self.MrRed_Texture = pygame.image.load(
            os.path.abspath(imgRes["mrRedBody"]))

        self.DiceTextures.append(
            pygame.image.load(os.path.abspath(imgRes["dice1Dot"])))
        self.DiceTextures.append(
            pygame.image.load(os.path.abspath(imgRes["dice2Dot"])))
        self.DiceTextures.append(
            pygame.image.load(os.path.abspath(imgRes["dice3Dot"])))
        self.DiceTextures.append(
            pygame.image.load(os.path.abspath(imgRes["dice4Dot"])))
        self.DiceTextures.append(
            pygame.image.load(os.path.abspath(imgRes["dice5Dot"])))
        self.DiceTextures.append(
            pygame.image.load(os.path.abspath(imgRes["dice6Dot"])))

        self.saveBtnTexture = pygame.image.load(
            os.path.abspath(imgRes["savebtn"]))

    def initScene(self):
        #Players
        self.MrRed = Player(self.MrRed_Texture, id="MrRed")
        self.MrBlue = Player(self.MrBlue_Texture, id="MrBlue")

        #Buttons
        self.SaveBtn = Button(self.saveBtnTexture)

        self.all_sprites_list = pygame.sprite.Group()

        self.all_Dice_list = pygame.sprite.Group()

        #fonts and texts
        self.weponFont = pygame.font.SysFont(None, 32)
        self.smallFont = pygame.font.SysFont(None, 20)

        for i in weponsList:  #self.MrBlue.wepons:
            self.MrRedWepons.append(
                self.weponFont.render(
                    str(i) + " " + str(self.MrBlue.wepons[i]), 1, self.WHITE))
            self.MrBlueWepons.append(
                self.weponFont.render(
                    str(i) + " " + str(self.MrRed.wepons[i]), 1, self.WHITE))

        self.RollButton = self.weponFont.render("Click anywhere to roll Dice",
                                                1, self.YELLOW)
        self.ResultText = self.weponFont.render(" ", 1, self.YELLOW)

        self.Instruction = self.smallFont.render(
            "once result is displayed, click on the save button to save the output and to exit the game anytime press \"Esc\"   ",
            1, self.YELLOW)

        self.RedPointText = self.weponFont.render(
            str(self.MrRed.calculatePoints()), 1, self.RED)
        self.BluePointText = self.weponFont.render(
            str(self.MrBlue.calculatePoints()), 1, self.BLUE)

        self.NumChancesText = self.weponFont.render(str(self.num_chances), 1,
                                                    self.YELLOW)

        self.DiceRed = Dice(self.DiceTextures)
        self.DiceBlue = Dice(self.DiceTextures)

        self.DiceBlue.randomize()
        self.DiceRed.randomize()

        self.setSpritePosition(self.MrBlue, [
            self.windowWidth / 2 -
            (self.MrBlue.rect.width * 1.25), self.windowHeight / 4
        ])
        self.setSpritePosition(self.MrRed,
                               [self.windowWidth / 2, self.windowHeight / 4])
        self.setSpritePosition(self.DiceBlue, [
            self.windowWidth / 2 -
            (self.MrBlue.rect.width * 1.25), self.windowHeight / 2
        ])
        self.setSpritePosition(self.DiceRed,
                               [self.windowWidth / 2, self.windowHeight / 2])

        self.setSpritePosition(self.SaveBtn, [
            self.windowWidth / 4 -
            (self.SaveBtn.rect.width * 1.25), self.windowHeight * 3 / 4
        ])

        self.all_sprites_list.add(self.MrBlue)
        self.all_sprites_list.add(self.MrRed)
        self.all_sprites_list.add(self.SaveBtn)
        self.all_Dice_list.add(self.DiceRed)
        self.all_Dice_list.add(self.DiceBlue)

    def setSpritePosition(self, _sprite, pos=[0, 0]):
        _sprite.rect.x = pos[0]
        _sprite.rect.y = pos[1]

    def on_loop(self):

        self.all_sprites_list.update()
        self.all_Dice_list.update()

        self.redPoints = self.MrRed.calculatePoints()
        self.bluePoints = self.MrBlue.calculatePoints()

        if self.num_chances == 0 or self.detectAnybodyLostAllWepons():
            self._gameOver = True
            self._startLoop = False
            self.calculateResults()

        if self._gameOver == False and self._showInput == True:
            self.num_chances = self.askQuestion(
                self._display_surf,
                "How many times do you want to roll the dice?", self.YELLOW,
                self.BLUE)
            if (self.num_chances == 0):
                self.num_chances = int(
                    self.config.get("Assignment", "num_Chances"))
        if self._gameOver == False and self._startLoop == True:
            if self._rolling_dice == False:
                self.timer += self.clock.get_time()
                if self.timer >= 1200:
                    self.animateDices()
            else:
                self.timer += self.clock.get_time()
                if self.timer >= 500:
                    self.stopDiceAnimations()

        for event in pygame.event.get():
            #quit if the quit button was pressed
            if event.type == pygame.QUIT:
                self._running = False
                exit()

            if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                if self._gameOver:
                    x, y = event.pos
                    if self.SaveBtn.rect.collidepoint(x, y):
                        self.writeResultToFile()
                else:
                    self._startLoop = True
                    self.outputToWrite = "No of Chances= " + str(
                        self.num_chances)
                    self.timer = 0
                    self.RollDices(num_chances=self.num_chances)

        pass

    def stopDiceAnimations(self):

        self._rolling_dice = False
        self.DiceRed.stopAnimationAtValue(
            self.RedDiceResults[self.num_chances - 1])
        self.DiceBlue.stopAnimationAtValue(
            self.BlueDiceResults[self.num_chances - 1])

        #time.sleep(1.5)
        self.DoAction(self.MrBlue, self.RedDiceResults[self.num_chances - 1])
        self.DoAction(self.MrRed, self.BlueDiceResults[self.num_chances - 1])

        self.redPoints = self.MrRed.calculatePoints()
        self.bluePoints = self.MrBlue.calculatePoints()
        #self.outputToWrite+= "\n chance=> "+ str(self.num_chances)+"  Dice Blue: "+str(self.BlueDiceResults[self.num_chances-1])+"  Dice Red: "+str(self.RedDiceResults[self.num_chances-1])+" Mr Blue Scored: "+ str(self.bluePoints)+" and Mr Red Scored: "+str(self.redPoints)
        self.generateOutput()
        self.num_chances -= 1
        self.timer = 0

    def animateDices(self):

        self.DiceRed.startAnimation()
        self.DiceBlue.startAnimation()
        self._rolling_dice = True
        self.timer = 0

    def RollDices(self, num_chances=3):

        self.RedDiceResults = self.DiceRed.roll(num_chances)
        self.BlueDiceResults = self.DiceBlue.roll(num_chances)

    def DoAction(self, player, weponid):
        #for i in DiceResult:
        player.removeWepon(weponsList[weponid - 1])

    def on_render(self):
        self._display_surf.fill((0, 0, 0))
        self.all_sprites_list.draw(self._display_surf)

        self.renderWepons(self.MrBlue, self.MrBlueWepons, self.BlueXPos)
        self.renderWepons(self.MrRed, self.MrRedWepons, self.RedXPos)

        self.RedPointText = self.weponFont.render(str(self.redPoints), 1,
                                                  self.RED)
        self.BluePointText = self.weponFont.render(str(self.bluePoints), 1,
                                                   self.BLUE)

        self._display_surf.blit(
            self.RedPointText,
            (self.windowWidth * 2 / 3, self.windowHeight / 8))
        self._display_surf.blit(self.BluePointText,
                                (self.windowWidth / 3, self.windowHeight / 8))

        self.NumChancesText = self.weponFont.render(
            "Remainig rolls: " + str(self.num_chances), 1, self.YELLOW)
        if self._rolling_dice == True:
            self.RollButton = self.weponFont.render(
                "Please wait untill game is over ", 1, self.YELLOW)

        self._display_surf.blit(
            self.NumChancesText,
            (self.windowWidth / 4, self.windowHeight * 4 / 5))

        self._display_surf.blit(self.Instruction,
                                (10, self.windowHeight * 13 / 14))

        self.all_Dice_list.draw(self._display_surf)

        if self._gameOver:
            self._display_surf.blit(
                self.ResultText,
                (self.windowWidth / 4, self.windowHeight * 7 / 8))
        else:
            self._display_surf.blit(
                self.RollButton,
                (self.windowWidth / 3, self.windowHeight * 7 / 8))

        pygame.display.update()
        self.clock.tick(60)
        pygame.display.flip()

    def detectAnybodyLostAllWepons(self):
        if self.bluePoints < 2 or self.redPoints < 2:
            return True
        else:
            return False

    def calculateResults(self):

        if self.redPoints != self.bluePoints:
            if self.redPoints > self.bluePoints:
                self.ResultText = self.weponFont.render(
                    "Mr Red Wins ", 1, self.YELLOW)
                return 1
            else:
                self.ResultText = self.weponFont.render(
                    "Mr Blue Wins ", 1, self.YELLOW)
                return 0
        else:
            self.ResultText = self.weponFont.render(" Its a Tie ", 1,
                                                    self.YELLOW)
            return None

    def renderInput(self):
        print("this is to take input from user")

    def generateOutput(self):
        i = self.calculateResults()
        if self._gameOver:
            self.outputToWrite += "\n overall"
        else:
            self.outputToWrite += "\n chance=> " + str(self.num_chances)
            self.outputToWrite += "  Dice Blue: " + str(self.BlueDiceResults[
                self.num_chances - 1]) + "  Dice Red: " + str(
                    self.RedDiceResults[self.num_chances - 1])
            self.outputToWrite += " Mr Blue Scored: " + str(
                self.bluePoints) + " and Mr Red Scored: " + str(self.redPoints)

        if i == 1:
            self.outputToWrite += " winner is Mr Red"
        elif i == 0:
            self.outputToWrite += " winner is Mr Blue "
        else:
            self.outputToWrite += " its a tie "

    def writeResultToFile(self):
        if self._outputSaved == False:
            self.generateOutput()
            self._outputSaved = True

        #print("This prints result of the game into output file")
        file_path = os.path.abspath(outputFile)
        if os.path.exists(file_path):
            f = open(file_path, "w")
            f.write(self.outputToWrite)
        else:
            f = open(file_path, "w")
            f.write(self.outputToWrite)

    def renderWepons(self, player, weponlist, xPos):
        counter = 0
        for i in weponlist:
            if player.wepons[weponsList[counter]] != 0:
                self._display_surf.blit(weponlist[counter],
                                        (xPos, self.LblYPos + (35 * counter)))
            counter += 1

    def on_cleanup(self):

        pygame.quit()

    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        while (self._running):
            pygame.event.pump()
            keys = pygame.key.get_pressed()
            if (keys[pygame.K_ESCAPE]):
                self._running = False

            self.on_loop()
            self.on_render()
            self.clock.tick(60)
        self.on_cleanup()

    def popup(self, screen, message, width, height, x, y, bgcolor, textColor):
        #Display a popup box in the middle of the screen
        #This popup will only disappear when the user presses the Return key

        fontobject = pygame.font.Font(None, 18)
        pygame.draw.rect(screen, bgcolor,
                         (x - width / 2 + 2, y - height / 2 + 2, 300, 36), 0)
        pygame.draw.rect(screen, self.WHITE,
                         (x - width / 2, y - height / 2, 304, 40), 1)
        if len(message) != 0:
            screen.blit(fontobject.render(message, 1, textColor),
                        (x - width / 2 + 10, y - height / 2 + 14))
            pygame.display.flip()

    def askQuestion(self,
                    screen,
                    question,
                    bgColor,
                    textColor,
                    width=300,
                    height=40,
                    x=-1,
                    y=-1):
        #width, height, x, y, bgColor and textColor are optional arguments
        #When x and y are omitted, use the centre of the screen
        if x == -1:
            x = screen.get_width() / 2
        if y == -1:
            y = screen.get_height() / 2

        pygame.font.init()
        current_string = ""
        self.popup(self._display_surf,
                   question + ": " + "".join(current_string), width, height, x,
                   y, bgColor, textColor)

        while self._showInput:
            inkey = self.getKey()
            if inkey == pygame.K_BACKSPACE:
                current_string = current_string[0:-1]
            elif inkey == pygame.K_RETURN:
                self._showInput = False
            elif inkey <= 255:
                if (inkey >= 48 and inkey <= 57):
                    current_string += chr(inkey)
            self.popup(screen, question + ": " + "".join(current_string),
                       width, height, x, y, bgColor, textColor)

        return int(current_string)

    def getKey(self):
        while 1:
            event = pygame.event.poll()
            if event.type == pygame.KEYDOWN:
                return event.key
            else:
                pass
예제 #27
0
파일: OFTF.py 프로젝트: aessek/OFTF
class OFTF:
    def __init__(self):
        self.dice = Dice()
        self.score = 0
        self.saved_dice = []
        self.thrown_dice = []
        self.qualified = False
        self.results = 0

    def save_dice(self, dice):
        '''
        Adds the dice to your saved stack and removes it from the current throw
        '''
        for di in dice:
            self.saved_dice.append(di)
            self.thrown_dice.remove(di)

        return self

    def pick_highest(self, multiple=False):
        '''
        Finds the highest dice and selects it from the list of available dice. 
        If multiple is set to True, then if there are multiple of the determined
        highest dice, then it will grab all of them. E.g., it will grab three 6's
        instead of just one.
        '''
        picked_dice = []
        biggest = self.thrown_dice[0]

        if len(self.thrown_dice) is not 1:
            for i in range(len(self.thrown_dice) - 1):
                next_dice = self.thrown_dice[i + 1]
                if (next_dice > biggest):
                    biggest = next_dice

        if multiple is True:
            for _ in range(self.thrown_dice.count(biggest)):
                picked_dice.append(biggest)
        else:
            picked_dice.append(biggest)

        return picked_dice

    def get_results(self, dice):
        '''
        Get the score of the saved dice. The qualifying 1 and 4 are not counted. 
        If the player does not qualify the score is 0. 
        '''
        result = 0
        if dice is None:
            dice = self.saved_dice

        if 1 in dice and 4 in dice:
            while len(dice) is not 0:
                result = result + dice.pop()

            result = result - 5  # subtract 5 for the 1 and 4 when qualified

        self.results = result
        return result

    def play(self):

        while len(self.saved_dice) is not 6:
            self.thrown_dice = self.dice.roll(6 - len(self.saved_dice))

            # Look for a one or four, take one and roll again
            if self.qualified is False:
                if 1 in self.thrown_dice and 1 not in self.saved_dice:
                    self.save_dice([1])

                if 4 in self.thrown_dice and 4 not in self.saved_dice:
                    self.save_dice([4])

            # Get the biggest dice in the roll
            if 6 in self.thrown_dice:
                biggest = self.pick_highest(True)
                self.save_dice(biggest)
            elif len(self.thrown_dice) is not 0:
                biggest = self.pick_highest()
                self.save_dice(biggest)

            # Are we qualified?
            if 1 in self.saved_dice and 4 in self.saved_dice:
                self.qualified = True

        self.get_results(self.saved_dice)
예제 #28
0
from Dice import Dice
import time

d1 = Dice(6)
d2 = Dice(6)
d3 = Dice(6)

while True:
    list = [d1.roll(), d2.roll(), d3.roll()]

    print(list)

    time.sleep(.3)

    if (list[0] == list[1] and list[1] == list[2]):
        print("当たり!")
        break
예제 #29
0
class PokerApp:
    def __init__(self):
        self.money = 100
        self.numberOfGames = 0
        self.dice = Dice()
        self.interface = PokerInterface(self.money)

    def run(self):
        self.interface.updateScreen()

        while self.money >= 10 and self.interface.askIfWantToPlay():
            self.numberOfGames += 1

            self.doRoll()

            result, score = self.dice.getCategory()

            self.money += score
            self.interface.updateMoney(self.money)
            self.interface.showResults(result, score)

        self.verifyLeaderboardPosition()
        self.interface.close(self.numberOfGames)

    def doRoll(self):
        self.money -= 10
        self.interface.updateMoney(self.money)
        self.interface.messageTicketOutlay()

        rolls = 1

        self.dice.rollAll()
        diceValues = self.dice.getValues()
        self.interface.updateDiceValues(diceValues)

        while rolls < 3:
            rolls += 1

            diceToRoll = self.interface.chooseDice()

            if diceToRoll == []:
                break
            else:
                self.dice.roll(diceToRoll)
                diceValues = self.dice.getValues()
                self.interface.updateDiceValues(diceValues)

    def verifyLeaderboardPosition(self):
        path = "E:/Diego/ComputerScience/Programming/Training Projects/Python/Introduction to Python/Classes/DicePokerV2/highestScores.txt"
        highestScoreFile = open(path, "r")

        self.highestScores = self.getHighestScoresFrom(highestScoreFile)

        for i in range(10):
            if self.money > self.highestScores[i][1]:
                self.username = self.askForUsername()
                self.updateLeaderboardList()
                break

        self.highestScores.sort(key=self._userScore, reverse=True)
        self.reduceLeaderboardListToTen()

        highestScoreFile.close()
        highestScoreFile = open(path, "w")

        for userData in self.highestScores:
            print("{}, {}".format(userData[0], userData[1]),
                  file=highestScoreFile)

        highestScoreFile.close()

    def getHighestScoresFrom(self, file):
        highestScores = []
        for userData in file:
            username, score = userData.split(", ")
            highestScores.append([username, int(score)])

        return highestScores

    def askForUsername(self):
        return input("\n You've got a new record! Enter your username: ")

    def updateLeaderboardList(self):
        userFound = False

        for i in range(10):
            if self.username == self.highestScores[i][0]:
                userFound = True

                if self.money > self.highestScores[i][1]:
                    self.highestScores[i][1] = self.money

                break

        if not userFound:
            self.highestScores.append([self.username, self.money])

    def _userScore(self, userData):
        return userData[1]

    def reduceLeaderboardListToTen(self):
        for i in range(len(self.highestScores) - 10):
            self.highestScores.pop()
예제 #30
0
from Dice import Dice

dice_1 = Dice(6)
dice_2 = Dice(6)
dice_3 = Dice(6)

while True:
    a = dice_1.roll()
    b = dice_2.roll()
    c = dice_3.roll()
    print([a, b, c])
    if a == b == c:
        print('当たり!')
        break
예제 #31
0
 def getBirthAugrandLuckyRoll(self):
     table = luckScoreTable
     die = Dice(1, 30)
     return table.table.get(die.roll())
예제 #32
0
 def rollEquipment(self):
     eqt = equipmentTable()
     die = Dice(1, 24)
     return eqt.rollTable.get(die.roll())
예제 #33
0
 def rollCoppahs(self):
     dice = Dice(5, 12)
     return dice.roll()