예제 #1
0
def answer():
    if request.method == 'GET':
        return render_template('game.j2')
    if 'game_id' not in session and 'user_name' in session:
        filde = {'user_name': session['user_name']}
        game_play = Games(**filde)
        game_play.save()
        game_id = Games.select().order_by(Games.game_id.desc()).get()
        game_id = model_to_dict(game_id)['game_id']
        session['game_id'] = game_id
    answer = str(request.form['answer'])
    if 'riddle' in session:
        if answer.lower() == session['riddle']['answer'].lower():
            fields = {
                'game_result': True,
                'riddle': session['riddle']['id'],
                'game': session['game_id']
            }
            GameResulte(**fields).save()
            session.pop('riddle', None)
            return redirect(url_for('game'))
        else:
            resulte = 0
            resulte = GameResulte.select().where(
                GameResulte.game == session['game_id']).count()
            if not resulte:
                resulte = 'game over'
            session.pop('game_id', None)
            session.pop('riddle', None)
            session['resulte'] = resulte
            return redirect(url_for('index'))
    return render_template('game.j2')
예제 #2
0
파일: utils.py 프로젝트: le087/naval-battle
def add_new_game(new_field):
    """add new game in database
    
    - `new_field`: object field
    """
    new_game = Games(fields=[new_field])
    new_game.save()
    return new_game
예제 #3
0
def get_list_archive_game(firstdate, seconddate):
    """ returh list archive games

    - return dictionary in format:
              { 'date' : date,
                'players': user VS user }

    - `firstdate`: date from first field on archive.html
    - `seconddate`: date from second field on archive.html
    """
    if firstdate == '' and seconddate == '':
        games = Games.objects(status=2)
    elif seconddate == '' or firstdate == '':
        try:
            if firstdate and len(firstdate) == 10:
                year = int(firstdate[-4:])
                month = int(firstdate[3:5])
                day = int(firstdate[:2])
                dt = datetime.datetime(year, month, day)
                games = Games.objects(status=2, time_begin__gte=dt)
            elif seconddate and len(seconddate) == 10:
                year = int(seconddate[-4:])
                month = int(seconddate[3:5])
                day = int(seconddate[:2])
                dt = datetime.datetime(year, month, day)
                games = Games.objects(status=2, time_begin__gte=dt)
            else:
                return False
        except: 
            return False
    else:
        if len(firstdate) != 10 and len(seconddate) != 10:
            return False
        try:
            year_f = int(firstdate[-4:])
            month_f = int(firstdate[3:5])
            day_f = int(firstdate[:2])
            dt_first = datetime.datetime(year_f, month_f, day_f)
            year_s = int(seconddate[-4:])
            month_s = int(seconddate[3:5])
            day_s = int(seconddate[:2])
            dt_second = datetime.datetime(year_s, month_s, day_s)
            if dt_first < dt_second:
                dt_second = datetime.datetime(year_s, month_s, day_s, 23, 59, 59)
                games = Games.objects( Q(status=2) & (Q(time_begin__gte=dt_first) & Q(time_begin__lte=dt_second)))
            else:
                dt_first = datetime.datetime(year_f, month_f, day_f, 23, 59, 59)
                games = Games.objects( Q(status=2) & (Q(time_begin__lte=dt_first) & Q(time_begin__gte=dt_second)))
        except:
            return False
    if games:
        dict_game = {}
        for game in games:
            note = Logs.objects(game=game)[0]
            dict_game[str(note.game.id)] = { 'date' : note.game.time_begin.strftime('%d-%m-%Y'),
                                             'players': note.move_user + ' VS ' + note.opponent }
        return dict_game
    return True
예제 #4
0
def add_game():
    camilo = request.get_json()
    game = Games(
        name=camilo["name"],
        category=camilo["category"],
    )
    db.session.add(game)
    db.session.commit()  
    return jsonify(game.to_dict())
예제 #5
0
파일: services.py 프로젝트: kramschu/9dt
    def _create_game(self, players, columns, rows):
        error = Validators()._validate_board(players, columns, rows)
        if error:
            return error

        # This step is currently not needed. The players table is not used.
        # TODO: replace all player_name references with foreign_key on
        # primary_key
        player_ids = []
        for player in players:
            player_row = Players.query.filter_by(player_name=player).first()
            if player_row is None:
                new_player = Players(player_name=player)
                db.session.add(new_player)
                db.session.commit()
                player_row = Players.query.filter_by(
                    player_name=player).first()
            player_ids.append(player_row.player_name)
        player_ids = ','.join(map(str, player_ids))

        new_game = Games(players=str(player_ids),
                         game_columns=columns,
                         game_rows=rows,
                         game_state="IN_PROGRESS")
        db.session.add(new_game)
        db.session.commit()
        game_id = new_game.game_id
        return jsonify({"gameId": str(game_id)})
예제 #6
0
def index(resulte=None):
    game_played = Games.select().order_by(Games.game_id.desc()).count()
    query = Users.select(
        Users.user_name,
        peewee.fn.COUNT(Users.user_name).alias('total_points')).join(
            Games).join(GameResulte).group_by(Users.user_name).order_by(
                peewee.fn.COUNT(Users.user_name).desc()).limit(3)
    top_players = []
    try:
        for user in query:
            top_players += [{
                'name': user.user_name,
                "total_points": user.total_points
            }]
    except peewee.ProgrammingError as err:
        print(err)
    if 'resulte' in session:
        resulte = str(session['resulte'])
        session.pop('resulte', None)
        return render_template('index.j2',
                               game_played=game_played,
                               top_players=top_players,
                               resulte=resulte)
    return render_template('index.j2',
                           game_played=game_played,
                           top_players=top_players)
예제 #7
0
def add_title(request):
	newtitle = request.GET['title']
	if newtitle != '':
		try:
			existingGame = Games.objects.get(title=newtitle)
			return render_to_response('gameexist.html')
		except:
			newgame = Games()
			newgame.title = newtitle
			newgame.save()
			us =  User.objects.get(username__exact=request.user.username)
			us.employee.lastVoted = datetime.date.today()
			us.employee.save()
			us.save()
			gv = GameVote()
			gv.game_id = newgame
			gv.save()
	return HttpResponseRedirect('/home/')
예제 #8
0
def add_title(request):
    newtitle = request.GET['title']
    if newtitle != '':
        try:
            existingGame = Games.objects.get(title=newtitle)
            return render_to_response('gameexist.html')
        except:
            newgame = Games()
            newgame.title = newtitle
            newgame.save()
            us = User.objects.get(username__exact=request.user.username)
            us.employee.lastVoted = datetime.date.today()
            us.employee.save()
            us.save()
            gv = GameVote()
            gv.game_id = newgame
            gv.save()
    return HttpResponseRedirect('/home/')
예제 #9
0
파일: downloader.py 프로젝트: powellae/DFS
 def AddNewGame(self):
     game_new = Games(HomeTeamId=self.HomeTeamId,
                      HomeTeamScore=self.HomeTeamScore,
                      AwayTeamId=self.AwayTeamId,
                      AwayTeamScore=self.AwayTeamScore,
                      GameStatusId=self.GameStatusId,
                      GameTypeId=self.GameTypeId,
                      GameDate=self.GameDate,
                      GameLink=self.GameLink)
     self.game_new = game_new
예제 #10
0
파일: utils.py 프로젝트: le087/naval-battle
def get_wait_users():
    """return list of users who are waiting game
    """
    now = datetime.datetime.now()
    time_old = now + datetime.timedelta(minutes = -2)
    users_wait = Users.objects(status=0, last_time__gte=time_old)
    for user in users_wait:
        try:
            field = Fields.objects.get(id=user.field_battle.id)
        except:
            field = Fields()
            field.save()
        try:
            game = Games.objects.get(id=user.game.id)
            game.fields = [field]
            game.save()
        except:
            game = Games(fields=[field])
            game.save()
        user.field_battle = field
        user.game = game
        user.save()
    return users_wait
예제 #11
0
    def notifyUsersActiveGames():
        activeGames = Games.query(Games.active == True).fetch()
        # print activeGames

        for ag in activeGames:
            user = Users.get_by_id(ag.user_id)
            mail.send_mail(
                'noreply@%s.appspotmail.com' %
                (app_identity.get_application_id()),  # from
                user.email,  # to
                'Reminder',  # subj
                'Reminder: You have an active game! '  # body
                # 'gameInfo:\r\n\r\n%s' % ag.
            )
예제 #12
0
def get_begin_games():
    """return list begin games
    
    the structure of dictionary is:
    { 'id_game':['user1', 'user2'],
      'id_game':['user1', 'user2']}
    """
    games_begin = Games.objects(Q(status=1) | Q(status=3))
    users = Users.objects(game__in=games_begin)
    games = {}
    for user in users:
        game = user.game
        id_game = str(game.id)
        if games.has_key(id_game):
            games[id_game].append(user.user_name)
        else:
            games[id_game] = [user.user_name]
    return games
예제 #13
0
def createNewGame(user_id):
    """instantiates a new game and adds a player to the game"""

    #first check if user is already playing a game
    u = Users.query.get(user_id)
    if u.game_id:
        return [Games.query.get(u.game_id), 'user already playing game']

    while True:
        rand_code = random.randrange(10000, 99999)
        existing_code = Games.query.filter_by(code=rand_code).first()

        if not existing_code:
            g = Games(code=rand_code)
            db.session.add(g)
            db.session.commit()

            u.game_id = g.id
            u.isAdmin = True
            db.session.commit()
            return [g, 'created new game']
예제 #14
0
파일: utils.py 프로젝트: le087/naval-battle
def get_begin_games():
    """return list begin games
    
    the structure of dictionary is:
    { 'id_game':['user1', 'user2'],
      'id_game':['user1', 'user2']}
    """
    now = datetime.datetime.now()
    time_old = now + datetime.timedelta(minutes = -60)
    games_begin = Games.objects(Q(status=1) | Q(status=3))
    users = Users.objects(game__in=games_begin)
    games = {}
    for user in users:
        if user.last_time < time_old:
            pass
        else:
            game = user.game
            id_game = str(game.id)
            if games.has_key(id_game):
                games[id_game].append(user.user_name)
            else:
                games[id_game] = [user.user_name]
    return games
예제 #15
0
    with open('games.log', 'r') as file:
        file_data = file.read().split('\n')

    for line in file_data:
        line_elements = line.split()
        try:
            if line_elements[1] == 'InitGame:':
                if not file_parser._game:
                    file_parser.new_game_started()

                else:
                    game_hash = file_parser.generate_hash()
                    file_parser.print_game(game_hash)

                    game = Games()
                    game.game_info = file_parser._game.data_to_store()
                    game.hash_game = game_hash

                    db.add(game)
                    db.commit()
                    file_parser.new_game_started()

            elif line_elements[1] == 'Kill:':
                file_parser.check_kill(line_elements[2], line_elements[3])

            elif line_elements[1] == 'ClientUserinfoChanged:':
                file_parser.user_info_changed(line_elements)

        except IndexError:
            game_hash = file_parser.generate_hash()
예제 #16
0
def create_game_route():
	content = request.json
	game_types = [
		'basic_addition',
		'advanced_addition',
		'basic_subtraction' ,
		'advanced_subtraction',
		'basic_multiplication',
		'advanced_multiplication', 
		'basic_division',
		'advanced_division',
		'basic_mixed',
		'advanced_mixed', 
		'add_fractions',
		'subtract_fractions',
		'multiply_fractions',
		'divide_fractions',
		'simplify_fractions', 
		'angles',
		'perimeter', 
		'area',
		'pythagorean',
		'average',
		'median',
		'range',
		'dollars_and_cents',
		'exponents_and_powers',
		'square_roots'
	]

	if content['game_type'] not in game_types:
		return jsonify({
				'status' : 'error',
				'message' : 'Invalid game type.'
			})
	number_of_questions = int(content['number_of_questions'])

	#MAKE TEMPORARY UNIQUE JOIN CODE
	found_join_code = False
	join_code = ""
	while found_join_code == False:
		join_code = generate_short_code()
		query = Games.query.filter_by(live_game = 1).filter_by(join_code = join_code).first()
		if query == None:
			found_join_code = True

	#CREATE GAME HERE
	game_id = generate_random_string(10,20)
	new_game = Games(
		game_id,
		"public",
		content['game_type'],
		number_of_questions,
		1,
		join_code
	)
	db.session.add(new_game)

	#CREATE QUESTIONS
	for x in range(number_of_questions):
		question_data = create_question(content['game_type'])
		new_question = Questions(
			generate_random_string(10,200),
			game_id,
			x + 1,
			question_data['question_text'],
			question_data['answer']
		)
		db.session.add(new_question)

	db.session.commit()

	return jsonify({
			'status' : 'success',
			'game_id' : game_id
		})
예제 #17
0
    for event in events:
        rot_away = event.rotation_away
        rot_home = event.rotation_home

        # We need to see if we have already stored this game
        result_count = Games.query.filter_by(game_id=event.rundown_id).count()

        if result_count > 0:
            print('Game already exists in DB. Skipping.')

        elif event.event_status == 'STATUS_CANCELED':
            print('Game cancelled. Skipping')

        else:
            game = Games()
            game.game_date = event.datetime
            game.game_id = event.rundown_id
            game.team_away_name = event.team_away_name
            game.team_home_name = event.team_home_name
            game.rotation_away = event.rotation_away
            game.rotation_home = event.rotation_home
            game.event_status = event.event_status
            game.score_away = event.score_away
            game.score_home = event.score_home
            game.winner_away = event.winner_away
            game.winner_home = event.winner_home

            games_added.append(game)
            db.session.add_all(games_added)
            db.session.commit()
예제 #18
0
    def createGame(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
            return newGameMSGout(msg='Not Logged In!',
                                 uv='',
                                 game_id=0,
                                 hint_one='',
                                 hint_two='',
                                 hint_three='')
        email = user.email()
        user2 = Users.query(Users.email == email).get()
        # print user2
        if not user2:
            msg = 'Email Does Not Exist In App. Please Create Account.'
            return newGameMSGout(msg=msg,
                                 uv='',
                                 game_id=0,
                                 hint_one='',
                                 hint_two='',
                                 hint_three='')

        user_id = user2.key.id()
        checkGame = Games \
        .query(ndb.AND(Games.user_id == user_id, Games.active == True)).get()
        if checkGame:
            msg = ''' You already have an active game. That game must be
                finished before starting a new one.
                You Guessed %s Times.''' % checkGame.tries
            return newGameMSGout(msg=msg,
                                 uv='',
                                 game_id=0,
                                 hint_one='',
                                 hint_two='',
                                 hint_three='')

        game = random.choice(options)
        uv = randomVal()

        newGame = Games(user_id=user_id,
                        uv=uv,
                        answer=game['answer'],
                        hint_one=game['hintONE'],
                        hint_two=game['hintTWO'],
                        hint_three=game['hintTHREE'])

        ng = newGame.put()
        # print ng
        ng = ng.id()
        user2.current_game_id = ng
        user2.put()

        taskqueue.add(params={
            'email':
            email,
            'gameInfo':
            'New Game!!! https://gamewai-142922.appspot.com/'
        },
                      url='/tasks/send_newgame_email')

        return newGameMSGout(msg='New Game Created! Guess Who It Is...',
                             uv=newGame.uv,
                             game_id=ng,
                             hint_one=newGame.hint_one,
                             hint_two=newGame.hint_two,
                             hint_three=newGame.hint_three)
예제 #19
0
 def get_form_kwargs(self):
     kwargs = super(SubmitGame, self).get_form_kwargs()
     kwargs['instance'] = Games()
     if self.request.user.is_authenticated():
         kwargs['instance'].name = self.request.user
     return kwargs
예제 #20
0
파일: views.py 프로젝트: plutokamin/pujiahh
 def get_form_kwargs(self):
     kwargs = super(SubmitGame, self).get_form_kwargs()
     kwargs['instance'] = Games()
     if self.request.user.is_authenticated():
         kwargs['instance'].name = self.request.user
     return kwargs