Example #1
0
    def __init__(self):
        """"Class Constructor: will inizialite a dictionary and the num_throws to count
         the amount of times he is going to throw it"""

        self.keep_playing = True
        self.guess = True
        self.dealer = Dealer()
        self.score = 300
Example #2
0
 def __init__(self):
     self.points = 0
     self.keep_playing = True
     self.user_H_L_choice = ""
     self.play_again = True
     self.get_choice = ""
     self.dealer = Dealer()
     self.highscore = Highscore()
Example #3
0
 def __init__(self):
     """The class constructor.
     
     Args:
         self (Director): an instance of Director.
     """
     self.keep_playing = True
     self.score = 300
     self.dealer = Dealer()
Example #4
0
class Director:
    def __init__(self):
        self.playerScore = 300
        self.current_card = 0
        self.next_card = 0
        self.dealer = Dealer()
        self.keepPlaying = True

    def startGame(self):
        # Jeremy does this one
        while (self.keepPlaying):
            self.current_card = self.dealer.drawCard()
            print("The card is: " + str(self.current_card))
            guess = self.getInput()
            self.next_card = self.dealer.drawCard()
            print("Next card was: " + str(self.next_card))
            self.doUpdates(guess)
            print("Your score is: " + str(self.playerScore))
            self.keepPlaying = self.getKeepPlaying()
            print("")

    def getInput(self):
        #mikaela does this
        guess_1 = input("Higher or Lower? [h/l]: ")
        return guess_1

    def doUpdates(self, guess):
        #Abram
        if self.current_card < self.next_card and guess == "h":
            self.playerScore += 100
        elif self.current_card < self.next_card and guess == "l":
            self.playerScore -= 75
        elif self.current_card > self.next_card and guess == "l":
            self.playerScore += 100
        elif self.current_card > self.next_card and guess == "h":
            self.playerScore -= 75

    def getKeepPlaying(self):
        #Samson
        valid = False
        while not valid:
            text = input("Keep playing? [y/n]: ")
            if isinstance(text, str):
                prompt = text.lower()
                if prompt == "n":
                    valid = True
                    return False

                elif prompt == "y":
                    valid = True
                    return True
                else:
                    valid = False
                    print(
                        "Error: Please enter y/n to keep playing or stop playing."
                    )
    def __init__(self,
                 chat_id: int,
                 user_id: int,
                 lang_id: str,
                 first_name: str,
                 game_handler: object,
                 message_id: int,
                 send_message: callable,
                 multiplayer: bool = None,
                 game_id: str = None):
        # declare variables and set initial values
        self.players = []
        self.chat_id = chat_id
        self.__game_id = game_id
        self.lang_id = lang_id
        self.deck = CardDeck(lang_id)
        # TODO language of the cards & dealer cannot be changed
        # TODO especially with new multiplayer important!
        self.dealer = Dealer(translate("dealerName", lang_id), self.deck)
        self.game_running = False
        self.current_player = 0
        self.game_handler = game_handler
        self.send_message = send_message
        self.logger = logging.getLogger(__name__)

        if multiplayer:
            self.game_type = self.MULTIPLAYER_GAME
            chat_id = 0
        elif chat_id >= 0:
            self.game_type = self.PRIVATE_CHAT
        else:
            self.game_type = self.GROUP_CHAT

        one_more_button = KeyboardButton(
            translate("keyboardItemOneMore", lang_id))
        no_more_button = KeyboardButton(
            translate("keyboardItemNoMore", lang_id))
        stop_button = KeyboardButton(translate("keyboardItemStop", lang_id))
        self.keyboard_running = ReplyKeyboardMarkup(
            keyboard=[[one_more_button, no_more_button], [stop_button]],
            selective=True)

        self.add_player(user_id, first_name, message_id, silent=True)

        # Only send a "Please join the game" message, when it's a group chat
        if self.game_type == self.GROUP_CHAT:
            keyboard = [[
                InlineKeyboardButton(text=translate("join",
                                                    self.lang_id).capitalize(),
                                     callback_data="join_game")
            ]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            send_message(chat_id,
                         translate("newRound", lang_id),
                         message_id=message_id,
                         reply_markup=reply_markup)
        elif self.game_type == self.MULTIPLAYER_GAME:
            pass
        else:
            self.start_game()
Example #6
0
 def __init__(self, num_seats: int, _id: int,
              dealer_delegate: DealerDelegate):
     self._seats: [_Seat] = [_Seat(i) for i in range(num_seats)]
     self._players: {int: Player} = self._load_players(_id)
     self._id = _id
     self.dealer = Dealer(self, dealer_delegate)
     self.button_position = 0
     self.point = None
Example #7
0
    def __init__(self, app):
        self.app          = app
        self.bg_image     = app.loader.load_image("bg.png")
        self.card_sprites = [ app.loader.load_image("card-%02x.png" % (x+1)) for x in range(13)]
        self.card_empty   = app.loader.load_image("card-empty.png")
        self.card_down    = app.loader.load_image("card-down.png")
        self.card_hint    = app.loader.load_image("card-hint.png")
        self.font         = app.loader.load_ttf("liberation-sans.ttf", 15)

        self.snd_capable = app.sound_capable
        self.snd_enabled = True
        self.snd_samples = [
                app.loader.load_wav("click-deal.wav"),
                app.loader.load_wav("click-pick-up.wav"),
                app.loader.load_wav("click-put-down.wav"),
                app.loader.load_wav("hint.wav"),
                app.loader.load_wav("no-hint.wav"),
                app.loader.load_wav("win.wav")
                ]

        # game structures
        self.columns   = [ Column(self.card_empty, self.card_hint) for x in range(10)]
        self.dealer    = Dealer(self.card_sprites, self.card_hint, self.card_down)
        self.done_pile = DonePile(self.card_sprites)
        self.undo      = Undo(self)
        self.fireworks = FireworkScreen(self)
        self.game_over = False

        # helper systems
        self.automator = Game.Automator(app)
        self.hints     = None 
        self.score_box = Game.ScoreBox(self.app.screen, self.font)
        
        self.drag_cards       = None
        self.drag_from_column = None
        self.drag_xoffs       = 0
        self.drag_yoffs       = 0
        self.drag_xpos        = 0
        self.drag_ypos        = 0
        self.drag_gap         = 0

        self.over      = -1
        self.over_card = None
        self.over_gap  = 0

        self.hover_cards = None
        self.hover_xpos  = 0
        self.hover_ypos  = 0

        self.run_over_card = None
Example #8
0
    def __init__(self, chat_id, user_id, lang_id, first_name, game_handler,
                 message_id, send_message):
        # declare variables and set initial values
        self.players = []
        self.join_message_ids = []
        self.chat_id = chat_id
        self.lang_id = lang_id
        self.deck = CardDeck(
            lang_id)  # TODO language of the cards & dealer cannot be changed
        self.dealer = Dealer(translate("dealerName", lang_id), self.deck)
        self.game_running = False
        self.current_player = 0
        self.game_handler = game_handler
        self.send_message = send_message
        self.logger = logging.getLogger(__name__)

        if chat_id >= 0:
            self.game_type = self.PRIVATE_CHAT
        else:
            self.game_type = self.GROUP_CHAT

        one_more_button = KeyboardButton(
            translate("keyboardItemOneMore", lang_id))
        no_more_button = KeyboardButton(
            translate("keyboardItemNoMore", lang_id))
        stop_button = KeyboardButton(translate("keyboardItemStop", lang_id))
        self.keyboard_running = ReplyKeyboardMarkup(
            keyboard=[[one_more_button, no_more_button], [stop_button]],
            selective=True)

        self.add_player(user_id, first_name, message_id, silent=True)

        # Only send a "Please join the game" message, when it's a group chat
        if self.game_type == self.GROUP_CHAT:
            send_message(
                chat_id, translate("newRound", lang_id),
                message_id=message_id)  # keyboard=self.keyboard_not_running
        else:
            self.start_game()
Example #9
0
class Director:

    def __init__(self):
        self.keep_playing = True
        self.score = 300
        self.dealer = Dealer()
        self.current_card = 0

    def start_game(self):
        while self.keep_playing:
            #self.get_inputs()
            #self.do_updates()
            self.do_outputs()

    def get_inputs(self):
        self.dealer.deal_card()

    def do_updates(self):
        points = self.dealer.get_points()
        self.score += points

    def do_outputs(self):
        if len(self.dealer.cards) == 13:
            self.current_card = self.dealer.deal_card()
        print(f"The card is: {self.current_card}")
        if self.dealer.can_deal() and self.score != 0:
            choice = input("Higher or lower? [h/l] ")
            new_card = self.dealer.deal_card()
            if (choice == "h" and new_card > self.current_card) or (choice == "l" and new_card < self.current_card):
                self.score += 100
            elif (choice == "h" and new_card < self.current_card) or (choice == "l" and new_card > self.current_card):
                self.score -= 75
            else:
                print("That wasn't an option. You lose 200 points.")
                self.score -= 200
            print(f"Next card was: {new_card}")
            print(f"Your score is: {self.score}")
            self.current_card = new_card
            play_more = input("Draw again? [y/n] ")
            self.keep_playing = (play_more == "y")
        else:
            self.keep_playing = False
Example #10
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to keep track of the score and control the 
    sequence of play.
    
    Attributes:
        keep_playing (boolean): Whether or not the player wants to keep playing.
        score (number): The total number of points earned.
        thrower (Thrower): An instance of the class of objects known as Thrower.
    """
    def __init__(self):
        """The class constructor.
        
        Args:
            self (Director): an instance of Director.
        """
        self.keep_playing = True
        self.score = 300
        self.dealer = Dealer()

    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        while self.keep_playing:
            self.get_inputs()
            self.do_updates()
            self.do_outputs()

    def get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means throwing the dice.

        Args:
            self (Director): An instance of Director.
        """
        self.dealer.draw_card()

    def do_updates(self):
        """Updates the important game information for each round of play. In 
        this case, that means updating the score.

        Args:
            self (Director): An instance of Director.
        """
        print(f"\nThe card was: {self.dealer.card}")
        choice1 = input("Higher or lower? [h/l] ")
        points = self.dealer.get_points(choice1)
        self.score += points

    def do_outputs(self):
        """Outputs the important game information for each round of play. In 
        this case, that means the dice that were rolled and the score.

        Args:
            self (Director): An instance of Director.
        """
        print(f"Next card was: {self.dealer.card}")
        if (self.dealer.right_v_wrong):
            print(Fore.GREEN + f"Your score is: {self.score}" +
                  Style.RESET_ALL)
        else:
            print(Fore.RED + f"Your score is: {self.score}" + Style.RESET_ALL)
        if self.dealer.can_shuffle(self.score):
            choice2 = input("Keep playing? [y/n] ")
            self.keep_playing = (choice2 == "y")
        else:
            print("Better luck next time!\n")
            self.keep_playing = False
Example #11
0
class Director:

    # ********************** Will inizialite the game
    def __init__(self):
        """"Class Constructor: will inizialite a dictionary and the num_throws to count
         the amount of times he is going to throw it"""

        self.keep_playing = True
        self.guess = True
        self.dealer = Dealer()
        self.score = 300

    # ********************** Start Game
    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): an instance of Director.
        """
        while self.keep_playing:
            self.get_inputs()
            self.do_outputs()
            self.do_updates()

    # ********************** Get imputs
    def get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means throwing the cards.
        """

        self.dealer.deal_cards()

    # ********************** do outputs
    def do_outputs(self):
        """Outputs the important game information for each round of play. In 
        this case, that means the dealer will get a card and do the score 

        """
        print(f"\nThe Card is : {self.dealer.cards[0]}")
        self.dealer.guess()

        # ********************** Do updates

    def do_updates(self):
        """Updates the important game information for each round of play. In 
        this case, that means updating the score.
        """

        print(f"Next Card was : {self.dealer.cards[1]}")

        self.score = self.dealer.get_points()

        print(f"Your score is {self.score}")

        if self.dealer.can_deal():
            choice = input("Keep playing? [y/n] ")
            if choice == "n":
                print("Thanks for playing have a nice day")
            self.keep_playing = (choice == "y")
        else:

            self.keep_playing = False
            print("You Lost but Thanks for Playing!!")
Example #12
0
# TODO: Add entry point code here
# Test comment from Bro. Lythgoe

from game.dealer import Dealer
#This imports the dealer class
dealer = Dealer()
#This initializes the dealer class
dealer.play_game()
#This calls the function in the dealer class to start playing the game
Example #13
0
 def __init__(self):
     self.keep_playing = True
     self.score = 300
     self.dealer = Dealer()
     self.current_card = 0
Example #14
0
def initialise_game(room):
    numPlayers = len(rooms[room])
    players = Players(numPlayers)
    dealer = Dealer()
    dealer.initialiseCards()
    dealer.shuffleCards()
    dealer.distributeCards(players.players)
    for ((username, p_roomid), player) in zip(rooms[room], players.players):
        player.name = username
        player.pRoomId = p_roomid
        player.roomId = room

    socketio.emit('game_data', players.json_game_data(), room=room)
    socketio.emit('player_data', player.json_player_data(), room=p_roomid)

    # for ((username, p_roomid), player) in zip(rooms[room], players.players):
    # emit('player_data', player, room=id)
    # socketio.emit('game_data',json_game_data(players,dealer), room = room)

    playerChance = 0
    player = players.players[playerChance]
    while (not player.hasWon()):
        print('+++++++++++++++++++++++++++++')
        print(f'Player - {player.id}')
        player.sendMessageToAll(f"It's {player.name}'s turn.", socketio)
        print('+++++++++++++++++++++++++++++')
        player.chance = True
        # p_roomid = rooms[room][playerChance][1]
        # socketio.emit('player_data',json_player_data(player,dealer), room = player.pRoomId)
        # print(player.handCards,player.propertyCollection, player.bankCollection)
        player.drawCards(dealer)
        player.chanceNo = 1

        socketio.emit('player_data',
                      player.json_player_data(),
                      room=player.pRoomId)
        socketio.emit('game_data', players.json_game_data(), room=room)

        print(len(dealer.drawPile), len(player.handCards))
        while player.chanceNo <= player.cardsToPlay:
            val = player.playCard(
                socketio=socketio, dealer=dealer,
                players=players)  #TODO check the value of val
            # player.clearMessage(socketio)
            if val == -1:
                break
            # player.chanceNo +=1  Will increase this in the lower functions
            socketio.emit('player_data',
                          player.json_player_data(),
                          room=player.pRoomId)
            socketio.emit('game_data', players.json_game_data(), room=room)

        if len(player.handCards) > 7:
            player.discardCards(dealer.drawPile, socketio)
            socketio.emit('player_data',
                          player.json_player_data(),
                          room=player.pRoomId)
            socketio.emit('game_data', players.json_game_data(), room=room)

        if player.hasWon():
            player.sendMessageToAll(f"{player.name} has won the game.",
                                    socketio)
            socketio.emit('new_game', room=room)
            print('***************************************')
            print(f'Player - {player.id} has won the game.')
            print('***************************************')
            break

        player.chance = False
        socketio.emit('player_data',
                      player.json_player_data(),
                      room=player.pRoomId)

        playerChance = (playerChance + 1) % numPlayers
        player = players.players[playerChance]
Example #15
0
class Game:

    class ScoreBox:
        def __init__(self, screen, font):
            self.screen = screen
            self.font   = font
            self.color  = (255,255,255)
            self.reset()
        
        def reset(self):
            self.move_count = 0
            self.score      = 500
            self._render()

        def _render(self): 
            self.score_text_surface = self.font.render("Score: %d"%self.score, True, self.color)
            self.moves_text_surface = self.font.render("Moves: %d"%self.move_count, True, self.color)

        def inc_score(self):
            self.score += 100
            self._render()

        def inc_moves(self):
            self.score      -= 1
            self.move_count += 1
            self._render()

        def is_over(self, px, py):
            box_w = 200
            box_h = CARD_HEIGHT
            xpos = (self.screen.get_width() - box_w) / 2
            ypos = self.screen.get_height() - PADDING - box_h

            if px < xpos or py < ypos:
                return False

            if px >= xpos+box_w or py >= ypos+box_h:
                return False

            return True

        def draw(self, screen):

            box_w = 200
            box_h = CARD_HEIGHT
            xpos = (screen.get_width() - box_w) / 2
            ypos = screen.get_height() - PADDING - box_h
            pg.draw.rect(
                    screen,
                    (0,150,0),
                    (xpos, ypos, box_w, box_h))

            pg.draw.rect(
                    screen,
                    (0,50,0),
                    (xpos, ypos, box_w, box_h),
                    1)

            screen.blit(
                    self.score_text_surface,
                    (xpos + 55, ypos + 25))

            screen.blit(
                    self.moves_text_surface,
                    (xpos + 55, ypos + 55))

    class Hinter:
        def __init__(self, game, columns):
            self.app      = game.app
            self.game     = game
            self.columns  = columns
            self.hints    = []
            self.hint_pos = 0

            for from_column in self.columns:

                longest_run_card = from_column.longest_run()
                if not longest_run_card:
                    continue

                for to_column in self.columns:
                    if from_column == to_column:
                        continue
                    
                    if to_column.can_card_be_pushed(longest_run_card):
                        self.hints.append((from_column, longest_run_card, to_column))
            
            # TODO: sort these...
            self.flash_next()


        def flash_next(self):
            if len(self.hints) == 0:
                self.game.snd_play(SND_NO_HINT)
                return

            from_column = self.hints[self.hint_pos][0]
            from_card   = self.hints[self.hint_pos][1]
            to_column   = self.hints[self.hint_pos][2]
            self.hint_pos = (self.hint_pos+1)%len(self.hints)

            def flash_stop():
                to_column.set_hint(None)
                self.app.repaint() 

            def flash_to():
                from_column.set_hint(None);
                to_column.hint_last_card()
                self.app.set_callback(30, flash_stop)
                self.app.repaint()

            self.game.snd_play(SND_HINT)

            from_column.set_hint(from_card)
            self.app.set_callback(30, flash_to)
            self.app.repaint()

    class Automator:
        def __init__(self, app):
            self.animator_stack = []
            self.app = app

        def _tick(self):
            def next_tick():
                self._tick()
            
            anim = self.animator_stack[-1]
            anim.tick();

            if anim.has_ended(): 
                self.animator_stack = self.animator_stack[0:(len(self.animator_stack)-1)]
            else:
                self.app.set_callback(2, next_tick)

        def is_active(self):
            return len(self.animator_stack) > 0

        def push_animator(self, anim):
            def tick_callback():
                self._tick()

            self.animator_stack.append(anim)
            self.app.set_callback(2, tick_callback)


    def __init__(self, app):
        self.app          = app
        self.bg_image     = app.loader.load_image("bg.png")
        self.card_sprites = [ app.loader.load_image("card-%02x.png" % (x+1)) for x in range(13)]
        self.card_empty   = app.loader.load_image("card-empty.png")
        self.card_down    = app.loader.load_image("card-down.png")
        self.card_hint    = app.loader.load_image("card-hint.png")
        self.font         = app.loader.load_ttf("liberation-sans.ttf", 15)

        self.snd_capable = app.sound_capable
        self.snd_enabled = True
        self.snd_samples = [
                app.loader.load_wav("click-deal.wav"),
                app.loader.load_wav("click-pick-up.wav"),
                app.loader.load_wav("click-put-down.wav"),
                app.loader.load_wav("hint.wav"),
                app.loader.load_wav("no-hint.wav"),
                app.loader.load_wav("win.wav")
                ]

        # game structures
        self.columns   = [ Column(self.card_empty, self.card_hint) for x in range(10)]
        self.dealer    = Dealer(self.card_sprites, self.card_hint, self.card_down)
        self.done_pile = DonePile(self.card_sprites)
        self.undo      = Undo(self)
        self.fireworks = FireworkScreen(self)
        self.game_over = False

        # helper systems
        self.automator = Game.Automator(app)
        self.hints     = None 
        self.score_box = Game.ScoreBox(self.app.screen, self.font)
        
        self.drag_cards       = None
        self.drag_from_column = None
        self.drag_xoffs       = 0
        self.drag_yoffs       = 0
        self.drag_xpos        = 0
        self.drag_ypos        = 0
        self.drag_gap         = 0

        self.over      = -1
        self.over_card = None
        self.over_gap  = 0

        self.hover_cards = None
        self.hover_xpos  = 0
        self.hover_ypos  = 0

        self.run_over_card = None

    def _draw_bg(self):

        s_width   = self.app.screen.get_width()
        s_height  = self.app.screen.get_height()
        bg_width  = self.bg_image.get_width()
        bg_height = self.bg_image.get_height()

        y = 0
        while y < s_height:
            x = 0
            while x < s_width:
                self.app.screen.blit(self.bg_image, (x, y))
                x += bg_width
            y += bg_height

    def _next_hint(self):
        for c in self.columns:
            c.set_hint(None)

        if self.hints:
            self.hints.flash_next()
        else:
            self.hints = Game.Hinter(
                    self,
                    self.columns)
    
    def set_hover_cards(self, cards):
        if not cards:
            self.hover_cards = None
        elif type(cards) is Card:
            self.hover_cards = [cards]
        elif type(cards) is list: 
            self.hover_cards = cards
        else:
            raise BaseException("Game.Automator#set_hover_cards: Unknown type '%s'"%type(cards))

    def set_hover_pos(self, xpos, ypos):
        self.hover_xpos = xpos
        self.hover_ypos = ypos

    def resize(self):
        step = self.app.screen.get_width() / float(len(self.columns))
        xpos = (step - CARD_WIDTH) / 2.0
        for c in self.columns:
            c.set_pos(xpos)
            xpos += step

        self.dealer.set_pos(self.app.screen)

    def reset(self):
        self.dealer.reset()

        for i in range(0, 44):
            self.columns[i%len(self.columns)].push(self.dealer.next_card())

        
        self.automator.push_animator(Dealer.DealAnimator(self))
        #self.dealer.deal(self.app.screen, self.columns)

    def mouse_move(self, xp, yp):

        self.drag_xpos = xp
        self.drag_ypos = yp

        if self.automator.is_active() or self.game_over:
            return

        self.over = -1
        for i in range(0, len(self.columns)):
            if self.columns[i].is_point_over(xp, yp):
                self.over = i
                break

        if self.over == -1:
            self.over_card = None
            self.run_over_card = None

        else:
            self.over_gap = self.columns[self.over].card_gap
            found = self.columns[self.over].over_card(xp, yp)
            if found:
                self.over_card  = found[0]
                self.over_xoffs = found[1]
                self.over_yoffs = found[2]

        self.app.repaint()

    def test_if_player_done(self):

        if self.done_pile.is_full():
            self.snd_play(SND_GAME_OVER)
            self.fireworks.reset()
            self.game_over = True
            self.app.repaint()
            
    def mouse_down(self):

        if self.automator.is_active() or self.game_over:
            return

        if self.score_box.is_over(self.drag_xpos, self.drag_ypos):
            self._next_hint()
            return 

        if self.drag_cards:
            return

        over_column = self.columns[self.over]
        if self.over_card and over_column.can_card_be_picked_up(self.over_card):
            self.snd_play(SND_PICK_UP)
            self.drag_from_column = over_column
            self.drag_cards = over_column.pop(self.over_card)
            self.drag_xoffs = self.over_xoffs
            self.drag_yoffs = self.over_yoffs
            self.drag_gap   = self.over_gap
            self.app.repaint()
            return

        if self.dealer.is_mouse_over(self.app.screen, self.drag_xpos, self.drag_ypos):
            self.automator.push_animator(Dealer.DealAnimator(self))
            self.undo.flush()
            self.hints = None


    def mouse_up(self): 

        if self.automator.is_active() or self.game_over:
            return

        if self.drag_cards:
            try_column = self.columns[self.over]
            if self.over > -1 and try_column.can_card_be_pushed(self.drag_cards[0]):
                self.hints = None

                card_down = False
                last_card = self.drag_from_column.last_card()
                if last_card:
                    card_down = last_card.face_down

                try_column.push(self.drag_cards)
                try_column.adjust_gap(self.app.screen)
                self.drag_from_column.turn_over_top_card()
                self.drag_from_column.adjust_gap(self.app.screen)
                if try_column != self.drag_from_column:
                    self.score_box.inc_moves()

                column_run = try_column.ends_in_run()
                if column_run:
                    self.undo.flush()
                    self.automator.push_animator(Column.RunAnimator(self, try_column))

                else:
                    self.snd_play(SND_PUT_DOWN)
                    self.undo.push(self.drag_from_column, card_down, try_column, self.drag_cards[0])

            else:
                self.snd_play(SND_PUT_DOWN)
                self.drag_from_column.push(self.drag_cards)

            self.drag_cards = None
            self.app.repaint()

    def key_down(self, key):

        if self.automator.is_active() or self.game_over:
            return

        if key == pg.K_u:
            self.undo.pop()
            return

        if key == pg.K_m:
            self._next_hint()

    def draw(self):
        self._draw_bg()

        self.score_box.draw(self.app.screen)

        self.dealer.draw(self.app.screen)
        self.done_pile.draw(self.app.screen)

        for c in self.columns:
            c.draw(self.app.screen)

        if self.drag_cards:
            draw_x = self.drag_xpos + self.drag_xoffs
            draw_y = self.drag_ypos + self.drag_yoffs
            for card in self.drag_cards:
                card.draw(self.app.screen, draw_x, draw_y)
                draw_y += self.drag_gap

        if self.hover_cards:
            ypos = self.hover_ypos
            for hc in self.hover_cards:
                hc.draw(self.app.screen, self.hover_xpos, ypos)
                ypos += PADDING

        if self.game_over:
            self.fireworks.draw()
            self.app.repaint()
        
        #self.app.draw_text(
                #self.font,
                #10, 530,
                #"#over=%d"%self.over,
                #(#255,255,255))


        #if self.over_card:
            #self.app.draw_text(
                    #self.font,
                    #10, 550,
                    #"#card=%s"%self.over_card,
                    #(#255,255,255))

            #self.app.draw_text(
                    #self.font,
                    #10, 570,
                    #"#xoffs=%d  yoffs=%d"%(self.over_xoffs, self.over_yoffs),
                    #(#255,255,255))

    def snd_play(self, sound_id):
        if self.snd_capable and self.snd_enabled:
            self.snd_samples[sound_id].play()
Example #16
0
class Director:
    """
    A code template for a person who directs the game. The responsibility of 
    this class of objects is to keep track of the score and control the 
    sequence of play.
    
    Attributes:
        start_game: starts the game
        points: The total number of points earned.
        play_again: An instance of the class of objects known as Thrower.
        get_choice: See if they want to go high or low. 

    General Workflow:
        get_inputs
        do_updates
        do_outputs
    """
    def __init__(self):
        self.points = 0
        self.keep_playing = True
        self.user_H_L_choice = ""
        self.play_again = True
        self.get_choice = ""
        self.dealer = Dealer()
        self.highscore = Highscore()

    def start_game(self):
        """
        Starts the game loop
        """

        while self.keep_playing:
            self.get_inputs()
            self.do_updates()
            self.do_outputs()

    def get_inputs(self):
        """
        Prints and asks for the user input
        """
        self.dealer.draw_card()
        print(f"The card is {self.dealer.prev_card}")
        self.user_H_L_choice = input("Higher or Lower? [h/l] ")
        print(f"The next card was {self.dealer.current_card}")


    def do_updates(self):
        """
        This will adjust data based off of user's choices

        """
        if self.user_H_L_choice == self.dealer.determine_result():
            self.points += 100
        elif self.user_H_L_choice != self.dealer.determine_result():
            self.points -= 75
        else:
            self.points += 0

    def do_outputs(self):
        """
        Outputs the last bit of data, as well as some last minute proccessing
        """
        self.highscore.get_highscore()
        check_points = int(self.points)
        self.highscore.check_highscore(check_points)
        self.highscore.save_highscore
        if self.points <= 0:
            print('YOU LOSE')
            self.keep_playing == False
            quit()
        else:
            print(f'Points = {self.points}')
            self.get_choice = input("Keep Playing? [y/n] ")

            if self.get_choice == 'y':
                self.keep_playing == True
            elif self.get_choice == 'n':
                self.highscore.get_highscore()
                check_points = int(self.points)
                self.highscore.check_highscore(check_points)
                self.highscore.save_highscore()
                print(f'Your highscore was: {self.highscore.highscore}')
                self.keep_playing == False
                quit()
Example #17
0
 def __init__(self):
     self.playerScore = 300
     self.current_card = 0
     self.next_card = 0
     self.dealer = Dealer()
     self.keepPlaying = True
Example #18
0
class Director:
    """A code template for a person who directs the game. The responsibility of 
    this class of objects is to keep track of the score, control the 
    sequence of play, and determine if the player can keep playing.
    
    Attributes:
        score (number): The total number of points earned.
        keep_playing (Boolean): Whether or not the player wants to keep playing.
        dealer (Dealer): An instance of the class of objects known as Dealer.
    """
    def __init__(self):
        """The class constructor.
        
        Args:
            self (Director): An instance of Director.
        """
        self.keep_playing = True
        self.score = 300
        self.dealer = Dealer()

    def start_game(self):
        """Starts the game loop to control the sequence of play.
        
        Args:
            self (Director): An instance of Director.
        """
        while self.keep_playing:
            current_card = self.dealer.get_nextCard()
            print(f"The card is: {current_card}")
            hl_inputs = self.get_inputs()
            next_card = self.dealer.get_nextCard()
            print(f"Next card was: {next_card}")
            higher = self.isHigher(current_card, next_card)
            isCorrect = self.is_correct(hl_inputs, higher)
            self.do_updates(isCorrect)
            self.do_outputs()
            self.keepPlaying()
            print()

    def keepPlaying(self):
        """Determines whether the player can keep playing, if they have more
        points than 0, and if so gives the player gets the choice to keep playing 
        or end the game.
        
        Args:
            self (Director): An instance of Director.
        """
        if self.score <= 0:
            self.keep_playing = False
        else:
            userInput = input("Keep playing? [y/n] ")
            if userInput == 'y':
                self.keep_playing = True
            else:
                self.keep_playing = False

    def is_correct(self, hl_inputs, higher):
        """This function determines whether the player guessed correctly or 
        incorrectly about the next card being high or low. 
        
        Args:
            self (Director): An instance of Director.
            hl_inputs: An input from the user that will either 
            be an h or l.
            higher: Determined which card is higher or lower.
        Returns: 
            boolean: True if the player guesses right, and false
            if the player guesses wrong.
        """
        if hl_inputs == 'h' and higher:
            return True
        elif hl_inputs == 'h' and not higher:
            return False
        elif hl_inputs == 'l' and higher:
            return False
        elif hl_inputs == 'l' and not higher:
            return True

    def get_inputs(self):
        """Gets the inputs at the beginning of each round of play. In this case,
        that means whether the player thinks the next card is higher or lower.

        Args:
            self (Director): An instance of Director.
        Returns:
            string: Returns an h or l depending on what the user inputs.
        """
        userInput = input("Higher or lower? [h/l] ")
        return userInput

    def isHigher(self, current_card, next_card):
        """Determines whether the current card and next card are higher or lower
        than each other.
        
        Args:
            self (Director): An instance of Director.
            current_card: Gives the current card, the one the user
            can see.
            next_card: Gives the next card.
        Returns:
            boolean: True if the current card is less than the next 
            card, and False if the current card is greater than or 
            equal to the next card.
        """
        if current_card < next_card:
            status = True
        elif current_card >= next_card:
            status = False
        return status

    def do_updates(self, isCorrect):
        """Updates the important game information for each round of play. In 
        this case, that means calculating and updating the score.

        Args:
            self (Director): An instance of Director.
            isCorrect: Determined whether the player guessed right
            or wrong.
        """
        if isCorrect == True:
            self.score += 100
        elif isCorrect == False:
            self.score -= 75

    def do_outputs(self):
        """Outputs what the score is for the player to see.

        Args:
            self (Director): An instance of Director.
        """
        print(f"Your score is: {self.score}")