Example #1
0
    def new_game(self, request):
        """This function creates a new game.
        Input: Two Usernames; Only The first is required,
        if the second is not given, the first player will be playing
        with an Automate (Computer)"""
        player = utils.get_by_username(request.player)

        if not request.opponent:
            opponent = Player.query(Player.username == "computer").get()
        else:
            opponent = utils.get_by_username(request.opponent)

        newgame = Game(player=player.key, opponent=opponent.key)
        newgame.put()
        # initialize players position
        Position(game=newgame.key, player=player.key, position=0).put()
        Position(game=newgame.key, player=opponent.key, position=0).put()

        # update score
        Score(game=newgame.key, player=player.key, score=0).put()
        Score(game=newgame.key, player=opponent.key, score=0).put()

        return NewGameForm(player=player.username,
                           opponent=opponent.username,
                           urlsafekey=newgame.key.urlsafe())
Example #2
0
def init_db():
    Base.metadata.create_all(bind=engine)
    player1 = Player(name="player1")
    db_session.add(player1)
    sc = Score(rule='ガチヤグラ',
               power=1900,
               weapon='スクリュースロッシャー',
               result='WIN',
               player=player1)
    db_session.add(sc)
    sc = Score(rule='ガチエリア',
               power=1920,
               weapon='スクリュースロッシャー',
               result='WIN',
               player=player1)
    db_session.add(sc)
    player2 = Player(name="player2")
    sc = Score(rule='ガチアサリ',
               power=2100,
               weapon='スプラシューター',
               result='WIN',
               player=player2)
    db_session.add(sc)
    sc = Score(rule='ガチエリア',
               power=2320,
               weapon='スプラシューターベッチュー',
               result='WIN',
               player=player2)
    db_session.add(sc)
    db_session.commit()
Example #3
0
    def add_player(self, user_in, pass_in):
        """
        Add a player to the database game
        return:
        True if everything is OK
        False if the user already exists
        """
        exists = False

        for user in User.select():
            if user_in.upper() == user.username.upper(
            ) and user.is_active == 1:
                exists = True
                response = False

        if not exists:
            user = User(username=user_in,
                        password=pass_in,
                        is_admin=0,
                        is_active=1)
            user.save()
            try:
                score = Score(score=0, date=date.today(), id_user=user.id_user)
                score.save()
                response = True
            except AttributeError:
                response = False

        return response
Example #4
0
def play():
    """Main function"""
    print('Hello in my AWESOME GAME!!!')
    name = input('Tell me yor NAME, my brave player: ')
    player = Player(name)
    enemy = Enemy()
    score = Score('scores.txt')
    while True:
        print('_' * 50)
        print('{}, make your choice!'.format(player.name))
        print('For start the GAME type "START"')
        print('For help about GAME type "HELP"')
        print('For view the scores of game type "SCORE"')
        print('For exit from GAME type "EXIT"')
        choice = input('>>>  ').lower()
        while choice not in ALLOWED_COMMANDS:
            choice = input('You are funny one))))\n' 'Try one more time: ')
        if choice == 'start':
            start(player, enemy)
        elif choice == 'help':
            _help()
        elif choice == 'score':
            score.print_score()
        else:
            raise KeyboardInterrupt
Example #5
0
def home():
    if 'email' not in session:
        return redirect(url_for('login'))

    user = User.query.filter_by(email=session['email']).first()

    form = ScoreForm()

    my_scores = []
    #my_scores = Score.query.filter_by(uid=user.uid)
    my_scores = Score.query.all()

    print(my_scores)

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('home.html', form=form)
        else:
            # submit the score into the db
            newscore = Score(user.uid, form.score.data)
            db.session.add(newscore)
            db.session.commit()

            # return those results
            return render_template('home.html', form=form, my_scores=my_scores)
    if request.method == 'GET':
        return render_template("home.html", form=form, my_scores=my_scores)
 def test_get_score_has_played(self):
     score_object = Score(player="Player1", score=9)
     self.math.session.add(score_object)
     self.math.session.commit()
     self.math.score = 3
     expected_result = {"has_played": True, "player_score": 9}
     self.assertEqual(self.math.get_score(), expected_result)
Example #7
0
    def create_score(payload, player_id):
        sub = payload.get('sub')
        check_user_id = Player.query.filter(
            Player.user_id == sub).one_or_none()
        # check if player_id is same as player_id come from JWT payload
        # if they are not same, abort.
        if check_user_id.id != player_id:
            print(' different user, no permission to create')
            abort(401)

        body = request.get_json()
        new_player_id = player_id
        new_course_id = body.get('course_id', None)
        new_score = body.get('score', None)
        new_date = body.get('date', None)
        try:
            score = Score(player_id=new_player_id,
                          course_id=new_course_id,
                          score=new_score,
                          date=new_date)
            score.insert()
            return jsonify({'added_score': new_score})

        except BaseException:
            abort(422)
Example #8
0
def connect_match_data_season_1617():
    df = pd.read_csv("./data/season_files/season1617.csv").drop(["Unnamed: 0"],
                                                                axis=1)
    n_rels = 0
    n_nodes = 0
    for _, row in df.iterrows():
        # NODES
        # Hometeam
        ht = Team.nodes.get(name=row["Home/Neutral"])
        # Visitor
        vt = Team.nodes.get(name=row["Visitor/Neutral"])
        # HomeScore
        hs = Score(score=row["PTS.1"]).save()
        # VisitorScore
        vs = Score(score=row["PTS"]).save()
        # Arena
        a = ht.arena.get()
        # Season
        s = Season.get_or_create({"name": "2016/2017"})[0]
        # Date
        d = Date.get_or_create({
            "datetime":
            datetime.strptime(row["Date"] + " " + row["Start (ET)"],
                              "%Y-%m-%d %I:%M %p")
        })[0]
        # Game
        g = Game(game_name=row["game_name"],
                 game_type=row["game_type"],
                 ot=row["OT"]).save()
        n_nodes += 1

        # RELATIONSHIPS
        # Team -> Score
        ht.scored.connect(hs)
        vt.scored.connect(vs)
        # Score -> Game
        hs.in_game.connect(g)
        vs.in_game.connect(g)
        # Game -> Season
        g.season.connect(s)
        # Game -> Date
        g.date.connect(d)
        # Game -> Arena
        g.arena.connect(a)
        n_rels += 7
    print("created (approx:) {} nodes and {} relationships".format(
        n_nodes, n_rels))
Example #9
0
 def test_float_serialization(self):
     """Tests that float values serialize and deserialize intact"""
     sc = Score(score=3.4)
     sc.save()
     serial_str = serializers.serialize(self.serializer_name, [sc])
     deserial_objs = list(serializers.deserialize(self.serializer_name,
                                             serial_str))
     self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1))
Example #10
0
 def test_init_invalid_state_code(self):
     with self.assertRaises(ValueError) as e:
         Score(
             criterion_id=self.criterion.id,
             state='fake-state',
             meets_criterion=True,
         )
     self.assertEqual(str(e.exception), invalid_state)
Example #11
0
 def test_init_invalid_criterion(self):
     with self.assertRaises(ValueError) as e:
         Score(
             criterion_id=0,
             state=self.state.code,
             meets_criterion=True,
         )
     self.assertEqual(str(e.exception), criterion_not_found)
Example #12
0
def save_result(session, test_id, questions_total, questions_correct):
    user_id = db.query(User).filter_by(session_token=session).first().id
    result = Score(user_id=user_id,
                   test_id=test_id,
                   questions_total=questions_total,
                   questions_correct=questions_correct)
    db.add(result)
    db.commit()
Example #13
0
 def save_score(self, score):
     score_info = self.get_score()
     if score_info["has_played"] is True and score_info["player_score"] < score:
         self.session.query(Score).filter(Score.player == self.player).update({"score": score})
         self.session.commit()
     if score_info["has_played"] is False:
         score_object = Score(player=self.player, score=score)
         self.session.add(score_object)
         self.session.commit()
Example #14
0
 def post(self, request):
     score = request.POST.get('score')
     question_id = request.POST.get('question_id')
     question = Question.objects.get(pk=question_id)
     
     score = Score(question=question,user=request.user,score=int(score))
     score.save()
     
     return HttpResponse(status=201)
def sample():
    db_session.add(Score(student_id='2015A7PS0033G',
                         course_id='ECON F211',
                         name='T2',
                         score=20))
    db_session.add(Score(student_id='2015A7PS0033G',
                         course_id='ECON F211',
                         name='T1',
                         score=18))
    db_session.add(Score(student_id='2015A7PS0033G',
                         course_id='ECON F211',
                         name='Quiz',
                         score=20))
    db_session.add(Score(student_id='2015A7PS0033G',
                         course_id='ECON F211',
                         name='Compre',
                         score=36))
    db_session.commit()
Example #16
0
def evaluate_hand(hand):
    """
    Evaluates a hand of cards against the defined poker hands (form highest to lowest) and returns a score.
    """
    for poker_hand in reversed(POKER_HANDS):
        rank_scores = poker_hand(hand)

        if any(rank_scores):
            return Score(hand, POKER_HANDS.index(poker_hand), rank_scores)
Example #17
0
def addScoreDB(key):
    if key.has_key('jd') == False:
        key['jd'] = None
    school_year = str(key['xnmmc'])
    school_term = int(key['xqmmc'])
    class_name = str(key['kcmc'])
    class_code = str(key['kch_id'])
    if len(class_code) > 10:
        class_code = class_code[0:8]
    credit = float(key['xf'])
    class_category = str(key['kcxzmc'])
    test_category = str(key['ksxz'])
    cjsfzf = str(key['cjsfzf'])
    score = str(key['cj'])
    if score =="中等":
        score = "75"
    if score =="合格":
        score = "65"
    if score =="良好":
        score = "85"
    if score =="优秀":
        score = "95"  
          
 
    if score >= "90":
        GPA=4.0
    elif score >= "80":
        GPA=3.0
    elif score >= "70":
        GPA=2.0
    elif score >= "60":
        GPA=1.0
    else:
        GPA=0.0
            
    class_mark = str(key['kcbj'])
    if key.has_key('kkbmmc') == False:
        key['kkbmmc'] = None
    class_ownership = str(key['kkbmmc'])
    stu_id = str(key['xh'])
    sco = Score.query.filter(Score.school_year == school_year).filter(Score.school_term == school_term).filter(
        Score.class_name == class_name).filter(Score.test_category == test_category).filter(Score.stu_id == stu_id).first()
    if sco:
        sco.credit = credit
        sco.class_category = class_category
        sco.test_category = test_category
        sco.cjsfzf = cjsfzf
        sco.score = score
        sco.GPA = GPA
        sco.class_mark = class_mark
        sco.class_ownership = class_ownership
        db.session.commit()
    else:
        sco = Score(school_year, school_term, class_name, class_code, credit, class_category,
                    test_category, cjsfzf, score, GPA, class_mark, class_ownership, stu_id)
        db.session.add(sco)
        db.session.commit()
Example #18
0
def create_score():
    data = request.get_json()
    score = Score(
        criterion_id=data.get('criterion_id'),
        state=data.get('state'),
        meets_criterion=data.get('meets_criterion'),
    ).save()

    return jsonify(score.serialize()), 201
Example #19
0
def process_score():
    tournament_id = 1
    if session['hole_num'] >= 18:
        session['hole_num'] = 1
        #session['round_num'] += 1
        db.session.add(Round(session['round_num'], tournament_id))
        db.session.add(
            Round_Player_Table(round_id=session['round_num'], player_id=1))
        db.session.add(
            Round_Player_Table(round_id=session['round_num'], player_id=2))
        db.session.add(
            Round_Player_Table(round_id=session['round_num'], player_id=3))
        db.session.add(
            Round_Player_Table(round_id=session['round_num'], player_id=4))
        db.session.commit()
        return redirect('/leaderboard')

    player_1_Score = int(request.form['player_1_score'])
    player_2_Score = int(request.form['player_2_score'])
    player_3_Score = int(request.form['player_3_score'])
    player_4_Score = int(request.form['player_4_score'])
    db.session.add(
        Score(round_id=session['round_num'],
              hole_id=session['hole_num'],
              player_id=1,
              score=player_1_Score))
    db.session.add(
        Score(round_id=session['round_num'],
              hole_id=session['hole_num'],
              player_id=2,
              score=player_2_Score))
    db.session.add(
        Score(round_id=session['round_num'],
              hole_id=session['hole_num'],
              player_id=3,
              score=player_3_Score))
    db.session.add(
        Score(round_id=session['round_num'],
              hole_id=session['hole_num'],
              player_id=4,
              score=player_4_Score))
    session['hole_num'] += 1
    db.session.commit()
    return redirect('/score_input')
Example #20
0
def parser(stu_id, html):
    # 根据HTML网页字符串创建BeautifulSoup
    soup = BeautifulSoup(
        html,  # HTML文档字符串
        'html.parser',  # HTML解析器
    )
    stu = Student.query.filter(Student.id == stu_id).first()
    tables = soup.findAll('table')
    tab = tables[0]
    count = 1
    lists = []
    for tr in tab.findAll('tr'):
        if count != 1:
            td = tr.findAll('td')
            for text in td:
                score = text.getText().strip()
                if score == '':
                    score = None
                lists.append(score)
            # 判断课程是否已存在于Subject表中
            sub_obj = Subject.query.filter(
                Subject.class_name == lists[3]).first()
            # 不存在则新插入该课程
            if sub_obj == None:
                sub = Subject(lists[0], lists[1], lists[2], lists[3], lists[4],
                              lists[6], lists[5], lists[9], lists[12],
                              lists[14], lists[15])
                db.session.add(sub)
                db.session.commit()
            # 判断学生没有拥有该课程
            if sub_obj not in stu.subject:
                sub = Subject.query.filter(
                    Subject.class_name == lists[3]).first()
                stu.subject.append(sub)
                db.session.add(stu)
                sub = Subject.query.filter(
                    Subject.class_name == lists[3]).first()
                score = Score(lists[8], lists[7], sub.id, stu_id, lists[10],
                              lists[11], lists[13])
                db.session.add(score)
                db.session.commit()
            # 如果拥有该课程,则更新数据
            else:
                for cla in stu.subject:
                    if cla == sub_obj:
                        cla.score[0].score = lists[8]
                        cla.score[0].GPA = lists[7]
                        cla.score[0].resit_score = lists[10]
                        cla.score[0].restudy_score = lists[11]
                        cla.score[0].note = lists[13]
                        cla.minor_tab = lists[9]
                        cla.resit_tab = lists[14]
                        db.session.commit()
                        break
            lists = []
        count = count + 1
Example #21
0
 def setUp(self):
     self.state = create_state()
     self.category = create_category()
     self.subcategory = create_subcategory(self.category.id)
     self.criterion = create_criterion(self.subcategory.id)
     self.score = Score(
         criterion_id=self.criterion.id,
         state=self.state.code,
         meets_criterion=True,
     ).save()
Example #22
0
def update_scores(request):

    if request.method == "POST":
        #question_list = request.POST.getlist('question_list[]')
        subtopic_list = request.POST.getlist('subtopic_list[]')
        level_list = request.POST.getlist('level_list[]')
        quiz_scores = request.POST.getlist('score_list[]')
        user = request.user

        totals_list = []
        for j in range(len(subtopic_list)):
            subtopic_level_answered, subtopic_level_correct = 0, 0
            for i in range(len(subtopic_list)):
                if subtopic_list[i] == subtopic_list[j] and level_list[
                        i] == level_list[j]:
                    subtopic_level_answered += 1
                    if str(quiz_scores[i]) == '1':
                        subtopic_level_correct += 1
            component = {
                'subtopic': subtopic_list[j],
                'level': level_list[j],
                'answered': subtopic_level_answered,
                'correct': subtopic_level_correct
            }
            if component not in totals_list:
                totals_list.append(component)

        for total in totals_list:
            subtopic = Subtopic.objects.get(name=total['subtopic'])
            try:
                current_score = Score.objects.get(user=user,
                                                  subtopic=subtopic,
                                                  level=int(total['level']),
                                                  is_current=True)
            except Score.DoesNotExist:
                current_score = None
            if current_score:
                cur_ans = current_score.number_answered
                cur_cor = current_score.number_correct
                current_score.is_current = False
                current_score.save()
            else:
                cur_ans = 0
                cur_cor = 0

            score = Score(user=user,
                          subtopic=subtopic,
                          level=int(total['level']))
            score.number_answered = cur_ans + total['answered']
            score.number_correct = cur_cor + total['correct']
            # score = % of correct, history independent
            score.score = total['correct'] / float(total['answered'])
            score.save()

        return HttpResponse('Success')
Example #23
0
 def entry_actions(self):
     self.score_label.set_text("Your score: " + str(GameApp.current_score))
     new_score = Score(score=GameApp.current_score, player_id=GameApp.current_player.id)
     GameApp.session.add(new_score)
     GameApp.session.commit()
     
     #Check if the game result is a high-score
     if GameApp.current_score > (GameApp.high_score_list[len(GameApp.high_score_list)-1][1] if GameApp.high_score_list else 0):
         self.menu_title.set_text("CONGRATULATIONS: HIGH SCORE!")
     else:
         self.menu_title.set_text("GAME OVER!")
 def create_user(self, request):
     """Create a User. Requires a unique username"""
     if User.query(User.name == request.user_name).get():
         raise endpoints.ConflictException(
             'A User with that name already exists!')
     user = User(name=request.user_name, email=request.email)
     user.put()
     score = Score(parent=user.key, wins=0, losses=0, ties=0)
     score.put()
     return StringMessage(
         message='User {} created!'.format(request.user_name))
def set_student_score(teacher_nid):
    '''设置学生分数'''

    print('set student')
    student_list = student_info(teacher_nid)
    choice = int(input('请选择学生:').strip())
    number = float(input('请输入分数:').strip())
    obj = Score(number)
    obj.save()
    student_list[choice].score_nid = obj.nid
    student_list[choice].save()
    print('------成绩设置成功------')
    def new_score(cls, cpf, score_type, value):
        score_value = cls.score_from_type(value, score_type)

        logger.info(f'Inc score to {cpf} by {score_value} from type {score_type} and value {value}')

        score = Score()
        score.cpf = cpf
        score.type = score_type
        score.value = value
        score.score = score_value

        return score
Example #27
0
def create_score():
    """Creates a new score for a specified idea"""
    score = request.get_json()
    new_score = Score(
        idea_id = score["idea_id"],
        user_id = g.user.id,
        score = score["score"]
    )
    db.session.add(new_score)
    db.session.commit()
    score['id'] = new_score.id
    score['user_id'] = g.user.id
    return _todo_response(score)
Example #28
0
def determine_scores(game_round):

    wins_dict = defaultdict(int)

    for play in game_round.plays:
        wins_dict[play.winner] += 1

    player_scores = Score(game_round.players)
    for p, bid in game_round.bids.items():
        if bid == wins_dict[p]:
            player_scores.add_points(p, 10 + bid)

    return player_scores
    def test(self, score_class_mock):
        save_mock = Mock(return_value=None)
        score_class_mock.return_value.save = save_mock

        storage = Storage()
        storage.populate()
        self.assertEqual(save_mock.call_count, 1)

        score = Score()
        score.score = 1234
        score_class_mock.objects.all.return_value.order_by.return_value = QuerySetMock(
            score_class_mock, score)
        score = storage.get_score()
        self.assertEqual(score, 1234)
Example #30
0
def update_high_score(address, score):
    from models import Score
    score_obj = Score.query.filter(Score.address == address).first()
    if not score_obj:
        score_obj = Score(address, score)

        db.session.merge(score_obj)
        db.session.commit()
        return 'success'

    if score_obj and score_obj.score and score > score_obj.score:
        score_obj.score = score
        db.session.merge(score_obj)
        db.session.commit()
    return 'success'