Example #1
0
    def __init__(self, name_image="ship-1.png"):
        Screen.__init__(self)
        self.keys = {
            "up": [K_UP],
            "down": [K_DOWN],
            "left": [K_LEFT],
            "right": [K_RIGHT],
            "rotate_left": [K_a, K_q],
            "rotate_right": [K_d],
            "fire": [K_SPACE],

            # test
            "lose_life": [K_l]  # c'est un L
        }

        self.image = pygame.image.load('img/' + name_image).convert_alpha()
        self.rect = self.image.get_rect()

        self.rect.center = self.srect.center
        self.ball = Ball(default_center=self.rect.center)

        self.vitesse = 2
        self.vitesse_rotate = 2

        self.orginal = self.image.copy()
        self.current_angle = 0

        self.cheated = 0

        self.max_life = 50
        self.life = self.max_life

        self.score = Score()
Example #2
0
 def show_menu(self):
     pygame.mouse.set_visible(1)
     self.menu.drawMenu()
     while True:
         pygame.time.Clock().tick(self.FPS)
         for event in pygame.event.get():
             self.menu.handleEvent(event)
             if event.type == Menu.MENUCLICKEDEVENT or event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:
                 if event.text == "Quit":
                     self.state = 'quit'
                     return
                 elif event.text == 'Start game':
                     self.state = 'game'
                     self.menu.deactivate()
                     return
             elif event.type == KEYDOWN and event.key == K_RETURN:
                 self.state = 'game'
                 self.menu.deactivate()
                 return
                     
         if self.menu.isActive():
             self.menu.drawMenu()
             
         Score.draw_high_scores(self.hiscores, self.surface)
         pygame.display.flip()
Example #3
0
	def __init__(self):
		# Initialize screen
		pygame.init()
		self.size = self.width, self.height = 640, 470
		self.black = 0, 0, 0
		self.screen = pygame.display.set_mode(self.size)
		self.background = pygame.image.load("sprites/background.png")

		# Initialize objects and clock
		self.spriteList = []
		self.player1 = Player(self, 1)
		self.player2 = Player(self, 2)
		self.ball1 = Ball(self)
		self.ball2 = Ball(self)
		self.ball3 = Ball(self)
		self.score1 = Score(self, 1)
		self.score2 = Score(self, 2)
		self.spriteList.append(self.player1)
		self.spriteList.append(self.player2)
		self.spriteList.append(self.score1)
		self.spriteList.append(self.score2)
		self.spriteList.append(self.ball1)

		self.player1_tot = 0
		self.player2_tot = 0

		self.stop = 0
		self.win = 0

		self.level = 1
		self.counter = 120
Example #4
0
def selected_game(game_num, difficulty):
    global run_program
    game = object()
    if game_num in [1, 2, 3]:
        if game_num == 1:
            game = MemoryGame(difficulty)
            game.generate_sequence()

        elif game_num == 2:
            game = GuessGames(difficulty)
            game.generate_number()

        elif game_num == 3:
            game = CurrencyRouletteGame(difficulty)

        its_awin = game.play()
        if its_awin:
            print("You win")
            current_score = Score(difficulty)
            current_score.add_score()

        else:
            print("You lose")  # USD = 3.51

    elif game_num == 4:
        print(
            "Goodbye, Check your score in http://localhost (Press CTRL+C to quit)"
        )
        run_score.on_web()
        run_program = False
    return run_program
Example #5
0
 def __init__(self, threshold):
     Score.__init__(self)
     self.threshold = threshold
     self.matrix = [
         x[:] for x in [[0] * len(self.indexes)] * len(self.indexes)
     ]
     self.nbOfBlocks = 0
    def prepare_for_start(self):
        self.field_leds.set_all_pixels_to_black()
        self.field_matrix.set_all_pixels_to_black()

        self.field_for_snake = []

        for i in range(self.field_leds.height):
            self.field_for_snake.append([])
            for _ in range(self.field_leds.width):
                self.field_for_snake[i].append(0)

        self.head_x = 5
        self.head_y = 20

        self.direction = 0
        self.lenght_of_snake = 3

        self.delay = 0.5
        self.game_over = False

        self.food_is_on_field = False
        self.food_x = 0
        self.food_y = 0

        self.is_there_a_direction_change_in_this_tick = False

        self.score = Score()
        self.score.points = 3
        self.score.draw_score_on_field(self.field_matrix)
        self.rgb_field_painter.draw(self.field_leds)
        self.led_matrix_painter.draw(self.field_matrix)
Example #7
0
    def __init__(self):
        title = "Trip: Down The Rabbit Hole"  #working title
        self.canvas_width = 500
        self.canvas_height = 500
        self.frame = simplegui.create_frame(title, self.canvas_width,
                                            self.canvas_height)
        self.frame.set_canvas_background("rgb(28, 17, 23)")
        self.state = "start"

        self.start_screen = StartScreen(self.canvas_width, self.canvas_height)
        self.end_screen = EndScreen(self.canvas_width, self.canvas_height)

        # Player
        self.player = Wizard(
            Vector(self.canvas_width / 2, self.canvas_height / 2))
        self.health = PlayerHealthbar(self.player, (20, 20), (170, 50))
        self.score = Score((self.canvas_width - 150, 40))
        self.floor = 0

        # Interactions
        self.keyboard = Keyboard()
        self.mouse = Mouse((self.canvas_width / 2, self.canvas_height / 2))
        self.player_input = PlayerInputInteraction(self.player, self.keyboard,
                                                   self.mouse)
        self.player_game = None

        # Map Generation
        self.__min_room_size = 256
        self.__max_rooms = 12
        self.__random_rooms = 0.4
        self.map = None
def firstProblem():
    result = []

    for m in range(100):
        for size in ssize:
            score = Score()
            cv = LeaveNOut()
            classifier = KNeighborsClassifier(n_neighbors=3, algorithm="kd_tree")

            X = np.random.normal(mu, sigma, size)
            X = np.expand_dims(X, axis=1)

            Y = np.zeros([X.shape[0]])
            Y = np.expand_dims(Y, axis=1)
            one_indices = random.sample([i for i in range(X.shape[0])], size / 2)
            Y[one_indices, 0] = 1

            #leave one out
            pred, true = cv.run(data=X, labels=Y, model=classifier, n_out=1)
            c = score.c_score(pred, true)
            auc_score = auc(pred, true, reorder=True)
            result.append([c, auc_score, size, m])

    data = pd.DataFrame(result)
    data.to_csv('result1.csv', header=False, index=False)
Example #9
0
def RandomMotifSearch(DNA, k, t):
    Motifs = []  # utworzenie listy Motifs
    for i in range(0, t):  # Petla iterujaca od 0 do ilosci sekwencji
        Indeks = random.randint(
            0,
            len(DNA[0]) - k
        )  # losowanie zmiennej indeks w przedziale od 0 do konca sekwencji -
        # dlugosc meru
        Motifs.append(Indeks)  # Dodanie wylosowanej liczby do listy Motifs
    BestMotifs = Motifs
    while True:  # Niekonczaca sie petla
        Profil = Profile(Motifs, DNA,
                         k)  # Tworzenie profilu na podstawie listy motifs
        for n in range(0, t):  # Petla od 0 do ilosci sekwencji
            Motifs[n] = MostProbableFromProfile(
                DNA[n], Profil,
                k)  # Znalezienie najbardziej podobnych motywow na
            # podstawie profilu
        if Score(Motifs, DNA,
                 k) > Score(BestMotifs, DNA,
                            k):  # Sprawdzenie czy Score Motifs jest wyzszy od
            # wylosowanego
            BestMotifs = Motifs  # Jesli tak to BestMotifs = Motifs
        else:
            return Score(
                BestMotifs, DNA, k
            ), BestMotifs  # Jesli nie to zwracany jest Score oraz BestMotifs
Example #10
0
 def spawn_boulder(self):
     x = random.randint(0, Screen.get_width())
     boulder = Boulder(x, -150, 0 + random.uniform(-0.5, 0.5),
                       self.velocity * random.uniform(1, 2),
                       random.uniform(0.4, 0.6))
     self.boulders.append(boulder)
     Score.increment_score()
Example #11
0
    def start(self):
        pygame.init()

        self.stage = Stage(self, 1)
        self.screen = pygame.display.set_mode((800, 600))

        self.background = Background(self)
        self.background.load()

        self.player = Player(self)
        self.player.load()

        self.bullet = Bullet(self)
        self.bullet.load()

        self.enemies = Enemies(self)
        self.enemies.load()

        self.game_text = GameText(self)
        self.game_text.load()

        self.explosion = Explosion(self)
        self.explosion.load()

        self.caption = Caption(self)
        self.caption.load()

        self.score = Score(self)
        self.score.load()

        while self.running:
            self.screen.fill((0, 0, 0))
            self.background.show()
            self.handle_event()
Example #12
0
 def __init__(self,
              sets_to_win,
              player_one_win_point_probability_function=None):
     self.player_one_win_point_probability_function = player_one_win_point_probability_function
     self.sets_to_win = sets_to_win
     self.score = Score()
     self.match_is_over = False
     self.player_serving = random.choice([0, 1])
def right_feature_selection(X, Y):
    score = Score()
    cv = LeaveNOut()
    classifier = KNeighborsClassifier(n_neighbors=3, algorithm="kd_tree")

    pred, true = cv.run(data=X, labels=Y, model=classifier, n_out=1, embedded_feature_selection=True)
    c = score.c_score(pred, true)
    auc_score = auc(pred, true, reorder=True)
    return c, auc_score
Example #14
0
    def userInput(self, gateway):
        gateway = gateway + '/'

        try:
            with open('/var/www/html/userinput.txt', mode='r') as fp:
                credentials = [line.rstrip('\n') for line in fp]
                fp.close()
        except OSError:
            print('File: ' + file + '.txt' + ' failed to load.')
        if(len(credentials) is not 0):
                    if(self.token != credentials[2]):
                            self.token = credentials[2]
                            session = HTMLSession()
                            print('Trying custom credentials: User: '******' Password: '******'http://'+ credentials[0] + ':' + credentials[1] + '@' + gateway)
                            print('http://' + credentials[0] + ':' + credentials[1] + '@'+ gateway)
                            code = r.status_code
                            print('Response: ' + str(code))
                            if(code != 200 and self.tests['Credentials']['mainPage'] == 1):
                                    print('Trying subpage...')
                                    r.html.render()
                                    soup = BeautifulSoup(r.html.html, 'lxml')
                                    page = soup.find('a')
                                    print('http://' + credentials[0] + ':' + credentials[1] + '@'+ gateway + page['href'])
                                    r = session.get('http://' + credentials[0] + ':' + credentials[1] + '@' + gateway + page['href'])
                                    code = r.status_code
                                    print('Response: ' + str(code))
                                    if (code == 200):
                                            self.tests['Credentials']['username'] = credentials[0]
                                            self.tests['Credentials']['password'] = credentials[1]
                                            try:
                                                    Score.update(self.tests)
                                                    self.tests['Credentials']['found'] = 1
                                            except:
                                                    pass
                                            session.close()
                                            return 1
                                    else:
                                            print('Custom credentials incorrect. Waiting for new input...')
                                            return 0
                            else:
                                    if(code == 200):
                                            self.tests['Credentials']['username'] = credentials[0]
                                            self.tests['Credentials']['password'] = credentials[1]
                                            try:
                                                    Score.update(self.tests)
                                                    self.tests['Credentials']['found'] = 1
                                            except:
                                                    pass
                                            session.close()
                                            return 1
                                    else:
                                        print('Custom credentials incorrect. Waiting for new input...')
                                        return 0
                    else:
                            return 0
        else: return 0
Example #15
0
    def __init__(self, data, type = 'raw'):
        self.__data = loader(data, type).load()
        self.score = Score()
        self.interpret = Interpret()

        prerequisites = self.__data['prerequisites']
        self.__prerequisites = {}
        for prerequisite in prerequisites:
            self.__prerequisites[prerequisite.get('label')] = prerequisite
Example #16
0
 def __init__(self):
     init()
     random.seed(1)
     self.game_over = False
     self.board = Board()
     self.bomberman = self.board.board[1][1][0]
     self.score = Score()
     self.lives = Lives()
     self.direction_key = ''
     self.bomb_key = ''
def wrong_feature_selection(X, Y):
    score = Score()
    cv = LeaveNOut()
    classifier = KNeighborsClassifier(n_neighbors=3, algorithm="kd_tree")

    X, indices = cv.select(X, Y, select_count=10)
    pred, true = cv.run(data=X, labels=Y, model=classifier, n_out=1)
    c = score.c_score(pred, true)
    auc_score = auc(pred, true, reorder=True)
    return c, auc_score
Example #18
0
 def __init__(self, field_leds: Field, field_matrix: Field,
              rgb_field_painter: RGB_Field_Painter,
              led_matrix_painter: Led_Matrix_Painter,
              highscorelist: Highscorelist):
     super(Tetris,
           self).__init__(field_leds, field_matrix, rgb_field_painter,
                          led_matrix_painter, highscorelist)
     self.score = Score()
     pygame.init()
     game_sound.init_mixer()
Example #19
0
class Game(object):
    """This is the highest level class which contains the Jeopardy, Double Jeopardy,
    and final Jeopardy rounds, as well as the player's score.
    """
    def __init__(self, clues):
        self.r1 = self.create_board(clues, 'Jeopardy!')
        self.r2 = self.create_board(clues, 'Double Jeopardy!')
        self.final_jeopardy_clue, self.final_jeopardy_category = self.get_final_jeopardy(
            clues)
        self.score = Score()

    def create_board(self, clues, round):
        return GameBoard(clues, round)

    def get_final_jeopardy(self, clues):
        for clue in clues:
            if clue['round'] == 'Final Jeopardy!':
                return Clue(clue['value'], clue['answer'],
                            clue['question']), clue['category']

    def play(self):
        self.score = self.r1.play(self.score)
        self.score = self.r2.play(self.score)
        self.play_final_jeopardy()

    def play_final_jeopardy(self):
        print("\n\nFINAL JEOPARDY!\n")
        print("Category: " + self.final_jeopardy_category)
        wager = self.get_final_jeopardy_wager()
        self.final_jeopardy_clue.play()
        self.print_final_score(wager)

    def get_final_jeopardy_wager(self):
        while True:
            wager = input("\nEnter final Jeopardy wager: ")
            try:
                wager = int(wager)
                if wager < 0 or wager > self.score.score:
                    raise ValueError
                else:
                    return wager
            except ValueError:
                print("Invalid wager. Try again.")
                continue

    def print_final_score(self, wager):
        while True:
            correct = input("Enter '1' for correct or '0' for incorrect.")
            if correct is '1':
                self.score.update(wager)
                break
            elif correct is '0':
                self.score.update(wager * -1)
                break
        print("\n\nFinal score: $" + str(self.score.score))
Example #20
0
    def __init__(self):
        self.running = False
        self.paused  = False
        self.godMode = False

        self.scoreText = Score()
        self.player    = Player()

        self.asteroids = []
        self.sinceLastSpawn = 0.0
        self.prevFrameTime = 0
 def get_score_by_tm_id(self, tm_id=None):
     if tm_id is None:
         return
     url = 'http://jw.xujc.com/student/index.php?c=Search&a=cj&tm_id=' + tm_id
     tbody = self.get_tbody(url)
     all_score = []
     for tr in tbody.find_all('tr'):
         temp = Score([
             td.text for index, td in enumerate(tr.find_all('td'))
             if index != 4 and index < 6
         ])
         all_score += [temp.__dict__()]
     return all_score
Example #22
0
    def __init__(self, goodSteps, comboName):

        self.comboSteps = []
        self.comboSteps = goodSteps
        self.numberOfSteps = len(self.comboSteps)
        self.name = comboName
        self.fileLocs = FileLocations()
        self.scorer = Score()
        self.difficulty = 0
        self.difficultyBenchmarks = {
            "easy": 40000,
            "medium": 70000,
            "hard": 2000000
        }
Example #23
0
    def game_loop(self):
        pygame.mouse.set_visible(0)
        while True:
            pygame.time.Clock().tick(self.FPS)
            events = pygame.event.get()
            for event in events:
                if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:
                    self.state = 'quit'
                    return
                elif self.state == 'game':
                    if event.type == KEYDOWN:
                        if event.key == K_UP:
                            self.up = True
                    if event.type == KEYUP:
                        if event.key == K_UP:
                            self.up = False
                elif self.state == 'gameover':
                    if event.type == KEYUP:
                        if event.key == K_RETURN:
                            if self.nameinput != None:
                                name = self.nameinput.value
                                if name == '':
                                    name = 'no name'
                                Score.update_highscore(name, self.level.get_score(), self.hiscores)
                            self.state = 'menu'
                            return
             
            # Update level 
            self.level.update(self.up)
            self.level.draw()
            self.text = self.font.render("$" + str(self.level.get_score()), 1, self.DARK_GREY)
            self.surface.blit(self.text, (10, 10))

            # If player is busted the level is ended
            if self.level.player.state == 'busted':
                if Score.is_highscore(self.level.get_score(), self.hiscores):
                    self.message = "NEW HISCORE!"
                    if self.nameinput == None:
                        self.nameinput = eztext.Input(x = 400, y = 440, maxlength = 6, color = self.GREEN, prompt = 'Enter name: ')
                    self.nameinput.update(events)
                    self.nameinput.draw(self.surface)
                else:
                    self.message = "You did not collect enough cash, try again!"
                self.show_final_score()
                self.up = False
                self.state = 'gameover'

            # Flip the buffer to show the updates
            pygame.display.flip()
Example #24
0
    def __init__(self, patient_path):
        """
        :param patient_path: name of the folder containing all the information about the data
        example: ./data/data-1

        """
        Thread.__init__(self)
        self.__patient_path = patient_path

        self.__low_pass_filter = LowPassFilter(filename=self.__patient_path)
        self.__band_pass_filter = BandPassFilter(filename=self.__patient_path)
        self.__hampel_filter = HampelFilter(filename=self.__patient_path)
        self.__gravity_filter = GravityFilter(filename=self.__patient_path)
        self.__score = Score(filename=self.__patient_path)
        self.__reporter = Reporter(filepath=self.__patient_path)
Example #25
0
def main():
    # initialize the pygame module
    pygame.init()
    pygame.display.set_caption("Tetris Clone")

    # create a surface on screen that has the size of 240 x 180
    screen = pygame.display.set_mode((640, 480))
    screen_model = Screen()
    screen_model.spawnPiece()

    # define a variable to control the main loop
    running = True
    score = Score()

    i = 0
    # main loop
    while running:
        pygame.time.delay(350)
        on_event(pygame, running, screen_model, score)
        on_loop(pygame, screen_model, score)
        on_render(pygame, screen, screen_model, score)
        if i == 0:
            playMidi(pygame, "GameBegin1.wav")
            pygame.time.delay(1000)
            playMidi(pygame, "GameBegin2.wav")
            playMidi(pygame, "Theme.wav")
        i += 1
    pygame.midi.quit()
Example #26
0
def allScores():
    cur = mysql.connection.cursor()
    cur.execute("select * from scoreboard order by score desc")
    results = cur.fetchall()
    resultsList = [Score(result).toDict() for result in results]
    cur.close()
    return render_template("allScores.html", scores=resultsList)
Example #27
0
class Game():
    totalTimeInMinutes = 90
    GameScore = Score()

    def printScore(self):
        scoreText = "{} - {}"
        print(
            scoreText.format(self.GameScore.TeamOneGoals,
                             self.GameScore.TeamTwoGoals))

    def addTeamGoal(self, scorer, teamName, teamId):
        if teamId == 1:
            self.addTeamOneGoal(scorer, teamName)
        elif teamId == 2:
            self.addTeamTwoGoal(scorer, teamName)

    def addTeamOneGoal(self, scorer, teamName):
        self.GameScore.TeamOneGoals = self.GameScore.TeamOneGoals + 1
        print("Goal by {} for {}".format(scorer, teamName))
        self.printScore()

    def addTeamTwoGoal(self, scorer, teamName):
        self.GameScore.TeamTwoGoals = self.GameScore.TeamTwoGoals + 1
        print("Goal by {} for {}".format(scorer, teamName))
        self.printScore()
Example #28
0
class Rubber(Deal):
    def __init__(self,screen):
        Deal.__init__(self,screen)
        self.dealer=-1
        self.bidding=Bidding(screen,self.dealer)
        self.score=Score()
        self.contract=None
    def newHand(self,screen):
        self.contract=None
        self.shuffle()
        self.rotateDealer()
        self.bidding.reset(screen,self.dealer)
    def getContract(self,screen,table,auto):
        self.bidding.processBidding(screen,table,auto)
        self.contract=self.bidding.contract
        if self.contract:
            self.getHand(self.contract.owner).contractowner=True
    def rotateDealer(self):
        self.dealer=(self.dealer+1)%4
    def endHand(self):
        return self.score.addScore(self.contract,self.trickcount)
    def zeroScore(self):
        self.games=[0,0]
        for xx in self.score.scores:
            xx.over=0
            xx.under=[0]
Example #29
0
def importBloc(nom_fichier, proportion = 0.5):

    # Ouverture du fichier
    fichier = open(nom_fichier, 'r')

    listBloc = []


    i = 0
    seq = 0

    for ligne in fichier:
        ligne = ligne.strip()

        if(ligne[0] == '>'):
            i = 0
            seq += 1

        else:
            if(seq == 1):
                listBloc.append([ligne])
            else:
                if(len(listBloc) > i):
                    listBloc[i].append(ligne)
                else:
                    raise SyntaxError("Erreur de taille dans la" \
                        " liste: %d | i: %d" % (len(listBloc), i))
            i += 1

    return Score([Bloc(seq, proportion) for seq in listBloc])
Example #30
0
    def start(self, img):
        self.score = Score(img)
        self.right = np.argmax(img.sum(axis=0) == 255 * img.shape[0])
        self.top = img.shape[0] - np.argmax(img[::-1, :self.right].sum(
            axis=1) == 255 * self.right)

        # Get dinossaur's nose location to track if he is on the ground
        x, y = 0, 0
        for i in range(0, img.shape[0] - 1 - self.top):
            if img[self.top + i, self.right - 1] == 0:
                x, y = self.right - 1, self.top + i - 1
                break
        for i in range(1, img.shape[0] - 1 - y):
            if img[y + i, self.right - 1] == 255:
                self.reference_pixels = ((x, y), (self.right - 1, y + i))
                break
Example #31
0
 def init_objects(self):
     with self.canvas:
         self.stones = []
         self.rubies = []
         self.player = Player(self.width / 2)
         self.properties = Properties()
         self.score = Score(self.height)
Example #32
0
 def __init__(self, parent, size=4):
     self.size = size
     self.parent = parent
     self.tiles = self.create_empty()
     self.labels = self.create_labels()
     self.init_tiles()
     self.score = Score()
Example #33
0
    def getscores(self, id_user):
        try:
            list_score = []
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(
                "SELECT * FROM score WHERE id_user=%s ORDER BY submitted asc" %
                id_user)
            myresult = mycursor.fetchall()

            for row in myresult:
                list_score.append(
                    Score(id_user, int(row[1]), int(row[2]), (row[3])))

            json_score = [obj.to_dict_set() for obj in list_score]
            jsdata = json.dumps({"list_score": json_score},
                                indent=4,
                                sort_keys=True,
                                default=str)
            jsdataj = json.loads(jsdata)

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(
                error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
                return jsdataj
Example #34
0
	def __init__(self, name_image="ship-1.png"):
		Screen.__init__(self)
		self.keys = {
			"up"          : [K_UP],
			"down"        : [K_DOWN],
			"left"        : [K_LEFT],
			"right"       : [K_RIGHT],
			"rotate_left" : [K_a, K_q],
			"rotate_right": [K_d],
			"fire"        : [K_SPACE],

			# test
			"lose_life": [K_l] # c'est un L
		}

		self.image = pygame.image.load('img/' + name_image).convert_alpha()
		self.rect  = self.image.get_rect()

		self.rect.center = self.srect.center
		self.ball = Ball(default_center=self.rect.center)

		self.vitesse = 2
		self.vitesse_rotate = 2

		self.orginal = self.image.copy()
		self.current_angle = 0

		self.cheated = 0

		self.max_life = 50
		self.life = self.max_life

		self.score = Score()
Example #35
0
class game_manager(common):
    def __init__(self):
        self.games = []
        self.text_menu = ''
        self.create_games_obj()
        self.create_menu()
        self.game_score = Score()

    # need to create all object to get the menu
    def create_games_obj(self):
        new_game = guess_game()
        self.games.append(new_game)
        new_game = memory_game()
        self.games.append(new_game)
        new_game = Currency_Roulette_Game(
            'Currency Roulette - try and guess the value of a random amount of USD in ILS'
        )
        self.games.append(new_game)

    def create_menu(self):
        self.text_menu = "Please choose a game to play:\n"
        index = 0
        for games in self.games:
            index += 1
            new_line = index.__str__() + '. ' + games.get_menu() + '\n'
            self.text_menu += new_line

    def play_game(self, game_obj, difficulty):
        game_result = game_obj.play(difficulty=difficulty)
        if game_result:
            self.game_score.add_score(difficulty)
        print(game_result)

    def show_main_menu(self):
        self.clean_screen()
        game_number = self.start_validate_input(message=self.text_menu,
                                                val_from_value=1,
                                                val_to_value=3)
        difficulty_number = self.start_validate_input(
            "Please choose game difficulty from 1 to 5: ",
            val_from_value=1,
            val_to_value=5)
        self.clean_screen()
        self.play_game(self.games[game_number - 1], difficulty_number)

    def welcome(self, name):
        return "Hello " + name + " and welcome to the World of Games(WoG).\nHere you can find many cool games to play."
Example #36
0
def getTopTen():
    cur = mysql.connection.cursor()
    cur.execute("select * from scoreboard order by score desc limit 10")
    results = cur.fetchall()  #a tuple of tuples, which makes ugly JSON
    resultsList = [Score(result).toDict() for result in results
                   ]  #cannot serialize python class as JSON
    cur.close()
    return jsonify(resultsList)
Example #37
0
def enter():
    global background, smallReplay, smallExit, bigReplay, bigExit, chooseExit, chooseReplay, cursor, crying, score
    background = Background()
    smallReplay = SmallReplay()
    smallExit = SmallExit()
    bigReplay = BigReplay()
    bigExit = BigExit()
    chooseExit = False
    chooseReplay = False
    cursor = Cursor()
    crying = Crying()
    score = Score()
    score.score = main_state.number.score
    game_world.clear()
    game_world.add_object(crying, 0)
    game_world.add_object(score, 0)
    game_world.add_object(cursor, 1)
Example #38
0
	def __init__(self):
		self.player1 = None 				#set player1 and player2 slot up
		self.player2 = None
		self.ai = AI()
		self.score = Score(self.player1, self.player2, self.ai)
		self.win = 0
		self.loss = 0
		self.tie = 0
Example #39
0
    def __init__(self, name='Top'):
        Score.__init__(self, name=name)
        self.scores = {}
        self.variant_list = []
        self.errorRegex = []
        self.warningRegex = []
        self.testBeginRegex = None  # There can be only 1
        self.testEndRegex = None    # There can be only 1
        self.errors = []
        self.warnings = []
        self.error_re = re.compile(r'ERROR')

        self.level = 0
        self.longest_string = 0
        self.max_level = None
        self.test_count = 0
        self.task_count = 0
Example #40
0
 def __init__(self):
     pygame.init()
     self.font = pygame.font.SysFont('sans-serif', 18, True)
     self.surface = pygame.display.set_mode(self.SCREEN_SIZE, 0, 32)
     self.state = 'intro'
     self.hiscores = Score.read_high_score()
     self.menu = Menu(("Start game", "Quit"))
     pygame.mixer.music.load(self.MUSIC_FILE)
     pygame.mixer.music.play(-1)
    def __init__(self):
        """Called when the the Game object is initialized. Initializes
        pygame and sets up our pygame window and other pygame tools
        that we will need for more complicated tutorials."""

        pygame.init()

        self.uiServer = GameControllerServer(self, min_players=2,max_players=2)
        self.paddleMap = {}
        self.leftPaddleFree = True
        self.rightPaddleFree = True
        self.started = False

        self.window = pygame.display.set_mode((800, 400))

        self.clock = pygame.time.Clock()

        pygame.display.set_caption("Pong with Android Controller")

        pygame.event.set_allowed([QUIT, USEREVENT])

        self.background = pygame.Surface((800,400))
        self.background.fill((255,255,255))

        pygame.draw.line(self.background, (0,0,0), (400,0), (400,400), 2)
        self.window.blit(self.background, (0,0))

        pygame.display.flip()

        self.sprites = pygame.sprite.RenderUpdates()

        self.leftpaddle = Paddle((50,200))
        self.sprites.add(self.leftpaddle)
        self.rightpaddle = Paddle((750,200))
        self.sprites.add(self.rightpaddle)

        self.ball = Ball((400,200))
        self.sprites.add(self.ball)

        self.scoreImage = Score((400, 50))
        self.sprites.add(self.scoreImage)

        self.pingsound = pygame.mixer.Sound(os.path.join('sound', 'ping.wav'))
        self.pongsound = pygame.mixer.Sound(os.path.join('sound', 'pong.wav'))

        self.uiThread = Thread(target=self.uiServer.serve)
        self.uiThread.start()
Example #42
0
 def start(self):
     while True:
         if self.state == 'intro':
             # Show the intro and when it's done we move directly to game state
             intro = Intro(pygame, self.surface);
             new_state = intro.show()
             self.state = new_state
         elif self.state == 'menu':
             # Show the menu and run the menu loop
             self.hiscores = Score.read_high_score()
             self.show_menu()
         elif self.state == 'game':
             # Run a game and run the game loop
             self.load_level()
             self.game_loop()
         elif self.state == 'quit':
             # Quit, we're done.
             pygame.quit()
             sys.exit()
Example #43
0
 def __init__(self, x, y, speed):
     self.image = pygame.image.load("actions/crook-0.png").convert_alpha()
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y - self.rect.height
     self.dx = 0
     self.dy = 0
     self.jumping = False
     self.colliding = False
     self.speed = speed
     self.score = Score()
     self.state = 'free'
     self.running_sound = pygame.mixer.Sound('data/step.ogg')
     self.running_sound.set_volume(0.2)
     self.channel = None
     self.frame = 0
     self.images =   ["actions/crook-0.png","actions/crook-1.png",
                      "actions/crook-2.png", "actions/crook-3.png",
                      "actions/crook-4.png", "actions/crook-5.png",
                      "actions/crook-6.png", "actions/crook-7.png"]
    def test_getLikeColors(self):
        likeColors = Score.getLikeColors(self.cards)

        self.assertTrue(len(likeColors) == 2)
Example #45
0
class Game:
	def __init__(self):
		self.player1 = None 				#set player1 and player2 slot up
		self.player2 = None
		self.ai = AI()
		self.score = Score(self.player1, self.player2, self.ai)
		self.win = 0
		self.loss = 0
		self.tie = 0
		
	def start(self):
		print ("Welcome to RPSLS, Lets Begin!")
		print ("Choose to face AI or Human")
		choice = input("1 for AI, 2 for Human: ")
		if choice == '1':
			self.player1 = self.getPlayer() #jump to getplayer function
			self.player1.getGuess()			#jump to get user pick function
			self.comp = self.getAI()		#jumps to getAI function
			self.player1.name
			self.end = self.score.results(self.player1.usernum, self.compnum, self.player1.name,self.win, self.loss, self.tie)
			self.score.win
			self.score.loss
			self.score.tie
			self.rest = self.restart(self.score.win, self.score.loss, self.score.tie)
			
		elif choice == '2':
			self.player1 = self.getPlayer() #jump to getplayer function
			self.player2 = self.getPlayer()
			print(self.player1.name , "'s turn")
			self.player1.getGuess()			#jump to get user pick function
			print(self.player2.name , "'s turn")
			self.player2.getGuess()	
			
			self.end = self.score.results2(self.player1.usernum, self.player2.usernum, self.player1.name, self.player2.name, self.win, self.loss, self.tie)
			self.score.win
			self.score.loss
			self.score.tie
			self.rest = self.restart(self.score.win, self.score.loss, self.score.tie)
		else:
			print("Invalid choice")
			return Game.start(self)			#returns to beginning of question
		
	def getPlayer(self):
		name = input("Enter a name: ")  	#ask for user input for name
		player = Player(name)				#jump to Player class and use name from previous line
		return player						#return player name into register 0
		
	def getAI(self):
		com = AI.AIgen(self)				#jumps to AI class and specifically AI gen function
		self.ai.compnum
	
	def restart(self, win, tie, loss):
		answer = input("would you like to play again? Y/N: ")
		print (answer)
		if answer.lower() == "y":
			Game.start(self)
		elif answer.lower() == "n":
			print("Goodbye.")
			print("Total Wins = ", win)
			print("Total Losses = ", loss)
			print("Total Ties = ", tie)
		else:
			print("Invalid, type Y or N")
			Game.restart()
 def test_testForOrder(self):
     self.assertTrue(Score.checkForOrder([Card(2, "Hearts"), Card(4, "Diamonds"), Card(3, "Hearts"), Card(5, "Diamonds")]))
Example #47
0
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
            self.FONT = self.boss.FONT
        else:
            self.boss = None
            self.FONT = "Dearest.ttf"

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        # Creation of two players
        self.player1 = Player(1)
        self.player2 = Player(-1)
        self.players = {1 : self.player1, -1 : self.player2}
        self.player1Hand = self.player1.hand
        self.player2Hand = self.player2.hand

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        # played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        self.position = None
        self.CARD = None
        self.infoCARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard, self)
        self.emptySquare = 9

        self.alphaAnimation = 255

        # Manage the winner congratulations font
        self.winner = Text("", self.FONT, white, 60)

        # Manage the display of the name of the card selected
        self.cardName = None

        # Do we show the name of the card selected?
        self.selectedCardName = 1
Example #48
0
class Application():
    """Main class of the game, manage the window"""
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
            self.FONT = self.boss.FONT
        else:
            self.boss = None
            self.FONT = "Dearest.ttf"

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        # Creation of two players
        self.player1 = Player(1)
        self.player2 = Player(-1)
        self.players = {1 : self.player1, -1 : self.player2}
        self.player1Hand = self.player1.hand
        self.player2Hand = self.player2.hand

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        # played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        self.position = None
        self.CARD = None
        self.infoCARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard, self)
        self.emptySquare = 9

        self.alphaAnimation = 255

        # Manage the winner congratulations font
        self.winner = Text("", self.FONT, white, 60)

        # Manage the display of the name of the card selected
        self.cardName = None

        # Do we show the name of the card selected?
        self.selectedCardName = 1


    def update(self):
        """Updates all the sprites on the window"""
        self.screen.blit(self.background, self.background.get_rect())
        self.screen.blit(self.field.surface, self.field.rect)

        for card in self.player1Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
              self.CARD.borderRect.topleft = self.CARD.rect.topleft
              self.screen.blit(self.CARD.border, self.CARD.borderRect)

        for card in self.player2Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
              self.CARD.borderRect.topleft = self.CARD.rect.topleft
              self.screen.blit(self.CARD.border, self.CARD.borderRect)

        self.scorePlayer1.update()
        self.scorePlayer2.update()
        self.screen.blit(self.scorePlayer1.surface, self.scorePlayer1.rect)
        self.screen.blit(self.scorePlayer2.surface, self.scorePlayer2.rect)
        if self.winner.text != "":
            self.winner.changeText()
            self.screen.blit(self.winner.surface, self.winner.rect)

        if self.selectedCardName != 0: 
            self.showName(1)
            self.showName(-1)

        if self.cardName != None:
                self.screen.blit(self.backCard, self.backCardRect)
                self.screen.blit(self.cardName.surface, self.cardName.rect)
                self.cardName = None

        if self.infoCARD == None:
        # If we aren't showing the about popup. Because About need to blit one
        # more thing before doing the following commands.
            pygame.display.flip()
            self.clock.tick(self.fps)

    def main(self):
        """Main part handling the game"""
        self.cardsOwner()
        self.update()
        while 1:
            if self.animation == 1:
                # We continue the animation
                self.putCard()
                self.update()
            else:
                # We over the animation and now the next player have to play.
                if self.sensAnimation == 1:
                    self.player = self.player * -1
                    self.sensAnimation = 0

            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP and self.animation == 0:
                    if event.button == 3 and self.winner.text == "":
                        if self.getCard(0):
                            self.showAbout()
                    if self.winner.text == "" and event.button == 1:
                        self.infoCARD = None
                        self.players[self.player].playCard(self)
                elif event.type == QUIT:
                    audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                    setConfig(audio)
                    self.field.saveState()
                    pygame.quit()
                    sys.exit()
                else:
                    # We get the status of all key on keyboard.
                    # Then we select the one at place 27: Escape.
                    # We can do this only if we ran the game
                    # with Menu.py and not directly from main.py
                    if pygame.key.get_pressed()[27] and self.boss != None:
                        self.boss.main()

            pygame.display.flip()
            self.clock.tick(self.fps)

    def putCard(self):
        """Animation of a card put on the field"""

        if self.CARD.inHand == 1:
        # We check if self..CARD is in the player's Hand
            self.Sound.playPutCard()

        # We drop the card off the Hand
        if self.CARD.inHand == 1:
            self.CARD.inHand = 0

        # Depending of the direction of the animation, we make the card
        # being invisible or visible again.
        if self.sensAnimation == 0:
            self.alphaAnimation -= 25 + (self.fps / 30.0 * 5)
            if self.alphaAnimation < 0:
                self.alphaAnimation = 0
            self.CARD.image.set_alpha(self.alphaAnimation)
            self.CARD.rect.centerx += 2 * self.player
        elif self.sensAnimation == 1:
            self.alphaAnimation += 25 + (self.fps / 30.0 * 5)
            if self.alphaAnimation > 255:
                self.alphaAnimation = 255
            self.CARD.image.set_alpha(self.alphaAnimation)

        # We change the position of the card and the animation's direction
        if self.CARD.image.get_alpha() <= 25:
            self.CARD.rect = self.Square
            self.sensAnimation = 1

        if self.CARD.image.get_alpha() == 255 and self.sensAnimation == 1:
            # We have put the card on the field and the animation is over.
            # We compare the elements to give potential malus/bonus.
            # And we have to look if that card captured some of the
            # ennemy's.
            self.animation = 0
            squareElement = self.field.elementName[self.numberSquare]
            if squareElement != None:
                self.Sound.playElement(squareElement)
            if self.CARD.elementName == squareElement \
            and squareElement != None:
                self.CARD.addModifier(1)
            else:
                if squareElement != None:
                    self.CARD.addModifier(-1)
            adjacentCards = self.getAdjacent()
            capturedCard = adjacent(self.CARD, adjacentCards)
            self.changeOwner(capturedCard)
            self.emptySquare -= 1
            self.CARD = None

        if self.emptySquare == 0:
            self.winAnimation()

    def selectedCard(self):
        """Player has selected a card
        But not yet a place on the field"""
        for i in [1, 2, 3, 4, 5]:
            self.CARD.rect.centerx += 4 * self.player
            self.update()

    def deselectedCard(self):
        """Finally, the player wants an other card"""
        for i in [1, 2, 3, 4, 5]:
            self.CARD.rect.centerx -= 4 * self.player
        self.CARD = None
        self.update()

    def squareFilled(self):
        """Say if there is already a card in the square"""
        for card in self.player1Hand.cards:
            if card.rect == self.Square:
                return 1
        for card in self.player2Hand.cards:
            if card.rect == self.Square:
                return 1
        return 0

    def cardsOwner(self):
        """Which cards is owned by who?"""
        cardPlayer = 0
        cardPlayer += self.player1Hand.cardsOwner()
        self.scorePlayer1.updateScore(cardPlayer)
        self.scorePlayer2.updateScore(10 - cardPlayer)

    def getAdjacent(self):
        """Get all the adjacent cards of the first one put"""
        posx, posy = self.CARD.rect.topleft
        adjacentCards = [None, None, None, None]
        if self.player == 1:
            for card in self.player2Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        elif self.player == -1:
            for card in self.player1Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        return adjacentCards

    def changeOwner(self, cards):
        for card in cards:
            if card.owner == 1:
                self.player1Hand.cards.remove(card)
                self.player2Hand.cards.append(card)
            if card.owner == -1:
                self.player2Hand.cards.remove(card)
                self.player1Hand.cards.append(card)
            self.capturedAnimation(card)
        self.cardsOwner()

    def capturedAnimation(self, card):
        """Shows a little animation when capturing card"""
        # We want the sound of the card put played before doing anything more
        self.update()
        while (pygame.mixer.get_busy()):
            pass

        # self.Sound.capturedCard.play()
        width = card.rect.width  # we expect 113. If not please change format.
        height = card.image.get_rect().height  # Here we expect 139.
        topleft = list(card.rect.topleft)
        step = 30 - (self.fps / 30 * 3)

        while(width != 10):
            width -= step
            if width < 10:
                width = 10
            topleft[0] += step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        card.owner *= -1
        card.changeOwner()

        while (width != 113):
            width += step
            if width > 113:
                width = 113
            topleft[0] -= step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        # If card has a bonus or malus, we have to re-draw it on the card
        if card.modifierValue != 0:
            card.image.blit(card.modifierBack.surface, card.modifierBack.rect)
            card.image.blit(card.modifier.surface, card.modifier.rect)

    def winAnimation(self):
        """Show who won the game"""
        if self.scorePlayer1.score > self.scorePlayer2.score:
            self.winner.text = _("Blue win!")
            self.winner.rect.topleft = self.backgroundRect.midtop
            self.winner.rect.x -= 20
            self.winner.color = blue
        elif self.scorePlayer2.score > self.scorePlayer1.score:
            self.winner.text = _("Red win!")
            self.winner.rect.topright = self.backgroundRect.midtop
            self.winner.rect.x += 20
            self.winner.color = red
        else:
            self.winner.text = _("Equality!")
            self.winner.rect.topleft = self.backgroundRect.midtop
            self.winner.color = white

        self.winner.changeColor()
        self.winner.rect.y += 10

    def getCard(self, player):
        """Return the card at pygame.mouse.get_pos() coordinates """
        coords = pygame.mouse.get_pos()
        if player == 1:
            card = self.player1Hand.getCard(coords)
            if card >= 0:
                if self.CARD != None:
                    self.deselectedCard()
                self.CARD = self.player1Hand.cards[card]
        elif player == -1:
            card = self.player2Hand.getCard(coords)
            if card >= 0:
                if self.CARD != None:
                    self.deselectedCard()
                self.CARD = self.player2Hand.cards[card]
        elif player == 0:
            #If we get a right-click, then we want to print the About
            #popup even if it is an ennemy's card
            card = self.player1Hand.getCard(coords)
            if card != None:
                self.infoCARD = self.player1Hand.cards[card].About
            else:
                card = self.player2Hand.getCard(coords)
                if card != None:
                    self.infoCARD = self.player2Hand.cards[card].About
        if card != None:
            return 1
        return 0

    def showAbout(self):
        """Show some info on the card if we do a right-click on it"""
        width = 0
        quit = 0
        maxWidth = 450
        COLORRED = (200,0,0,125)
        COLORBLUE = (0,0,200,125)
        event = None
        if self.infoCARD.boss.owner == 1:
            COLOR = COLORBLUE
        elif self.infoCARD.boss.owner == -1:
            COLOR = COLORRED

        background = pygame.Surface((width, 140), SRCALPHA)
        rect = background.get_rect()
        background.fill(COLOR)

        if self.infoCARD.boss.owner == 1:
            rect.topleft = self.infoCARD.boss.rect.topright
        elif self.infoCARD.boss.owner == -1:
            rect.topright = self.infoCARD.boss.rect.topleft

        while 1:
            self.update()
            self.screen.blit(background,rect)
            pygame.display.flip()
            self.clock.tick(self.fps)

            if width < maxWidth and quit == 0:
                width += 40 - (self.fps / 30.0 * 5) 
                if width > maxWidth:
                    width = maxWidth
                background = pygame.Surface((width, 140), SRCALPHA)
                rect = background.get_rect()
                background.fill(COLOR)
                if self.infoCARD.boss.owner == 1:
                    rect.topleft = self.infoCARD.boss.rect.topright
                elif self.infoCARD.boss.owner == -1:
                    rect.topright = self.infoCARD.boss.rect.topleft

            if quit == 1:
                width -= 40 - (self.fps / 30.0 * 5)
                if width < 0:
                    width = 0
                background = pygame.Surface((width, 140), SRCALPHA)
                rect = background.get_rect()
                background.fill(COLOR)
                if self.infoCARD.boss.owner == 1:
                    rect.topleft = self.infoCARD.boss.rect.topright
                elif self.infoCARD.boss.owner == -1:
                    rect.topright = self.infoCARD.boss.rect.topleft

            if width == 0:
                if quit == 1:
                    self.update()
                    return
                quit = 1

            if width == maxWidth and quit == 0:
                background.fill(COLOR)
                background.blit(self.infoCARD.surface, self.infoCARD.rect)
                self.update()
                self.screen.blit(background,rect)
                pygame.display.flip()
                self.clock.tick(self.fps)
                event = pygame.event.wait()

            if width == 0:
                self.infoCARD = None
                self.update()
                return 0

            if event and event.type == MOUSEBUTTONUP:
                quit = 1
            elif event and event.type == QUIT:
                audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                setConfig(audio)
                pygame.quit()
                sys.exit()

        return 0

    def showName(self, player):
        """Show the name of the card selected at the bottom of the window"""
        self.backCard, self.backCardRect = loadImage("name.png")

        if player == 1:
            for card in self.player1Hand.cards:
                if card == self.CARD:
                    name = self.CARD.name
                    self.cardName = Text(name, self.FONT, white, 40)
        elif player == -1:
            for card in self.player2Hand.cards:
                if card == self.CARD:
                    name = self.CARD.name
                    self.cardName = Text(name, self.FONT, white, 40)

        if self.cardName != None:
            self.cardName.rect.midbottom = self.backgroundRect.midbottom
            self.cardName.rect.y -= 10
            self.backCardRect.center = self.cardName.rect.center
Example #49
0
 def __init__(self,screen):
     Deal.__init__(self,screen)
     self.dealer=-1
     self.bidding=Bidding(screen,self.dealer)
     self.score=Score()
     self.contract=None
Example #50
0
#setup the window
MAXWIDTH = 500
MAXHEIGHT = 500
screen = pygame.display.set_mode((MAXWIDTH, MAXHEIGHT), 0, 32)
pygame.display.set_caption('Py Dudes')
pygame.mouse.set_visible(0)

#setup the background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))

#SCORE
SCORE = 0
scoreSprite = Score((MAXWIDTH - 100, MAXHEIGHT - 25))

#Draw Everything
screen.blit(background, (0, 0))
pygame.display.flip()

#setup the sprite groups
bullets = pygame.sprite.Group()
aliens = pygame.sprite.Group()
allsprites = pygame.sprite.LayeredDirty()
guisprites = pygame.sprite.Group()

guisprites.add(scoreSprite)

#setup the clock
clock = pygame.time.Clock()
    def getScore(self):
        self.score = Score.getScore(self.cards)

        return self.score
class NetworkControlledPong(object):
    """Our game object! This is a fairly simple object that handles the
    initialization of pygame and sets up our game to run."""

    def __init__(self):
        """Called when the the Game object is initialized. Initializes
        pygame and sets up our pygame window and other pygame tools
        that we will need for more complicated tutorials."""

        pygame.init()

        self.uiServer = GameControllerServer(self, min_players=2,max_players=2)
        self.paddleMap = {}
        self.leftPaddleFree = True
        self.rightPaddleFree = True
        self.started = False

        self.window = pygame.display.set_mode((800, 400))

        self.clock = pygame.time.Clock()

        pygame.display.set_caption("Pong with Android Controller")

        pygame.event.set_allowed([QUIT, USEREVENT])

        self.background = pygame.Surface((800,400))
        self.background.fill((255,255,255))

        pygame.draw.line(self.background, (0,0,0), (400,0), (400,400), 2)
        self.window.blit(self.background, (0,0))

        pygame.display.flip()

        self.sprites = pygame.sprite.RenderUpdates()

        self.leftpaddle = Paddle((50,200))
        self.sprites.add(self.leftpaddle)
        self.rightpaddle = Paddle((750,200))
        self.sprites.add(self.rightpaddle)

        self.ball = Ball((400,200))
        self.sprites.add(self.ball)

        self.scoreImage = Score((400, 50))
        self.sprites.add(self.scoreImage)

        self.pingsound = pygame.mixer.Sound(os.path.join('sound', 'ping.wav'))
        self.pongsound = pygame.mixer.Sound(os.path.join('sound', 'pong.wav'))

        self.uiThread = Thread(target=self.uiServer.serve)
        self.uiThread.start()

    def addPlayer(self, id):
        if self.leftPaddleFree:
            self.paddleMap[id] = self.leftpaddle
            self.leftPaddleFree = False

        elif self.rightPaddleFree:
            self.paddleMap[id] = self.rightpaddle
            self.rightPaddleFree = False

        else:
            print "No paddle free at the moment"

    def removePlayer(self, id):
        try:
            if self.paddleMap[id] == self.leftpaddle:
                self.leftPaddleFree = True
            elif self.paddleMap[id] == self.rightpaddle:
                self.rightPaddleFree = True
            self.paddleMap[id] = None
        except KeyError:
            print "Controller not registered"

    def start(self):
        self.started = True

    def stop(self):
        self.running = False

    def pause(self):
        self.tmpBallVelY = self.ball.vely
        self.tmpBallVelX = self.ball.velx
        self.ball.vely   = 0
        self.ball.velx   = 0
        self.paused      = True

    def resume(self):
        self.ball.vely = self.tmpBallVelY
        self.ball.velx = self.tmpBallVelX
        self.paused    = False

    def run(self):
        """Runs the game. Contains the game loop that computes and renders
        each frame."""

        print 'Waiting for enough controllers'

        while not self.started:
            if self.handleEvents() == False:
                self.uiServer.stop()
                return 0
            else:
                time.sleep(0)

        print 'Enough controllers registered'
        print 'Starting Event Loop'

        self.running = True
        self.paused  = False

        while self.running:
            self.clock.tick(30)

            self.running = self.handleEvents()

            self.manageBall()

            for sprite in self.sprites:
                sprite.update()

            self.sprites.clear(self.window, self.background)    # clears the window where the sprites currently are, using the background
            dirty = self.sprites.draw(self.window)              # calculates the 'dirty' rectangles that need to be redrawn

            pygame.display.update(dirty)                        # updates just the 'dirty' areas

        print 'Quitting. Thanks for playing'
        self.uiServer.stop()
        return 0

    def handleEvents(self):
        """Poll for PyGame events and behave accordingly. Return false to stop
        the event loop and end the game."""

        for event in pygame.event.get():
            if event.type == QUIT:
                return False

            elif event.type == USEREVENT:
                if self.ball.velx == 0 and self.ball.vely == 0 and not self.paused:
                    self.ball.serve()
                if event.key.lower() == "up":
                    self.paddleMap[event.id].up()
                if event.key.lower() == "down":
                    self.paddleMap[event.id].down()
                if event.key.lower() == "stop":
                    return False

        return True


    def manageBall(self):
        self.ball.rect.x += self.ball.velx
        self.ball.rect.y += self.ball.vely

        if self.ball.rect.top < 0:
            self.ball.rect.top = 1
            self.ball.vely *= -1
            self.pongsound.play()

        elif self.ball.rect.bottom > 400:
            self.ball.rect.bottom = 399
            self.ball.vely *= -1
            self.pongsound.play()

        if self.ball.rect.left < 0:
            self.scoreImage.right()
            self.ball.reset()
            return

        elif self.ball.rect.right > 800:
            self.scoreImage.left()
            self.ball.reset()
            return

        collided = pygame.sprite.spritecollide(self.ball, [self.leftpaddle, self.rightpaddle], dokill=False)

        if len(collided) > 0:
            hitpaddle = collided[0]
            self.ball.velx *= -1
            self.ball.rect.x += self.ball.velx
            self.ball.vely += hitpaddle.velocity/3.0
            self.pingsound.play()
    def test_checkForPair(self):
        card = self.cards = [(Card(7, "Hearts")), Card(10, "Diamond"), Card(2, "Diamonds"), Card(10, "Hearts"), Card(2, "Diamonds")]

        temp = Score.checkForPair(card)

        self.assertTrue(len(temp) == 4)
    def test_getScoreStreightlFlush(self):
        cards = self.cards = [(Card(7, "Hearts")), Card(10, "Hearts"), Card(9, "Hearts"), Card(11, "Hearts"), Card(8, "Hearts")]

        self.assertTrue(Score.getScore(cards) == Score.score["StraightFlush"])
Example #55
0
File: main.py Project: Jingoo88/CA2
      PI.PUISSANCE_MOTEUR,\
      R1.DATE_CREATION DATE_CREA_RESERVATION,\
      P1.LOCALISATION_ADRESSE,\
      C1.DELAIS_MOYEN_REPONSE_MESSAGES,\
      ROUND(R1.MONTANT_TOTAL_SANS_CODE_PROMO/NB_JOURS) PRIX_JOURNEE_DATE_TICKET,\
      (SELECT COUNT(*) FROM RESERVATIONS WHERE PK_PRODUITS = P1.PK_PRODUITS AND PK_IX_RESERVATIONS_ETATS = 2 AND DATE_CREATION < R1.DATE_CREATION) NB_RESERVATIONS_DATE_TICKET,\
      (SELECT COUNT(*) FROM CONVERSATIONS WHERE PK_COMPTES_PROPRIETAIRE = P1.PK_COMPTES AND DATE_CREATION < R1.DATE_CREATION) NB_INTERLOCUTEURS_DATE_TICKET,\
      (SELECT COUNT(*) FROM PRODUITS_IMAGES WHERE PK_PRODUITS = P1.PK_PRODUITS AND DATE_CREATION < R1.DATE_CREATION) NB_PHOTOS_DATE_TICKET,\
      (SELECT COUNT(*) FROM RESERVATIONS WHERE PK_PRODUITS = P1.PK_PRODUITS AND DATE_CREATION < R1.DATE_CREATION) NB_DEMANDES_TOTAL_DATE_TICKET,\
      (SELECT COUNT(*) FROM RESERVATIONS WHERE PK_PRODUITS = P1.PK_PRODUITS AND DATE_CREATION < R1.DATE_CREATION AND PK_IX_RESERVATIONS_ETATS = 2) NB_DEMANDES_ACCEPTE_DATE_TICKET,\
      (SELECT AVG(MOYENNE) FROM PRODUITS_EVALUATIONS WHERE PK_PRODUITS = P1.PK_PRODUITS AND DATE_CREATION < R1.DATE_CREATION) NOTE_MOYENNE_DATE_TICKET \
    FROM PRODUITS P1 \
    INNER JOIN RESERVATIONS R1 ON R1.PK_PRODUITS = P1.PK_PRODUITS \
    INNER JOIN PRODUITS_INFORMATIONS_SUPPLEMENTAIRES PI ON PI.PK_PRODUITS = P1.PK_PRODUITS \
    INNER JOIN COMPTES C1 ON C1.PK_COMPTES = P1.PK_COMPTES \
    INNER JOIN FILS_ARIANE D1 ON D1.LNG = P1.LOCALISATION_LNG AND D1.LAT = P1.LOCALISATION_LAT AND D1.PK_IX_LANGAGES = 1 \
    WHERE (SELECT COUNT(*) FROM RESERVATIONS WHERE PK_PRODUITS = P1.PK_PRODUITS AND PK_IX_RESERVATIONS_ETATS = 2) >= 2;"

    sql_query3 = "SELECT * FROM NEW_ALGO_COEFFS"

    Score = Score(sql_query1, sql_query2, sql_query3, data_handler)
    score = Score.get_score()

    data_handler.update_table(score)

    end_time = time.clock()
    total_time = end_time - start_time

    logger.info("Main ended at time %i"%end_time)
    logger.info("Total computing time was %i seconds"%total_time)
    def test_getScore(self):
        cards = self.cards = [(Card(7, "Hearts")), Card(10, "Hearts"), Card(2, "Hearts"), Card(3, "Hearts"), Card(6, "Hearts")]

        score = Score.getScore(cards)

        self.assertTrue(score == Score.score["Flush"])
Example #57
0
class Application():
    """Main class of the game, manage the window"""
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance
            print self.Sound.soundVolume

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
        else:
            self.boss = None

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        Cards1 = []
        Cards2 = []

        # We generate two  and draw 5 cards from each
        # to have an entire Hand of Card
        list1 = [i for i in range(len(allCards))]
        random.shuffle(list1)
        list2 = [i for i in range(len(allCards))]
        random.shuffle(list2)
        for i in range(5):
            number = list1[0]
            Cards1.append(Card(number, 1))
            list1.remove(number)
        for i in range(5):
            number = list2[0]
            Cards2.append(Card(number, -1))
            list2.remove(number)

        # We create the Hands to manage the lists of cards
        self.player1Hand = Hand(Cards1, 1)
        self.player2Hand = Hand(Cards2, -1)

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        #played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        #self.Sound = Sound()
        self.position = None
        self.CARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard)
        self.alphaAnimation = 255
        self.emptyCase = 9

        # Manage the winner congratulations font
        self.winner = None
        self.winnerFont = pygame.font.Font(None, 60)

        # Manage the display of the name of the card selected
        self.cardFont = pygame.font.Font(None, 40)
        self.cardFontSurf = None

        # Manage the background for the name of the card selected
        self.backCard, self.backCardRect = loadImage("name.png")

        self.main()

    def update(self):
        self.screen.blit(self.background, self.background.get_rect())
        for card in self.player1Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
                name = self.CARD.name
                self.cardFontSurf = self.cardFont.render(name, True, white)
                self.cardFontRect = self.cardFontSurf.get_rect()
                self.cardFontRect.midbottom = self.backgroundRect.midbottom
                self.cardFontRect.y -= 10
                self.backCardRect.center = self.cardFontRect.center
                self.backCardRect.centery -= 0

        for card in self.player2Hand.cards:
            if card == self.CARD:
                name = self.CARD.name
                self.cardFontSurf = self.cardFont.render(name, True, white)
                self.cardFontRect = self.cardFontSurf.get_rect()
                self.cardFontRect.midbottom = self.backgroundRect.midbottom
                self.cardFontRect.y -= 10
            self.screen.blit(card.image, card.rect)

        self.scorePlayer1.update()
        self.scorePlayer2.update()
        self.screen.blit(self.scorePlayer1.surface, self.scorePlayer1.rect)
        self.screen.blit(self.scorePlayer2.surface, self.scorePlayer2.rect)
        if self.winner != None:
            self.screen.blit(self.winnerSurface, self.winnerRect)

        if self.cardFontSurf != None:
            self.screen.blit(self.backCard, self.backCardRect)
            self.screen.blit(self.cardFontSurf, self.cardFontRect)
            self.cardFontSurf = None

        pygame.display.flip()
        self.clock.tick(self.fps)

    def main(self):
        self.cardsOwner()
        self.update()
        while 1:
            if self.animation == 1:
                # We continue the animation
                self.putCard()
                self.update()
            else:
                # We over the animation and now the next player have to play.
                if self.sensAnimation == 1:
                    self.player = self.player * -1
                    self.sensAnimation = 0

            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP and self.animation == 0:
                    if self.winner == None:
                        self.playCard()
                elif event.type == QUIT:
                    audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                    setConfig("config.txt", audio)
                    pygame.quit()
                    sys.exit()
                else:
                    # We get the status of all key on keyboard.
                    # Then we select the one at place 27: Escape.
                    # We can do this only if we ran the game
                    # with Menu.py and not directly from main.py
                    if pygame.key.get_pressed()[27] and self.boss != None:
                        self.boss.main()

            pygame.display.flip()
            self.clock.tick(self.fps)

    def playCard(self):
        """When player has to play a card"""

        coords = pygame.mouse.get_pos()

        if self.player == 1:
        # Player 1
            for card in self.player1Hand.cards:
                if card.rect.collidepoint(coords) and card.inHand:
                    self.CARD = card
                    self.selectedCard()
                    break
            if not self.CARD == None:
            # If we clicked on a card.
            # We wait for the event 'MOUSEBUTTONUP', so first we clean the
            #queue event. Then we deactivate the MOUSEMOTION event, because
            #it causes the card to be put randomly on the field!
            #We wait an event, for example a touch on the keyboard
            #pressed, or MOUSEBUTTONUP, but not only, and we reactivate
            #MOUSEMOTION, we could need it later.
                self.deactivate()
                if not self.animation:
                    pygame.event.wait()
                while pygame.event.peek(MOUSEBUTTONUP) and not self.animation:
                    pass
                self.reactivate()
                # If the player clicked on the field this time, we test
                #each cases of the Field.
                if self.field.rect.collidepoint(pygame.mouse.get_pos()):
                    for case in self.field.fieldRects:
                        if case.collidepoint(pygame.mouse.get_pos()):
                            self.position = case.topleft
                            if not self.caseFilled():
                                self.animation = 1
                                self.putCard()
                                self.cardsOwner()
                            return
                else:
                    self.deselectedCard()
                    self.CARD = None

        if self.player == -1:
        # Player -1...I mean Player 2
            for card in self.player2Hand.cards:
                if (card.rect.collidepoint(coords) and card.inHand):
                    self.CARD = card
                    self.selectedCard()
                    break
            if not self.CARD == None:
                # Same as before
                self.deactivate()
                if not self.animation:
                    pygame.event.wait()
                while pygame.event.peek(MOUSEBUTTONUP) and not self.animation:
                    pass
                self.reactivate()
                if self.field.rect.collidepoint(pygame.mouse.get_pos()):
                    for case in self.field.fieldRects:
                        if case.collidepoint(pygame.mouse.get_pos()):
                            self.position = case.topleft
                            if not self.caseFilled():
                                self.animation = 1
                                self.putCard()
                                self.cardsOwner()
                            return
                else:
                    self.deselectedCard()
                    self.CARD = None

    def putCard(self):
            """Animation of a card put on the field"""

            if self.CARD.inHand == 1:
            # We check if self..CARD is in the player's Hand
                self.Sound.playPutCard()

            # We drop the card off the Hand
            if self.CARD.inHand == 1:
                self.CARD.inHand = 0

            # Depending of the direction of the animation, we make the card
            # being invisible or visible again.
            if self.sensAnimation == 0:
                self.alphaAnimation -= 25
                self.CARD.image.set_alpha(self.alphaAnimation)
            elif self.sensAnimation == 1:
                self.alphaAnimation += 25
                self.CARD.image.set_alpha(self.alphaAnimation)

            # We change the position of the card and the animation's direction
            if self.CARD.image.get_alpha() == 5:
                self.CARD.rect.topleft = self.position
                self.sensAnimation = 1

            if self.CARD.image.get_alpha() == 255 and self.sensAnimation == 1:
                # We have put the card on the field and the animation is over
                #Now we have to look if that card captured some of the ennemy's
                self.animation = 0
                adjacentCards = self.getAdjacent()
                capturedCard = adjacent(self.CARD, adjacentCards)
                self.changeOwner(capturedCard)
                self.emptyCase -= 1
                self.CARD = None

            if self.emptyCase == 0:
                self.winAnimation()

    def selectedCard(self):
        """Player has selected a card
        But not yet a place on the field"""
        for i in range(5):
            self.CARD.rect.centerx += 4 * self.player
            self.update()

    def deselectedCard(self):
        """Finally, the player wants an other card"""
        for i in range(5):
            self.CARD.rect.centerx -= 4 * self.player
        self.CARD = None
        self.update()

    def deactivate(self):
        """Deactivate MOUSEMOTION event and clean the queue"""
        pygame.event.set_blocked(MOUSEMOTION)
        pygame.event.clear()

    def reactivate(self):
        """Get back MOUSEMOTION"""
        pygame.event.set_allowed(MOUSEMOTION)

    def caseFilled(self):
        """Say if there is already a card in the case"""
        for card in self.player1Hand.cards:
            if card.rect.topleft == self.position:
                return 1
        for card in self.player2Hand.cards:
            if card.rect.topleft == self.position:
                return 1
        return 0

    def cardsOwner(self):
        """Which cards is owned by who?"""
        cardPlayer = 0
        for card in self.player1Hand.cards:
            if card.owner == self.player:
                cardPlayer += 1
        for cards in self.player2Hand.cards:
            if cards.owner == self.player:
                cardPlayer += 1
        if self.player == 1:
            self.scorePlayer1.updateScore(cardPlayer)
            self.scorePlayer2.updateScore(10 - cardPlayer)
        elif self.player == -1:
            self.scorePlayer1.updateScore(10 - cardPlayer)
            self.scorePlayer2.updateScore(cardPlayer)

    def getAdjacent(self):
        """Get all the adjacent cards of the first one put"""
        posx, posy = self.CARD.rect.topleft
        adjacentCards = [None, None, None, None]
        if self.player == 1:
            for card in self.player2Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        elif self.player == -1:
            for card in self.player1Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        return adjacentCards

    def changeOwner(self, cards):
        for card in cards:
            if card.owner == 1:
                self.player1Hand.cards.remove(card)
                self.player2Hand.cards.append(card)
            if card.owner == -1:
                self.player2Hand.cards.remove(card)
                self.player1Hand.cards.append(card)
            self.capturedAnimation(card)
        self.cardsOwner()

    def capturedAnimation(self, card):
        # We want the sound of the card put played before doing anything more
        self.update()
        while (pygame.mixer.get_busy()):
            pass

        # self.Sound.capturedCard.play()
        width = card.rect.width  # we expect 113. If not please change format.
        height = card.image.get_rect().height  # Here we expect 139.
        topleft = list(card.rect.topleft)
        print height, "\t", topleft
        step = 16

        while(width != 1):
            width -= step
            topleft[0] += step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        card.owner *= -1
        card.changeOwner(card.rect.center)

        while (width != 113):
            width += step
            topleft[0] -= step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

    def winAnimation(self):
        if self.scorePlayer1.score > self.scorePlayer2.score:
            self.winner = u"Blue win!"
        elif self.scorePlayer2.score > self.scorePlayer1.score:
            self.winner = u"Red win!"
        else:
            self.winner = u"Equality!"
        self.winnerSurface = self.winnerFont.render(self.winner, True, white)
        self.winnerRect = self.winnerSurface.get_rect()
        self.winnerRect.midtop = self.backgroundRect.midtop
        self.winnerRect.y += 10
    def test_getScoreRoayalFlush(self):
        cards = self.cards = [(Card(14, "Hearts")), Card(10, "Hearts"), Card(13, "Hearts"), Card(11, "Hearts"), Card(12, "Hearts")]

        self.assertTrue(Score.getScore(cards) == Score.score["RoyalFlush"])
Example #59
0
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance
            print self.Sound.soundVolume

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
        else:
            self.boss = None

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        Cards1 = []
        Cards2 = []

        # We generate two  and draw 5 cards from each
        # to have an entire Hand of Card
        list1 = [i for i in range(len(allCards))]
        random.shuffle(list1)
        list2 = [i for i in range(len(allCards))]
        random.shuffle(list2)
        for i in range(5):
            number = list1[0]
            Cards1.append(Card(number, 1))
            list1.remove(number)
        for i in range(5):
            number = list2[0]
            Cards2.append(Card(number, -1))
            list2.remove(number)

        # We create the Hands to manage the lists of cards
        self.player1Hand = Hand(Cards1, 1)
        self.player2Hand = Hand(Cards2, -1)

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        #played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        #self.Sound = Sound()
        self.position = None
        self.CARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard)
        self.alphaAnimation = 255
        self.emptyCase = 9

        # Manage the winner congratulations font
        self.winner = None
        self.winnerFont = pygame.font.Font(None, 60)

        # Manage the display of the name of the card selected
        self.cardFont = pygame.font.Font(None, 40)
        self.cardFontSurf = None

        # Manage the background for the name of the card selected
        self.backCard, self.backCardRect = loadImage("name.png")

        self.main()