Example #1
0
class TestFirstDart(unittest.TestCase):
    def setUp(self):
        self.round = Round()

    @data(('S10', 10), # test single
          ('D10', 20), # test double
          ('T10', 30), # test triple
          ('s10', 10)  # test lower case
          )
    @unpack
    def test_hit(self, throw, total):
        # 1st dart hit => set the marker,
        #                 add the score to total,
        #                 missed_first remains unchanged
        dart_throw = DartThrow(throw)
        self.round.dart1(dart_throw)
        self.assertEqual(total, self.round.total)
        self.assertFalse(self.round.missed_first)
        self.assertEqual(int(throw[1:]), self.round.marker)

    def test_miss(self):
        # 1st dart missed => don't set the marker,
        #                    don't add the score to total,
        #                    missed_first is set to true
        dart_throw = DartThrow('M')
        self.round.dart1(dart_throw)
        self.assertEqual(-50, self.round.total)
        self.assertTrue(self.round.missed_first)
        self.assertEqual(-1, self.round.marker)
Example #2
0
class Main(ShowBase):
	def __init__(self):
		ShowBase.__init__(self)
		self.login = Login(self)
	
	def startMainmenu(self):
		self.login.hide()
		self.mainmenu = MainMenu(self)
		self.pregame = Pregame(self)
		self.mainmenu.show()
	
	def startPregame(self):
		self.mainmenu.hide()
		self.pregame.reset()
		self.pregame.show()

	def returnToMenu(self):
		self.pregame.hide()
		self.mainmenu.show()
	
	def startRound(self):
		self.pregame.hide()
		self.round = Round(self)
	
	def endRound(self):
		self.round.destroy()
		del self.round
		self.pregame.show()
		
	def hostGame(self, params):
		pid = Popen(["python", "server.py", params]).pid
		print 'Server Process ID:', pid
	
	def quit(self):
		sys.exit()
Example #3
0
class TestSecondDart(unittest.TestCase):
    def setUp(self):
        self.round = Round()

    @data(('S10', 20),
          ('s10', 20),
          ('D10', 30),
          ('T10', 40),
          ('M', -40),
          ('S5', 5))
    @unpack
    def test_first_dart_hit(self, throw, total):
        self.round.missed_first = False
        self.round.marker = 10
        self.round.total = 10
        self.round.dart2_and_3(DartThrow(throw))
        self.assertEqual(total, self.round.total)

    @data(('S10', 20),
          ('M', -50))
    @unpack
    def test_first_dart_miss(self, throw, total):
        self.round.missed_first = True
        self.round.total = 0
        self.round.dart2_and_3(DartThrow('S10'))
        self.assertEqual(-10, self.round.total)
Example #4
0
class Game:
    """ Represents a Word Guess Game """
    
    def __init__(self, id):
        """ Initialize the Game """
        self.id = id
        self.currentRound = Round()
        self.points = 0
        
    def guess(self, guesses):
        """ Return the results of the guess against the current Round """
        self.currentRound.guess(guesses)
        self.tryToAwardPoints()
        
    def startNextRound(self):
        """ Start the Next Round """
        nextWordLength = GetNextLength(self.currentRound.wordLength)
        self.currentRound = Round(wordLength=nextWordLength)
        
    def tryToAwardPoints(self):
        """ Award Poitns if the Round was finished """
        if self.currentRound.completed:
            self.points += points[self.currentRound.triesLeft]
            
    def hasNextRound(self):
        """ Return if there is a round to play after the current round """
        return HasNextLength(self.currentRound.wordLength)
Example #5
0
 def play_game(self):
     """
     Play a game.
     - Start score as game_score (usually 0)
     - New rounds while no player reaches max_score        
     - If winner on round, winner's score is updated
     - History of game is updated with each round's result
         (winner and score of round)
     Return game winner and list of rounds results
     """
     score = self.game_score()
     while max(score.values()) < self.n_points:
         new_round = Round(self.players, self.n_tiles, self.max_number)
         winner, score, _ = new_round.play_round()
         try:
             winner.update_score(score)
         except AttributeError:
             pass
         self.history.append({'winner': str(winner), 'score': score})
         score = self.game_score()
         print self.str_game_score()
         print
     winner = [str(player) for player in self.players 
               if player.get_score() == max(score.values())][0]
     return winner, self.history
Example #6
0
 def start_round(self):
     names = self.__get_names()
     lists = self.__get_selected_lists()
     interface = RoundInterface(names)
     words_per_round = properties.WORDS_PER_ROUND
     word_time_interval = properties.WORD_TIME_INTERVAL
     img_from_wiki = properties.LOAD_IMAGES_FROM_WIKIPEDIA
     round = Round(words_per_round, word_time_interval, names, lists, interface, img_from_wiki)
     round.start()
Example #7
0
def game_view(request):

    if 'context' in request.session:
        ctx = request.session['context']
    else:
        ctx = UserContext()
        request.session['context'] = ctx

    request.session['round'] = Round.get_round(ctx.round)
    return render(request, 'game.html', {}, content_type="html")
Example #8
0
    def run(self, round_num):
        # initialize round pool
        self.config.log("Generating Initial Seating Arrangement")

        cur_round = Round(players=self.config.PLAYERS)
        cur_round.pair_players(
            list(self.config.PLAYERS), 
            self.config.SEATS_PER_TABLE,
            self.config.MIN_SEATS_PER_TABLE)

        should_converge = cur_round.should_converge(round_num, self.config)

        # iterate some number of times
        for i in range(0, self.config.MAX_ITERATIONS):
            iter_stats = self.stats.create_iteration()

            self.stats.record_round(cur_round)

            # if any are 0, then done.
            self.config.log("Checking for Global Minimum.")
            if self.stats.did_converge(self.config.NUM_PLAYERS):
                return cur_round

            self.config.log("Checking for early exit.")
            if not should_converge and self.check_early_exit():
               return cur_round

            self.config.log("Improving Seating Assignments")
            new_round = cur_round.improve(self.config)

            if new_round.score() <= cur_round.score():
                cur_round = new_round
            # else:
            #     pool = [cur_round.improve(self.config) for i in range(0, self.config.CLASH_MUTATION_SIZE)]
            #     pool.sort(key=lambda x: x.score())

            #     best_round = pool[0]
            #     
            #     if best_round.score() < cur_round.score():
            #         cur_round = best_round

            self.stats.finish_iteration()

            if self.config.DEBUG:
                iter_stats.print_iteration_report()

        cur_round.validate()

        return cur_round
Example #9
0
def set_up_test_data():
    stephen = Player('Stephen Muller')
    stephen_first_round = Round(stephen)
    first_round_misses = [21]
    stephen_first_round.singles_round.missed_target(first_round_misses)
    stephen_first_round.print_score()
    stephen_second_round = Round(stephen)
    second_round_misses = [6, 14, 24]
    stephen_second_round.singles_round.missed_target(second_round_misses)
    stephen_second_round.print_score()
Example #10
0
    def play(self):
        for _ in xrange(1, self.rounds + 1):
            self.current_round += 1
            self.print_score()
            for pKey, pVal in self.players.iteritems():
                start_msg = "Player {p}'s turn. Starting score = {s}"
                print start_msg.format(p=pKey, s=pVal.score)
                rnd = Round()
                dart = get_throw(1)
                rnd.dart1(DartThrow(dart))
                dart = get_throw(2)
                rnd.dart2_and_3(DartThrow(dart))
                dart = get_throw(3)
                rnd.dart2_and_3(DartThrow(dart))

                pVal.score += rnd.total
        self.game_in_progress = False
Example #11
0
def create_rounds(tournament_list):
    """
    Use the tournament_list object list, that was
    returned from the create_tournaments function, which
    contains 15 Tournament objects with the following
    instance variables:

    tourn_id, tourn_name, golf_course_id, start_date,
    num_rounds, num_golfers, golfers...

    Create num_rounds Round objects from every
    Tournament object element in tournament_list:
    Add in the following as instance variables values

    round_id, tourn_id, day

    A list is returned, where each element is a Round object

    """
    print("\nThe Round object list\n")

    # Create an empty list that will be filled with Round objects whose data comes from the parameter tournament_list
    rounds_list = []

    # Initialize round_id
    round_id = 1

    # Create an outer looper to traverse the input tournament_list, where the loop variable "tourn" will contain
    # one of the Tournament objects in tournament_list at each loop iteration
    for tourn in tournament_list:
        # Get the number_rounds and tourn_id from Tournament object, tourn, and initialize num_rounds to number_rounds -
        # this will be decremented below to find the correct day for the Round object being built
        tourn_id = tourn.get_tourn_id()
        number_rounds = tourn.get_num_rounds()
        num_rounds = int(number_rounds)

        # Create an inner loop to run number_round times using the range function, where the loop variable 'r' keeps
        # the number of Rounds being created
        for r in range(int(number_rounds)):
            # Check the value of num_rounds to determine the day value of this Round object.
            if int(num_rounds) == 4:
                day = "Thu"
            elif int(num_rounds) == 3:
                day = "Fri"
            elif int(num_rounds) == 2:
                day = "Sat"
            elif int(num_rounds) == 1:
                day = "Sun"

            # Decrement the num_rounds counter
            num_rounds -= 1

            # Create a Round object call it round passing in round_id, tourn_id, and day
            round = Round(round_id, tourn_id, day)

            # Append the Round object to the rounds_list
            rounds_list.append(round)

            # Increment the round_id
            round_id += 1

    # Print the round objects to the console
    for item in rounds_list:
        print(item)

    return rounds_list
Example #12
0
    def test_serialize_no_movie(self):
        round1 = Round(TestRound.room1, 1)

        ser = {'judge': '', 'movie': '', 'number': 1}

        self.assertEqual(round1.serialize(), ser)
Example #13
0
    def test_eq_equal(self):
        round1 = Round(TestRound.room1, 1)
        round2 = Round(TestRound.room1, 1)

        self.assertEqual(round1, round2)
Example #14
0
def fire_round(ai_settings, window, ship, rounds):
    if len(rounds) < ai_settings.num_rounds_on_screen:
        new_round = Round(ai_settings, window, ship)
        rounds.add(new_round)
Example #15
0
	def startRound(self):
		self.pregame.hide()
		self.round = Round(self)
Example #16
0
 def test_standard_moves(self):
     r = Round(SingleWordCollection(), [0, 1, 2])
     self.assertFalse(r.timer)
     r.timer = 25
     self.assertEqual(r.timer, 25)
     r.timer = 30
     self.assertEqual(r.timer, 30)
     r.timer = None
     self.assertFalse(r.timer)
     self.assertEqual(r.start_game(), (0, 1))
     self.assertEqual(r.start_move(0), "one")
     self.assertEqual(r.guessed(0), "one")
     self.assertEqual(r.time_ran_out(0), (1, 2))
     self.assertEqual(r.start_move(1), "one")
     self.assertEqual(r.failed(1), (2, 0))
     self.assertEqual(r.start_move(2), "one")
     self.assertEqual(r.guessed(2), "one")
     self.assertEqual(r.guessed(2), "one")
     self.assertEqual(r.guessed(2), "one")
     self.assertEqual(r.guessed(2), "one")
     self.assertEqual(r.pretty_scores(),
                      [[0, 5, 1, 4], [2, 4, 4, 0], [1, 1, 0, 1]])
Example #17
0
 def start_round(self, task):
     self.preround.hide()
     self.round = Round(self)
     return task.done
Example #18
0
def round_sm():
    """Generates a small round."""
    return Round(0, 0, 0, 1)
Example #19
0
def round_bg():
    """Generates a bigger round."""
    return Round(0, 0, 0, 2)
Example #20
0
 def startRound(self):
     self.lobby.hide()
     self.round = Round(self)

def onpick(event):
    ind = event.ind
    for i in ind:
        stroke2print = lookup_basedon_type_str_gain(round1, np.take(x, i),
                                                    np.take(y, i))
        stroke2print.stroke_print()


if __name__ == '__main__':
    #run only once on a round of data unless comment out save_round()
    data_import = pd.read_csv(
        'rounds\\Uploaded\\121418_LaurelCreek_Palmer.csv',
        names=['Club', 'Loc Start', 'Dist Start'])
    round1 = Round('12/14/18', 'LaurelCreek', 'Palmer', '18')

    for idx, row in data_import.iterrows():
        a = Stroke((idx + 1), row["Club"], row["Loc Start"], row["Dist Start"])
        round1.add_stroke(a)

    round1.calculate_strokes_gained()
    round1.strokes = round1.strokes_to_pandas()
    round1.calculate_strokes_to_hole()
    round1.build_scorecard()
    round1.single_round_plot()
    #round1.save_round('rounds\Taillie_History.csv')

#    fig2 = round1.plot_strgain_type_bar()
#
#
Example #22
0
def main():
    pygame.init()

    done = False
    fps_counter = 0
    game_speed = 60
    display_scale = 1
    clock = pygame.time.Clock()
    retlange_height = 50
    retlange_width = 500
    screen_height = 1080//display_scale
    screen_width = 1920//display_scale
    screen = pygame.display.set_mode((0, 0), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN)
    # screen = pygame.display.set_mode((400, 400), pygame.HWSURFACE | pygame.DOUBLEBUF)
    x = 100
    y = screen_height//10*9
    moving_speed = 15
    round_finished = False
    paddle_power = 0
    print(1)

    # pygame.display.set_caption("Arkanoid Wiktorii")
    icon = pygame.image.load('graphics/background.jpg').convert_alpha()
    # pygame.display.set_icon(icon)

    start_time = time.time()
    pygame.font.init()  # you have to call this at the start,
    # if you want to use this module.
    myfont = pygame.font.SysFont('Comic Sans MS', 30)
    # print(start_time)
    pygame.font.init()
    stage = Round(1)
    print(2)
    while not done:
        print(3)
        fps_counter += 1
        pressed = pygame.key.get_pressed()
        # if pressed[pygame.K_UP] and y > 0 :
        #     y = y - moving_speed
        # if pressed[pygame.K_DOWN] and y < 500 - retlange_height:
        #     y = y + moving_speed
        if pressed[pygame.K_RIGHT] and x < screen_width - retlange_width :
            x = x + moving_speed * paddle_power // 100
            if paddle_power < 100:
                paddle_power = paddle_power + 4
        if pressed[pygame.K_LEFT] and x > 0 :
            x = x - moving_speed * paddle_power // 100
            if paddle_power < 100:
                paddle_power = paddle_power + 4
        if not pressed [pygame.K_RIGHT] and not pressed [pygame.K_LEFT]:
            paddle_power = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                done = True


       # pygame.draw.rect(object, (object_colour), pygame.Rect(x, y, object_width, object_height))
        #pygame.draw.rect(screen, (91, 44, 111), pygame.Rect(x, y, retlange_width, retlange_height))
        stage.draw(screen, x, y, retlange_width)
        pygame.draw.polygon(screen, (91, 44, 111), [[x, y + retlange_height], [x + retlange_width, y + retlange_height], [x + retlange_width // 2, y]])
        fps_per_sec = fps_counter / (time.time() - start_time)


        textsurface = myfont.render(str(round(fps_per_sec)), False, (0, 0, 0))
        screen.blit(textsurface, (20, 20))
        if stage.round_finished:
            textsurface = myfont.render("Level 1 finished", False, (0, 0, 0))
            screen.blit(textsurface, (500, 500))
            time.sleep(1)
            stage = Round(2)
        #pygame.draw.rect(screen, tuple(ball_colour), pygame.Rect(ball_position[0], ball_position[1], ball_diameter, ball_diameter))

        pygame.display.flip()
        clock.tick(120)
Example #23
0
File: game.py Project: JTJL/Atama
 def work(self):
     # TODO: change one round to multiround
     with Round(self.client, self.dealer) as round:
         result = round.work()
Example #24
0
def create_rounds(tournament_list):
    #    Use the tournament_list object list, that was
    #    returned from the create_tournaments function, which
    #    contains 15 Tournament objects with the following
    #    instance variables:

    #    tourn_id, tourn_name, golf_course_id, start_date,
    #    num_rounds, num_golfers, golfers...

    #    Create num_rounds Round objects from every
    #    Tournament object element in tournament_list:
    #   Add in the following as instance variables values

    #    round_id, tourn_id, day

    #    A list is returned, where each element is a Round object
    #
    print("\nThe Round object list:\n")
    # 1. Create an empty list called rounds_list
    #   that will be filled in with Round objects
    #   whose data comes from the parameter - tournament_list
    rounds_list = []

    # 2. Initialize the round_id
    round_id = 1

    # 3. Create an outer loop to traverse the input
    #   tournament_list, where the loop variable 'tourn'
    #   will contain one of the Tournament objects in
    #   tournament_list at each loop iteration
    for tourn in tournament_list:
        # a. Get the number_rounds and tourn_id from the
        #      Tournament object, tourn, and initialize
        #      num_rounds to number_rounds - this will be
        #      decremented below to find the correct day
        #      for the Round object being built
        number_rounds = Tournament.get_num_rounds(tourn)
        tourn_id = Tournament.get_tourn_id(tourn)
        #   b. Create an inner loop to run number_rounds times
        #      using the range function, where the loop
        #      variable 'r' keeps the count for the
        #      number of Rounds being created
        r = number_rounds
        for item in range(number_rounds):
            #      1. Check the value of num_rounds to determine
            #         the day value of this Round object.
            #         Use an if/elif/else structure to set the
            #         day instance variable
            if r == 4:
                day = "Thu"
            elif r == 3:
                day = "Fri"
            elif r == 2:
                day = "Sat"
            elif r == 1:
                day = "Sun"


#      2. Decrement the num_rounds counter
            r = r - 1
            #      3. Create a Round object call it round passing
            #         in round_id, tourn_id, and day
            round = Round(round_id, tourn_id, day)
            #      4. Append the Round object to the rounds_list
            rounds_list.append(round)
            #      5. Increment the round_id
            round_id = round_id + 1
    # 4. Print the round objects to the console
    for rounds in rounds_list:
        print(rounds)

    #return rounds_list to console
    return rounds_list
Example #25
0
 def generate_round(self):
     new_round = Round(self.team_one, self.team_two)
     new_round.round_actions()
     self.rounds.append(new_round)
Example #26
0
 def setUp(self):
     self.a_round = Round()
     self.players = [Player(i) for i in range(5)]
     # exercise for reader: understand how generators and iterators work; learn their
     # benefits and drawbacks
     self.cards = (Card(suit, rank) for rank, suit in islice(product(Rank, Suit), 10))
Example #27
0
def blackjack():
    """Manages the blackjack game"""
    print_menu()
    menu_choice = input("What would you like to do (1/2)? ")

    while menu_choice == "1":
        current_round = Round()

        current_round.print_header()

        current_round.deal()

        # Ends the game if the player gets blackjack
        if current_round.round_winner:
            print_menu()
            menu_choice = input("What would you like to do (1/2)? ")
            continue

        current_round.print_hands()

        move = input("What is your move (Hit/Stay)? ")
        while move == "Hit" and current_round.round_winner == False:
            current_round.player_hit()
            if current_round.round_winner == False:
                move = input("What is your move (Hit/Stay)? ")

        # Only plays the dealer if the player doesn't bust
        if not current_round.round_winner:
            current_round.play_for_dealer()

        print_menu()
        menu_choice = input("What would you like to do (1/2)? ")
Example #28
0
 def start_new_round(self):
     self.curr_round = Round(self)
     self.curr_frame = self.curr_round
     self.main_menu.close()
Example #29
0
    def test_more_words(self):
        r = Round(ManyWordCollection(), [0, 1, 2])

        self.assertEqual(r.start_game(), (0, 1))
        got = set()
        got.add(r.start_move(0))
        got.add(r.guessed(0))
        got.add(r.guessed(0))
        self.assertEqual(r.time_ran_out(0), (1, 2))
        self.assertEqual(r.guessed(0), texts.not_your_turn_message)

        got.add(r.start_move(1))
        got.add(r.guessed(1))
        self.assertEqual(r.time_ran_out(1), (2, 0))

        self.assertEqual(r.start_move(1), texts.not_your_turn_message)

        got.add(r.start_move(2))
        self.assertEqual(r.time_ran_out(2), (0, 2))
        self.assertEqual(r.time_ran_out(2), texts.not_your_turn_message)

        got.add(r.start_move(0))
        got.add(r.guessed(0))
        self.assertEqual(r.time_ran_out(0), (1, 0))

        got.add(r.start_move(1))
        got.add(r.guessed(1))
        self.assertEqual(r.time_ran_out(1), (2, 1))

        got.add(r.start_move(2))
        self.assertEqual(r.failed(2), (0, 1))
        self.assertEqual(r.failed(2), texts.not_your_turn_message)
        self.assertEqual(r.guessed(2), texts.not_your_turn_message)

        self.assertEqual(r.start_move(0), texts.no_more_words_message)
        self.assertSetEqual(
            got, {"два", "двенадцать", "восемьдесят", "пять", "ноль", "шесть"})

        self.assertEqual(r.points[0], 4)
        self.assertEqual(r.points[1], 4)
        self.assertEqual(r.points[2], 2)
Example #30
0
 def play(self):
     self.start()
     # First 7 rounds (starting at 7, 1 less card each round until 1 card per person)
     for i in range(7):
         r = Round(7 - i, self.playerList)  # Gets the round initialized
         print()
         r.bets()
         sleep(1)
         # One iteration for each trick
         for k in range(7 - i):
             self.updateDisplay(self.roundNumber, r.topCard.getSuit(),
                                r.dealer)
             r.trick()
             sleep(1)
         # self.roundNumber += 1
         r.end()
         self.pointsDisplay(self.roundNumber, r.dealer)
         self.roundNumber += 1
     # Remaining 9 rounds (starting with 1 card, 1 more per round until 10)
     for i in range(9):
         r = Round(i + 2, self.playerList)  # Gets the round initialized
         r.bets()
         sleep(1)
         for k in range(i + 2):
             self.updateDisplay(self.roundNumber, r.topCard.getSuit(),
                                r.dealer)
             r.trick()
             sleep(1)
         # self.roundNumber += 1
         r.end()
         self.pointsDisplay(self.roundNumber, r.dealer)
         self.roundNumber += 1
     self.endGame()
def shoot_round(ai_settings, win, plane, rounds):
    """shoot a round if !limit"""
    if len(rounds) < ai_settings.num_rounds_on_screen:
        new_round = Round(ai_settings, win, plane)
        rounds.add(new_round)
Example #32
0
def play_game(Players, main_player):

    all_rounds = []
    for i in range(1, 14):
        table = []
        if all_rounds == []:
            current_round = Round(i)
            if not computer:
                roundWinner.score = ""
        else:
            if len(all_rounds[-1].leaders) > 1:
                current_round = Round(i, all_rounds[-1])
            else:
                current_round = Round(i)
                if not computer:
                    roundWinner.score = ""
        moves = dict()
        for player in Players:
            if player.type == 0:
                print("Player %d" % player.id)
                print(player.getCards())
                played = -1

                while played == -1:
                    for event in pygame.event.get():
                        pos = pygame.mouse.get_pos()
                        if event.type == pygame.QUIT:
                            played = -2
                            pygame.quit()
                            exit()

                        if event.type == pygame.MOUSEBUTTONDOWN:
                            if playButton.isOver(pos):
                                played = None
                                for card in player.hand.values():
                                    if card.selected:
                                        played = card.value
                                        continue
                                if played:
                                    table.append(player.hand[played])
                                else:
                                    played = -1
                                    # del player.hand[played]

                            for card in player.hand.values():
                                if card.isOver(pos):
                                    card.selected = True
                                else:
                                    card.selected = False
                    # choice = (int)(input("Enter Move: "))
                    # played = player.play(choice)

                    redrawWindow(main_player.hand.values(), table, win)

                played = player.play(played)
                redrawWindow(main_player.hand.values(), table, win)
                c.send("%d,%d" % (main_player.id, played.value))
                info = c.recv().split(",")
                for i in range(len(Players) - 1):
                    moves[int(info[2 * i])] = int(info[2 * i + 1])

            elif player.type == 2:
                played = player.play(random.choice(list(player.getCards())))
                # table.append(played)
                c.send("%d,%d" % (main_player.id, played))
                info = c.recv().split(",")
                for i in range(len(Players) - 1):
                    moves[int(info[2 * i])] = int(info[2 * i + 1])
            else:
                played = player.play(moves[player.id])
                if not computer:
                    table.append(played)
                # print("Player %d played: %d" %(player.id, played))
            if not computer:
                redrawWindow(main_player.hand.values(), table, win)
                current_round.update(player.id, played.value)
            else:
                current_round.update(player.id, played)
        all_rounds.append(current_round)
        current_round.status()
        if len(current_round.leaders) == 1:
            print("Round won by: Player %d" % current_round.leaders[0])
            if not computer:
                if current_round.leaders[0] == main_player_id:
                    roundWinner.score = "You"
                else:
                    roundWinner.score = "Player %d" % current_round.leaders[0]
        else:
            if not computer:
                roundWinner.score = "Tie"
        for player in Players:
            player.update(current_round)
            if not computer:
                score_board[player.id].score = str(player.points)
        if not computer:
            redrawWindow(main_player.hand.values(), table, win)
        sleep(2)
Example #33
0
from ball import Ball
from paddle import Paddle
from round import Round
from game import Game

if __name__ == '__main__':
    paddle = Paddle()
    ball = Ball()
    this_round = Round()
    game = Game()
    game.run(this_round, paddle, ball)
Example #34
0
    def test_eq_diff_rooms(self):
        round1 = Round(TestRound.room1, 1)
        round2 = Round(TestRound.room2, 1)

        self.assertNotEqual(round1, round2)
Example #35
0
class Game(object):
    def __init__(self, id, players):
        """
        init the game! once player threshold is met
        :param id: int
        :param players: Player[]
        """
        self.id = id
        self.players = players
        self.words_used = set()
        self.round = None
        self.board = Board()
        self.player_draw_ind = 0
        self.round_count = 1
        self.start_new_round()

    def start_new_round(self):
        """
        Starts a new round with a new word
        :return: None
        """
        try:
            round_word = self.get_word()
            self.round = Round(round_word, self.players[self.player_draw_ind],
                               self)
            self.round_count += 1

            if self.player_draw_ind >= len(self.players):
                self.round_ended()
                self.end_game()

            self.player_draw_ind += 1
        except Exception as e:
            self.end_game()

    def player_guess(self, player, guess):
        """
        Makes the player guess the word
        :param player: Player
        :param guess: str
        :return: bool
        """
        return self.round.guess(player, guess)

    def player_disconnected(self, player):
        """
        Call to clean up objects when player disconnects
        :param player: Player
        :raises: Exception()
        """

        # todo check this
        if player in self.players:
            self.players.remove(player)
            self.round.player_left(player)
            self.round.chat.update_chat(
                f"Player {player.get_name()} disconnected.")
        else:
            raise Exception("Player not in game")

        if len(self.players) <= 2:
            self.end_game()

    def get_player_scores(self):
        """
        give a dict of player scores.
        :return: dict
        """
        scores = {player.name: player.get_score() for player in self.players}
        return scores

    def skip(self, player):
        """
        Increments the round skips, if skips are greater than
        threshold, starts new round.
        :return: None
        """
        if self.round:
            new_round = self.round.skip(player)
            if new_round:
                self.round.chat.update_chat(f"Round has been skipped.")
                self.round_ended()
                return True
            return False
        else:
            raise Exception("No round started yet!")

    def round_ended(self):
        """
        If the round ends call thiss
        :return: None
        """
        self.round.chat.update_chat(f"Round {self.round_count} has ended.")
        self.start_new_round()
        self.board.clear()

    def update_board(self, x, y, color):
        """
        calls update method on board.
        :param x: int
        :param y: int
        :param color: 0-8
        :return: None
        """
        if not self.board:
            raise Exception("No board created")
        self.board.update(x, y, color)

    def end_game(self):
        """
        ends the game
        :return:
        """
        print(f"[GAME] Game {self.id} ended")
        for player in self.players:
            player.game = None

    def get_word(self):
        """
        gives a word that has not yet been used
        :return: str
        """
        with open("words.txt", "r") as f:
            words = []

            for line in f:
                wrd = line.strip()
                if wrd not in self.words_used:
                    words.append(wrd)

            self.words_used.add(wrd)

            r = random.randint(0, len(words) - 1)
            return words[r].strip()
Example #36
0
 def setUp(self):
     self.round = Round()
Example #37
0
class Game(object):
    def __init__(self, id, players):
        """
        lancez le jeu! une fois que le seuil de joueur est atteint
        """
        self.id = id
        self.players = players
        self.words_used = set()
        self.round = None
        self.board = Board()
        self.player_draw_ind = 0
        self.round_count = 1
        self.start_new_round()

    def start_new_round(self):
        """
        Commence un nouveau tour avec un nouveau mot
        """
        try:
            round_word = self.get_word()
            self.round = Round(round_word, self.players[self.player_draw_ind],
                               self)
            self.round_count += 1

            if self.player_draw_ind >= len(self.players):
                self.round_ended()
                self.end_game()

            self.player_draw_ind += 1
        except Exception as e:
            self.end_game()

    def player_guess(self, player, guess):
        """
        Fait deviner le mot au joueur

        """
        return self.round.guess(player, guess)

    def player_disconnected(self, player):
        """
        
        Appel pour nettoyer les objets lorsque le joueur se déconnecte
        """

        # todo check this
        if player in self.players:
            player_ind = self.players.index(player)
            if player_ind >= self.player_draw_ind:
                self.player_draw_ind -= 1
            self.players.remove(player)
            self.round.player_left(player)
            self.round.chat.update_chat(
                f"Player {player.get_name()} disconnected.")
        else:
            raise Exception("Player not in game")

        if len(self.players) <= 2:
            self.end_game()

    def get_player_scores(self):
        """
        donnez un dict des scores des joueurs..
        """
        scores = {player.name: player.get_score() for player in self.players}
        return scores

    def skip(self):
        """
        Incrémente les sauts de ronde, si les sauts sont supérieurs à
        seuil, commence un nouveau tour.
        """
        if self.round:
            new_round = self.round.skip()
            self.round.chat.update_chat(
                f"Player has votes to skip ({self.round.skips}/{len(self.players) -2})"
            )
            if new_round:
                self.round.chat.update_chat(f"Round has been skipped.")
                self.round_ended()
                return True
            return False
        else:
            raise Exception("No round started yet!")

    def round_ended(self):
        """
        Si le tour se termine, appelez-le
        """
        self.round.chat.update_chat(f"Round {self.round_count} has ended.")
        self.start_new_round()
        self.board.clear()

    def update_board(self, x, y, color):
        """
        appelle la méthode de mise à jour à bord.
        """
        if not self.board:
            raise Exception("No board created")
        self.board.update(x, y, color)

    def end_game(self):
        """
        arreter le jeu
        :return:
        """
        print(f"[GAME] Game {self.id} ended")
        for player in self.players:
            player.game = None

    def get_word(self):
        """
        donne un mot qui n'a pas encore été utilisé
        :return: str
        """
        with open("words.txt", "r") as f:
            words = []

            for line in f:
                wrd = line.strip()
                if wrd not in self.words_used:
                    words.append(wrd)

            self.words_used.add(wrd)

            r = random.randint(0, len(words) - 1)
            return words[r].strip()
Example #38
0
 def __init__(self, id):
     """ Initialize the Game """
     self.id = id
     self.currentRound = Round()
     self.points = 0
Example #39
0
    def test_repr(self):
        round1 = Round(TestRound.room1, 1)

        self.assertEqual(repr(round1), '1')
Example #40
0
 def round(self):
     r = Round(self.set_dealer())
     cards = list(self.cards)
     r.deal_cards(cards, self.players)
     # While loop continues until all players are out of cards or player wants to quit game
     while not r.check_end(self.players):
         # the.play() returns -1 when player wants to quit game
         if r.the_play() == -1:
             return -1
         r.change_player(self.players)
     r.calculate_points(self.players)
     r.empty_players_decks(self.players)
Example #41
0
    def test_eq_diff_types(self):
        round1 = Round(TestRound.room1, 1)
        round2 = 'I am a string'

        self.assertNotEqual(round1, round2)
Example #42
0
    def test_methods(self):

        game = Game()
        game.initialize_cards()
        game.players = [
            Player("Mike"),
            Player("Tim"),
            Player("Jack"),
            Player("Nick")
        ]

        # Points for Mike
        game.players[0].cards_deck = game.cards[0:26]
        # Points for Tim
        game.players[1].cards_deck = game.cards[26:37]
        # Points for Jack
        game.players[2].cards_deck = game.cards[37:49]
        # Points for Nick
        game.players[3].cards_deck = game.cards[49:52]

        rnd = Round(game.players[0])
        game.players[1].mokki = 2
        rnd.calculate_points(game.players)

        # Check that the points of each player is correct
        self.assertEqual(4, game.players[0].points, "Wrong amount of points!")
        self.assertEqual(3, game.players[1].points, "Wrong amount of points!")
        self.assertEqual(1, game.players[2].points, "Wrong amount of points!")
        self.assertEqual(3, game.players[3].points, "Wrong amount of points!")

        # Check that the validation algorithm works properly
        self.assertEqual(
            True,
            Round.check_validity(
                self, Card("Pata-7", 7,
                           7), [Card("Ruutu-3", 3, 3),
                                Card("Hertta-4", 4, 4)]), "Validation failed")
        self.assertNotEqual(
            True,
            Round.check_validity(
                self, Card("Pata-8", 8,
                           8), [Card("Ruutu-3", 3, 3),
                                Card("Hertta-4", 4, 4)]), "Validation failed")
        self.assertEqual(
            True,
            Round.check_validity(
                self, Card("Pata-2", 2,
                           15), [Card("Pata-8", 8, 8),
                                 Card("Hertta-7", 7, 7)]), "Validation failed")
        self.assertNotEqual(
            True,
            Round.check_validity(self, Card("Pata-10", 10, 10), [
                Card("Ruutu-5", 5, 5),
                Card("Hertta-5", 5, 5),
                Card("Pata-5", 5, 5)
            ]), "Validation failed")

        # Check that the dealer changes correctly after each round
        game.set_dealer()
        self.assertEqual(game.players[0], game.dealer, "Wrong dealer!")
        game.set_dealer()
        self.assertEqual(game.players[1], game.dealer, "Wrong dealer!")
        game.set_dealer()
        game.set_dealer()
        game.set_dealer()
        self.assertEqual(game.players[0], game.dealer, "Wrong dealer!")
Example #43
0
    def test_eq_diff_numbers(self):
        round1 = Round(TestRound.room1, 1)
        round2 = Round(TestRound.room1, 2)

        self.assertNotEqual(round1, round2)
Example #44
0
 def startNextRound(self):
     """ Start the Next Round """
     nextWordLength = GetNextLength(self.currentRound.wordLength)
     self.currentRound = Round(wordLength=nextWordLength)