Exemple #1
0
def load_game():
    import Utils
    import MemoryGame
    import GuessGame
    import Score
    print(
        "Please choose a game to play: \n 1. Memory Game - a sequence of numbers will appear for 1 second and you have to guess it back \n 2. Guess Game - guess a number and see if you chose like the computer"
    )
    choosegame = input()
    print("Please choose game difficulty from 1 to 5 :")
    if (choosegame > "2") or (choosegame < "1"):
        print(Utils.ERROR_MESSAGE), load_game()
    choosegame = int(choosegame)
    difficulty = input()
    if (difficulty > "5") or (difficulty < "1"):
        print(Utils.ERROR_MESSAGE), load_game()
    difficulty = int(difficulty)
    if choosegame == 1:
        if MemoryGame.play(difficulty) == True:
            Score.add_score(difficulty)
        else:
            load_game()
    elif choosegame == 2:
        if GuessGame.play(difficulty) == True:
            Score.add_score(difficulty)
        else:
            load_game()
def load_game():
    print(Utils.GAMES_AVAILABLE)

    # game and difficulty choosing process
    game_chosen = Utils.validate_user_input(1, 2, "game")

    difficulty = Utils.validate_user_input(1, 5, "difficulty")

    game_result = None

    # running games by user's choice
    if game_chosen == 1:
        game_result = MemoryGame.play(difficulty)

    elif game_chosen == 2:
        game_result = GuessGame.play(difficulty)

    # checking weather the user won or lost - Refer to the play method in either GuessGame or MemoryGame
    if game_result:
        print("Congratulation! YOU WON")
        Score.add_score(difficulty)
    else:
        print("Close but not quit right")
        Score.add_score(0)
        load_game()
Exemple #3
0
def load_game():
    game_num = 0
    game_dif = 0
    score = 0
    while score == 0:
        while game_num < 1 or game_num > 2:
            try:
                game_num = int(
                    input(
                        "1. Memory Game - a sequence of numbers will appear for 1 second and you have to guess it back.\r\n"
                        "2. Guess Game - guess a number and see if you chose like the computer\r\n"
                        "0. To cancel"))
            except ValueError as ee:
                print("Incorrect input. Try again.")
            if game_num == 0:
                exit()
        while game_dif < 1 or game_dif > 5:
            try:
                game_dif = int(
                    input("Please choose game difficulty from 1 to 5:"))
            except ValueError as ee:
                print("Incorrect input. Try again.")
        if game_num == 1:
            score = MemoryGame.play(game_dif)
        if game_num == 2:
            score = GuessGame.play(game_dif)
        if score > 0:
            score_file = "Scores.txt"
            Score.add_score(score_file, score)
            return
Exemple #4
0
    def __init__(self, master=None):
        """
        Constructeur de l'application
        Initialise tous les éléments visuels, sonores et touches
        @param master: Fenetre mère tkinter
        """

        self.canvas = None
        self.main_frame = None
        self.hp_canvas = None
        self.frameHeros = None
        self.rows = None
        self.ennemies = None
        self.vague = 1

        super().__init__(master)
        self.master = master
        self.pack(fill="both")
        self.score = Score()
        self.create_HPBAR()
        self.create_MAIN()
        self.hero = Joueur(ask_name())
        self.drawJoueur()
        self.init_game(fullreset=True)
        self.pause()
        self.init_sound()
        self.init_touch_binding()
Exemple #5
0
class GameWorld(object):
    """
    GameWorld
    The game world
    """
    def __init__(self, sense):
        """
        Initialize the game world
        :param sense The sense hat
        """
        self.level = Level()
        self.score = Score()
        self.mappy = Map(0, 7)
        self.snake = Snake(3, self.mappy)
        self.candy = Candy(self.snake)
        self.sense = sense
        self.i = 0
        print(self.snake)
        self.sense.clear()
        self.sense.show_message("Level: " + str(self.level.level),
                                text_colour=[180, 180, 180])

    def update(self, delta):
        """
        Compute all the objects
        :param delta The loop delta
        :return The dead state of the snake
        :return The score
        """
        deadStatus = False
        # UPS: 60 -> 2 * 60 = 120
        if (self.i >= (1.0 / self.snake.speed) * 120):
            deadStatus = self.snake.update(delta)
            self.__isEating__()
            print(self.snake)
            self.i = 0
        else:
            self.i += 1
        return (not deadStatus, self.score.score)

    def __isEating__(self):
        """
        Detect when the Snake eat a candy
        """
        head = self.snake.positions[0]
        if (head.x == self.candy.x and head.y == self.candy.y):
            self.score.increaseScore(self.snake, self.level)
            speed = int(self.snake.speed * 10)
            if (speed % 10 == 0):
                self.level.level += 1
                self.sense.clear()
                self.sense.show_message("Level: " + str(self.level.level),
                                        text_colour=[180, 180, 180])
                self.sense.clear()
                self.sense.show_message("Score: " + str(self.score.score),
                                        text_colour=[180, 180, 180])
                self.sense.clear()
            self.candy.randomize()
Exemple #6
0
def play(difficulty):
    pc_number = generate_number(difficulty)
    result = compare_results(difficulty, pc_number)

    if result:
        print("You won the game! " + str(difficulty) + " added to your score.")
        Score.add_score(difficulty)
    else:
        print("You lose!")
def score_server():
    html = None
    try:
        Score.connect_db()
        score = Score.read_score_from_db()
        html = f"<html><head><title>Scores Game</title></head><body><h1>The score is <div id=\"score\">{score}</div></h1></body></html>"
    except BaseException as e:
        html = f"<html><head><title>Scores Game</title></head><body><body><h1><div id=\"score\" style=\"color:red\">{e}</div></h1></body></html>"
    Score.disconnect_db()
    return html
def checkAnswer(qNum):
    answer = int(input("R: "))
    if (answer == c.correctAnswer[qNum]):
        c.currentGamePoints += 5
        return True
    else:
        ap.addPoints("Puntajes.txt", c.currentGamePoints)
        ap.graphScore("Puntajes.txt")
        bf.quitGame()
        return False
def score_server():
    try:
        Score.connect_db()
        text = Score.read_score_from_db()
        color = "black"
    except BaseException as e:
        text = e
        color = "red"
    Score.disconnect_db()
    return render_template('score.html', color=color, text=text)
Exemple #10
0
def play(difficulty):
    secret_number = get_guess_from_user(difficulty)

    if compare_results(difficulty, secret_number):
        print("You won!")
        Score.add_score(difficulty)
        return True
    else:
        print("You lost")
        Score.add_score(0)
        Live.load_game()
        return False
Exemple #11
0
def play(length, width, choice, Player_Bet, list_score, list_bet_score):
    winsound.PlaySound("Music\\Racing.wav",
                       winsound.SND_LOOP + winsound.SND_ASYNC)
    FinishLine = RaceTrack.Draw_RaceTrack(length, width)

    list_characters = Character_Implement.Settings_Characters(choice)
    list_shapes = Character_Implement.Setting_Shapes(choice, list_characters)
    list_names = [
        list_characters[0].Name, list_characters[1].Name,
        list_characters[2].Name, list_characters[3].Name,
        list_characters[4].Name
    ]

    list_rank = [0, 1, 2, 3, 4]
    random.shuffle(list_rank)
    list_place = [0, 0, 0, 0, 0]

    for step in range(5):
        for step2 in range(5):
            if list_rank[step2] == step:
                list_place[step] = step2

    RaceTrack.Arrange_Characters(list_characters, length, width, list_shapes,
                                 list_rank)
    RaceTrack.display_Name(list_names, list_place, Player_Bet)

    start_time = time.time()
    list_time = [0, 0, 0, 0, 0]

    while Settings.End_Match_Condition(list_characters, FinishLine) == 1:
        for ID in range(5):
            Character_Implement.Running(list_characters, list_shapes, ID,
                                        choice, FinishLine, list_time,
                                        start_time)

    for step in range(0, 5):
        if step != Settings.Check_Who_First(list_time)[0]:
            list_characters[step].Lose()
            Character_Implement.Losing(list_characters[step])

    Character_Implement.Winner(
        list_characters[Settings.Check_Who_First(list_time)[0]])

    list_ID_rank = Settings.Check_Who_First(list_time)

    Announcement.Annoucement(
        Settings.Win_Lose_Condition(Player_Bet,
                                    Settings.Check_Who_First(list_time)[0]),
        list_ID_rank, list_names, list_time)

    Score.Count_Score(list_ID_rank, list_score)
    Score.Count_Bet_Score(list_ID_rank, list_bet_score, Player_Bet)
    pass
def play(num):
    generate_sequence(num)
    get_list_from_user(num)
    result = is_list_equal()
    if result:
        Score.write_score(num)
        print(
            "You have guessed right and won the game. \n The computer have also chosen %s"
            % generated_list)
    else:
        print("Wrong guess , You have lost! \n The computer have chosen %s" %
              generated_list)
Exemple #13
0
def draw_score():
    score = Score.Get_Score()
    x_off = Globals.margin[
        0] * 2 + Globals.image_size * Gameboard.Gameboard_size
    y_off = Globals.margin[1] + Globals.image_size * 2
    TextHandler.RenderScore(str(score), x_off, y_off)
    combo = Score.Get_Combo()
    x_off = Globals.margin[
        0] * 2 + Globals.image_size * Gameboard.Gameboard_size
    y_off = Globals.margin[1] + 64
    TextHandler.RenderCombo(("x" + str(combo)), x_off, y_off)
    Globals.update_score = False
def cal_score(ref_lines, probs):
    line_count = 0
    pred_lines = defaultdict(list)
    for ref_line in ref_lines:
        ref_line = ref_line.replace('\n', '')
        parts = ref_line.strip().split()
        qid, aid, lbl = int(parts[0]), int(parts[2]), int(parts[3])
        pred_lines[qid].append((aid, lbl, probs[line_count]))
        line_count += 1
    MAP=Score.calc_mean_avg_prec(pred_lines)
    MRR=Score.calc_mean_reciprocal_rank(pred_lines)
    return MAP, MRR
Exemple #15
0
def play(difflevel):
    get_money_interval(difflevel)
    get_guess_from_user()
    if user_guess_entry > from_interval and user_guess_entry < upto_interval:
        print(
            "You have guessed it approximately right and won the game. \n The rate of USDILS is %f"
            % USDILS)
        Score.write_score(difflevel)
        return True
    else:
        print("Wrong guess , You have lost! \n  The rate of USDILS is %f" %
              USDILS)
        return False
Exemple #16
0
def load_game():
    no_exception = False  # Flag to keep info whether exception was thrown or not
    while no_exception == False:
        print(
            "Please choose a game to play: \n"
            "\t1. Memory Game - a sequence of  numbers  will appear for 1 second and you have to guess it back \n"
            "\t2. Guess Game - guess a number and see if you  chose like the computer \n"
            "\t3. Currency  Roulette - try and guess the value of a random amount of USD in ILS"
        )
        try:
            user__game_choice = int(input(">>>"))
            if user__game_choice not in range(1, 4):
                raise ValueError
            else:
                no_exception = True  # The exception was not thrown, so the loop will be finished.
        except ValueError as e:
            print(
                "\t\t!!!!!!!!!!!!!!!   Numbers 1, 2, 3 are only allowed   !!!!!!!!!!!!!!!!!\n"
            )

    no_exception = False  # Flag to keep info whether exception was thrown or not
    while no_exception == False:
        print("Please choose game difficulty from 1 to 5:")
        try:
            user__dificulty_choice = int(input(">>>"))
            if user__dificulty_choice not in range(1, 6):
                raise ValueError
            else:
                no_exception = True  # The exception was not thrown, so the loop will be finished.
        except ValueError as e:
            print(
                "\t\t!!!!!!!!!!!!!!!   Numbers from 1 to 5 are only allowed   !!!!!!!!!!!!!!!!!\n"
            )

    if user__game_choice == 2:
        GuessGame.set_difficulty(user__dificulty_choice)
        result = GuessGame.play()
    elif user__game_choice == 1:
        MemoryGame.set_difficulty(user__dificulty_choice)
        result = MemoryGame.play()
    elif user__game_choice == 3:
        CurrencyRouletteGame.set_difficulty(user__dificulty_choice)
        result = CurrencyRouletteGame.play()

    if result == True:
        print("                                     You won")
        Score.add_score(user__dificulty_choice)
    else:
        print("                                     You lost")
        Score.create_zero_score()
Exemple #17
0
def getScore(steamId, games):
    data = games
    achievements = getPlayerAchievements(steamId, data)
    #for austin
    totalHoursPerGame = getHoursPerGame(data)
    totalPossibleAchievements = getTotalAchievements(achievements)
    earnedAchievement = achievementEarned(achievements)
    numberOfGames = data['game_count']

    percenti = Score.percent(earnedAchievement, totalPossibleAchievements)
    aveHours = Score.getNumHours(totalHoursPerGame) / numberOfGames
    #def score(numGames, percent, avHours)
    score = Score.score(numberOfGames, percenti, aveHours)
    return score
def play(difficulty):
    list_a = generate_sequence(difficulty)
    print(list_a)
    Utils.screen_cleaner()
    list_b = get_list_from_user(difficulty)
    if is_list_equal(list_a, list_b):
        print("You won!")
        Score.add_score(difficulty)
        return True
    else:
        print("You lost")
        Score.add_score(0)
        Live.load_game()
        return False
def play(difflevel):
    generate_number(difflevel)
    if not get_guess_from_user(difflevel):
        print("You have chosen an incorrect Value! , please try again! ")
        exit(10)
    result = compare_results()
    if result == True:
        Score.write_score(difflevel)
        print(
            "You have guessed right and won the game. \n The computer have also chosen %d"
            % secret_number)
    else:
        print("Wrong guess , You have lost! \n The computer have chosen %d" %
              secret_number)
Exemple #20
0
def quitGame():
    global background, ball
    #restoration parametres terminal
    global old_settings
    os.system("clear")

    #couleur white
    sys.stdout.write("\033[37m")
    sys.stdout.write("\033[40m")

    Score.scores(ball)
    #pour jouer une seconde partie
    askContinueGame()
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
    sys.exit()
Exemple #21
0
def addPlayer(player_name, tournament):
    """ Adds a player to the database and initializes the
        player's scoreboard

        Args:
            player_name = name of player to be added to the database
            tournament = id of tournament where the player will play
    """

    name = player_name
    insertPlayer = "INSERT INTO players (name) VALUES (%s) RETURNING id"
    cursor.execute(insertPlayer, (name,))
    player = cursor.fetchone()[0]
    conn.commit()
    Score.add_to_board(player, tournament)
Exemple #22
0
 def __init__(self, sense):
     """
     Initialize the game world
     :param sense The sense hat
     """
     self.level = Level()
     self.score = Score()
     self.mappy = Map(0, 7)
     self.snake = Snake(3, self.mappy)
     self.candy = Candy(self.snake)
     self.sense = sense
     self.i = 0
     print(self.snake)
     self.sense.clear()
     self.sense.show_message("Level: " + str(self.level.level),
                             text_colour=[180, 180, 180])
Exemple #23
0
def main():
    fileSeq = "../files/maguk-sequences.fasta"
    fileMatrice = "../files/blosum62.iij"
    parsedFiles = Parser(fileSeq, fileMatrice)
    #=============== Sequences ================
    mySequences = parsedFiles.getSeq()
    # for elem in mySequences:
    # 	print(elem)
    #==========================================

    #================ Blosum ==================
    listAA = parsedFiles.getListAA()
    blosum = parsedFiles.getBlosum()
    blosumObj = Blosum(listAA, blosum)
    #print(blosumMatrice)

    # print(mySequences[0])
    # print(mySequences[1])

    x1 = ["T", "H", "I", "S", "L", "I", "N", "E", "D", "E", "D", "E", "D"]
    x2 = ["I", "S", "A", "L", "I", "G", "N", "E", "D", "A", "D", "I"]
    x1 = ["T", "H", "I", "S", "L", "I", "N", "E"]
    x2 = ["I", "S", "A", "L", "I", "G", "N", "E", "D"]
    x1 = mySequences[0].getSeq()
    x2 = mySequences[2].getSeq()
    x1 = ["M", "G", "G", "E", "T", "F", "A"]
    x2 = ["G", "G", "V", "T", "T", "F"]

    print(x1)
    print(x2)
    test = Score(x1, x2, blosumObj, -4)
    def get_rmsle_list(self, dataset, num_folds, n_estimators_list):
        self.num_iterations += 1
        print 'n_estimators_list: %s' % n_estimators_list
        rmsle_list = []
        score = Score.Score()

        for fold_ind in range(num_folds):
            print '  fold_ind: %d' % fold_ind
            fold_train = dataset.getTrainFold(fold_ind)
            fold_test = dataset.getTestFold(fold_ind)
            self._train(fold_train, n_estimators_list)
            score.addFold(fold_test.getSales(), self.predict(fold_test))

            for month_ind in range(12):
                cur_rmsle = score.getRMSLE(month_ind)
                rmsle_list.append(cur_rmsle)

                if cur_rmsle < self.best_rmsle_list[month_ind]:
                    self.is_best = True
                    self.best_rmsle_list[month_ind] = cur_rmsle
                    self.n_estimators_list[month_ind] = n_estimators_list[
                        month_ind]

        print 'best_n_estimators_list: %s' % self.n_estimators_list
        return rmsle_list
Exemple #25
0
def new_game():
    from Graphic_Element import draw_graphic_elements
    Globals.do_new_game = False
    Gameboard.random_Gameboard()
    Score.Reset_Score()
    Globals.selected_element = (-1, -1)
    Gameboard.check_availible_moves()
    set_start_time()
    set_game_state(Globals.Game_State.ready)
    Graphic_Element.clear_graphic_elements()
    Seeds.reset()
    while not Globals.do_quit:
        update_ticks()
        Globals.clock.tick()
        Globals.screen.fill((0, 0, 0))
        draw_background()
        game_loop()
        for x in range(0, Gameboard.Gameboard_size):
            for y in range(0, Gameboard.Gameboard_size):
                obj = Gameboard.Gameboard[x][y]
                if (obj is not None):
                    obj.update()
                    obj.draw(x, y)
        if not Globals.selected_element == (-1, -1):
            element = get_selected_element()
            if element is not None:
                element.draw_box(Globals.selected_element)
        draw_score()
        Seeds.draw_seed_interface()
        if Globals.game_state != Globals.Game_State.game_over:
            draw_time_left()
        draw_graphic_elements(get_ticks())
        pygame.display.flip()
        Globals.clock.tick_busy_loop(60)
    Globals.do_quit = False
Exemple #26
0
  def cross_validate(self, dataset, num_folds):
    dataset.createFolds(num_folds)
    best_params = None
    best_rmsle = float("inf")
    for C in SVMRegression.C_vals:
      for poly_degree in SVMRegression.poly_degrees:
        if self.debug:  
          print "Running SVM regression with C=%d, poly_degree=%d on %d folds" %(C, poly_degree, num_folds)

        cur_score = Score.Score()

        for fold_ind in range(num_folds):
          fold_train = dataset.getTrainFold(fold_ind)
          fold_test = dataset.getTestFold(fold_ind)
          self._train_with_values(fold_train, poly_degree=poly_degree, C=C)
          cur_score.addFold(fold_test.getSales(), self.predict(fold_test))
          
        cur_rmsle = cur_score.getRMSLE()
        if cur_rmsle < best_rmsle:
          if self.debug:
            print "Achieved new best score %f" %cur_rmsle
          best_params = (C, poly_degree)
          best_rmsle = cur_rmsle
        
    self.C, self.poly_degree = best_params
 def __init__(self, d):
     self.doc = d
     self.maxLyrics = 0
     self.lastVolta = 0
     self.beamMode = BeamMode.BEAM_NO
     self.score = Score.Score(defaultStyle)
     self.measureLength = list()
Exemple #28
0
def initialize_complex_map(N, groups, data_set, dataset_reduction_factor):
    the_map = np.zeros((N, N))

    data_set_with_line_scores = []

    for i in range(0, N):
        line_score = 0
        for j in range(0, i):
            slide_first = data_set[i]
            slide_second = data_set[j]
            the_map[i][j] = sc.score(slide_first, slide_second)
            the_map[j][i] = the_map[i][j]
            line_score = line_score + the_map[i][j]
        data_set_with_line_scores.append((line_score, data_set[i]))
    # ax = sns.heatmap(the_map)

    # plt.show()
    data_set_with_line_scores.sort(key=lambda tup: tup[0])  # sorts in place
    print("sorted dataset from map with start:" + data_set_with_line_scores[0] + "and end:" + data_set_with_line_scores[len(data_set_with_line_scores)-1] + " scores.")
    desired_number_of_elements = N // dataset_reduction_factor
    # get last N elements
    reduced_data_set_with_scores = data_set_with_line_scores[-desired_number_of_elements:]
    print("reduced dataset from map with start potential score of:" + reduced_data_set_with_scores[0] + "and end:" + reduced_data_set_with_scores[
        len(reduced_data_set_with_scores) - 1] + " scores.")
    # get only the slides
    reduced_data_set = [i[1] for i in reduced_data_set_with_scores]
    # get first N elements
    rest_of_reduced_population_with_scores = data_set_with_line_scores[N - desired_number_of_elements:]
    # get only the slides
    rest_of_reduced_population = [i[1] for i in rest_of_reduced_population_with_scores]
    return the_map, reduced_data_set, rest_of_reduced_population
Exemple #29
0
    def get_rmsle_list(self, dataset, num_folds, alpha_list, rho_list):
        self.num_iterations += 1

        rmsle_list = []

        score = Score.Score()
        for fold_ind in range(num_folds):
            fold_train = dataset.getTrainFold(fold_ind)
            fold_test = dataset.getTestFold(fold_ind)
            self._train(fold_train, alpha_list, rho_list)
            score.addFold(fold_test.getSales(), self.predict(fold_test))

        for month_ind in range(12):
            cur_rmsle = score.getRMSLE(month_ind)
            rmsle_list.append(cur_rmsle)

            if cur_rmsle < self.best_rmsle_list[month_ind]:
                self.is_best = True
                self.best_rmsle_list[month_ind] = cur_rmsle
                self.alpha_list[month_ind] = alpha_list[month_ind]
                self.rho_list[month_ind] = rho_list[month_ind]

        print "alpha_list: %s" % alpha_list
        print "best_rho_list: %s" % str(self.rho_list)
        print "best_alpha_list: %s" % str(self.alpha_list)
        return rmsle_list
Exemple #30
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # self.donIndex_list = []
        # self.don_list = []

        # self.push_changeOrder.clicked.connect(self.push_changeOrder_clicked)
        # self.push_add.clicked.connect(self.push_add_clicked)
        # self.push_del.clicked.connect(self.push_del_clicked)
        # self.push_addBeat.clicked.connect(self.push_addBeat_clicked)
        # self.push_delBeat.clicked.connect(self.push_delBeat_clicked)
        # self.MAX_WIDTH = self.label_beat.width()
        # self.beatInfo = {'beats':[], 'hIndex':-1}

        self.label_beat.setFixedSize(self.scrollArea.height() * 2 / 3,
                                     self.scrollArea.height() * 2 / 3)
        self.horizontalLayout.addStretch(1)

        self.push_load.clicked.connect(self.push_load_clicked)
        self.push_save.clicked.connect(self.push_save_clicked)
        self.noteList = list()
        self.beatList = list()
        self.highlightBeatLabel = None
        self.score = Score.TJA()
        # print(self.label_beat.width())

        # sample code
        self.push_create.clicked.connect(self.push_create_clicked)
        self.undoStack = QUndoStack(self)
        self.donList = []
        self.donNum = 0
def initialize_complex_map(N, groups, data_set, ith_chunk_nr,
                           number_of_chunks):

    desired_number_of_elements = N // number_of_chunks
    chunk_start_index = desired_number_of_elements * ith_chunk_nr
    chunk_end_index = min(N, chunk_start_index + desired_number_of_elements)

    the_map = np.zeros((N, N))

    data_set_with_line_scores = []

    for i in range(chunk_start_index, chunk_end_index):
        line_score = 0
        for j in range(chunk_start_index, i):
            slide_first = data_set[i]
            slide_second = data_set[j]
            the_map[i][j] = sc.score(slide_first, slide_second)
            the_map[j][i] = the_map[i][j]
            line_score = line_score + the_map[i][j]
        data_set_with_line_scores.append((line_score, data_set[i]))
    # ax = sns.heatmap(the_map)

    # plt.show()
    data_set_with_line_scores.sort(key=lambda tup: tup[0])  # sorts in place

    return the_map
def reportMatch(tournament, winner, loser, draw='FALSE'):
    """
        Reports a match's result to the database and assigns
        corresponding points to a player
        Args:
            tournament =  id of tournament where the match took place
            winner = id of the winner
            loser =  id of the loser
            draw =  true if the match is  a draw
    """

    if draw == 'TRUE':
        wPoint = 1
        lPoint = 1
    else:
        wPoint = 3
        lPoint = 0

    Match.add(tournament, winner, loser)
    Score.add(tournament, winner, wPoint)
    Score.add(tournament, loser, lPoint)
def deleteMatches():
    """Removes all match records from the database."""

    Match.deleteAll()
    Score.reset()
def deletePlayers():
    """Removes all player records from the database."""

    Player.deleteAll()
    Score.deleteAll()
    return data


data = Encoding(data, general_matrix)
test_data = Encoding(test_data, general_matrix)

p = pca(n_components=2)
pca_cal(standardize_dataset(data), labels.T[0].tolist(), data, title = "PCA with z-score normalization on training set")
pca_cal(standardize_dataset(test_data), test_labels, test_data, title = "PCA with z-score normalization on test set")
data[:, 4:] = standardize_dataset(data[:, 4:])
test_data[:, 4:] = standardize_dataset(test_data[:, 4:])

# Seperate dataset to test and train set
kf = KFold(n=len(data), n_folds=10, shuffle=True)
train, test = kf.get_indices()
s = Score()

total_cv_error = []
total_test_error = []
confusion_matx = []
f1score = []
for k in range(1, 100, 5):
    cv_error = []
    test_error = []
    nn = Pipeline([
            ('feature_selection', SelectFromModel(LinearSVC(penalty="l2"))),
            ('classification', KNeighborsClassifier(n_neighbors=k, metric='manhattan'))
        ])
    for i in range(10):
        print "round %d %d" % (k, i)
        train_data = data[train[i]]
def deleteScoreboard():
    """Removes all score records from the database."""

    Score.deleteAll()
# Simple Explorartory Analysis
# Bar plots
for col in data.columns:
    agg = data.groupby([col, 'class']).count()
    sns.set_style("whitegrid")
    ax = sns.barplot(x=agg.ix[:, [0]].index.values, y=agg.ix[:, [0]].values.T[0])
    plt.title("Distribution of " + col)
    plt.show()

# PCA
pca_cal(standardize_dataset(ndata.as_matrix()), data['class'], data.columns, title="PCA with normalization")

# Seperate dataset to test and train set
kf = KFold(n=len(ndata), n_folds=10, shuffle=True)
train, test = kf.get_indices()
s = Score()

total_train_error = []
total_test_error = []

for k in range(1, 200, 3):
    train_error = []
    test_error = []
    for i in range(10):
        print "round %d %d" % (k, i)
        train_data = ndata.ix[train[i]]
        test_data = ndata.ix[test[i]]

        #######TRAIN#####
        nn = NearestNeighborsClassifier(n_neighbors=k)
Exemple #38
0
width = 900
height = 700
size = width, height

bgColor = r,b,g = 255,255,255

screen = pygame.display.set_mode(size)

balls = []
ballTimer = 0
ballTimerMax = 2 * 60

player = PlayerPaddle( ["Pics/Player/player.png"], [10,10], [10, 300])
player2 = PlayerPaddle( ["Pics/Player/player2.png"], [10,10], [880, 300])

scoreP1 = Score([300, 350])
scoreP2 = Score([600, 350])

endScore = 3
lastScore = random.randint(1,2)
beginningScore = 0

while True:
    while scoreP1.score < endScore and scoreP2.score < endScore:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                sys.exit()
            
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    player.go("up")
             Wall([550,150],[600,250]), 
             Wall([100,450],[150,600]), #10
             Wall([100,550],[250,600]), 
             Wall([450,550],[600,600]), 
             Wall([550,450],[600,600]), 
             Wall([150,300],[250,400]), 
             Wall([300,150],[400,250]), #15
             Wall([450,300],[550,400]), 
             Wall([300,450],[400,550]), #17
           ]  
    
    ghosts = [Ghost("purple", [random.randint(5, 8)*50+25,random.randint(5, 8)*50+25]),
          Ghost("blue", [random.randint(5, 8)*50+25,random.randint(5, 8)*50+25]),
          Ghost("green", [random.randint(5, 8)*50+25,random.randint(5, 8)*50+25])]

    score = Score("Score: ", (125,25))
    lives = Score("Lives: ", (125,675))
    while player.living and len(orbs) > 0:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player.go("up")
                elif event.key == pygame.K_DOWN:
                    player.go("down")
                elif event.key == pygame.K_LEFT:
                    player.go("left")
                elif event.key == pygame.K_RIGHT:
                    player.go("right")
            elif event.type == pygame.KEYUP:
               "21", "22", "23",
               "31", "32", "33"]
 
 deadGhosts = {}
 
 files = os.listdir("Levels/")
 for f in files:
     if f[-4:] == ".sav":
         os.remove("Levels/"+f)
 lx = 1
 ly = 1
 level = Level("Levels/Map"+str(lx)+str(ly))
 
 player = Manpac([7,7], (602,602))
 
 score = Score("Score: ", 0, (125,25))
 lives = Score("Lives: ", 5,  (125,675)) 
 while lives.score >= 5 and len(levelsLeft)>0: 
     for event in pygame.event.get():
         if event.type == pygame.QUIT: 
             sys.exit()
         elif event.type == pygame.KEYDOWN:
             if event.key == pygame.K_w or event.key == pygame.K_UP:
                 player.go("up")
             elif event.key == pygame.K_s or event.key == pygame.K_DOWN:
                 player.go("down")
             elif event.key == pygame.K_a or event.key == pygame.K_LEFT:
                 player.go("left")
             elif event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                 player.go("right")
         elif event.type == pygame.KEYUP:
import matplotlib.pyplot as plt
import seaborn as sns
from legacy_script import *
from LeaveNOut import *
from sklearn.svm import SVR
import pdb

data = pd.read_csv('Water_data.csv')
# Split data into labels and features
train_labels, train_data = np.hsplit(data, [3])

# Normalization
train_data = standardize_dataset(train_data)
train_labels = train_labels.as_matrix()

#Try with different neighbors and different leave N out cross validation:
for n in [1, 3]:
    plot_data = []

    for i in range(1, 30, 1):
        model = NearestNeighborsRegressor(n_neighbors=i)
        runner = LeaveNOut()
        predict, true = runner.run(data=train_data, model=model, labels=train_labels, n_out=n)
        score = Score()
        plot_data.append([score.c_score(np.array(predict)[:, 0], np.array(true)[:, 0]), i, 'c_total'])
        plot_data.append([score.c_score(np.array(predict)[:, 1], np.array(true)[:, 1]), i, 'Cd'])
        plot_data.append([score.c_score(np.array(predict)[:, 2], np.array(true)[:, 2]), i, 'Pb'])

    line_plot(np.array(plot_data), title="C_index by different K Neighbors - Leave %s out CV" % n,
              x_title="K Neighbors", y_title="C-Index")
from kNN import NearestNeighborsRegressor
from sklearn.neighbors import KNeighborsRegressor
from Score import *
import matplotlib.pyplot as plt
import seaborn as sns
from legacy_script import *
from LeaveNOut import *
from sklearn.svm import SVR
import pdb

input = pd.read_csv('./Soil_water_permeability_data/INPUT.csv',header=None)
output = pd.read_csv('./Soil_water_permeability_data/OUTPUT.csv', header=None)
coordinates = pd.read_csv('./Soil_water_permeability_data/COORDINATES.csv', header=None)

# Normalization
std_input = standardize_dataset(input)
plot_data = []

for n in range(0,201,10):
    model = NearestNeighborsRegressor(n_neighbors=5)
    runner = LeaveNOut(zone_radius=n)
    predict, true = runner.run(data=std_input, model=model, labels=output.as_matrix(), n_out=1, coordinates = coordinates.as_matrix())
    score = Score()
    plot_data.append([score.c_score(np.array(predict)[:, 0], np.array(true)[:, 0]), n, 'Concordance Index'])
    print "epoch %d " % n

line_plot(np.array(plot_data), title="Concordance index by different Dead zone radius - Leave 1 out CV",
              x_title="Dead zone radius", y_title="C-Index")


                if event.key == pygame.K_BACKSPACE:
                    run = "menu"
                
        all.update(width, height)
        
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(60)  
        
        for s in all.sprites():
         s.kill()
    
    BackGround("RSC/Background/Illuminati.png", True, [0,-1])

    score = Score([width-300, height-25], "Score: ", 80)

    spawnRate = .3 #seconds

    player1 = Player((width/2, height/2), 1)
    player2 = Player((width/2, height/2), 2)

    while run == "game":
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    player1.go("up")
                if event.key == pygame.K_UP:
                    player2.go("up")
                if event.key == pygame.K_d: