Exemplo n.º 1
0
 def get(self, request):
     form = GameForm(request.GET)
     if form.is_valid():
         game = form.get_game()
         return self.render_to_response({"game": [game]})
     else:
         return self.render_to_response({"request_error": form.errors, "game": []})
Exemplo n.º 2
0
def new(request):
    game_form = GameForm(request.user)
    screenshot_form = formset_factory(ScreenshotForm, extra=4, min_num=4, max_num=8)
    
    if request.method == "POST":
        game_form = GameForm(request.user, request.POST, request.FILES)
        screenshot_form = screenshot_form(request.POST, request.FILES)
        
        if game_form.is_valid():
            game = game_form.save()
            
            if screenshot_form.is_valid():
                for scf in screenshot_form:
                    action = scf.save(commit=False)
                    if not action.image:
                        continue
                    action.game = game
                    action.save()
                messages.add_message(request, messages.SUCCESS, "New game has been added successfully.")
                return redirect(reverse('games_index'))
            else:
                game.delete()
                messages.add_message(request, messages.ERROR, "Add new game failed. Check your screenshots.")
        else:
            messages.add_message(request, messages.ERROR, "Add new game failed. Check your game data.")
            
    data = {'game_form': game_form, 'screenshot_form': screenshot_form}
    return render(request, 'games/new.html', data)
Exemplo n.º 3
0
def editar_form(jogo_id):
    jogo_id = int(jogo_id)
    jogo=Game.get_by_id(jogo_id)
    jogo_form = GameForm()
    jogo_form.fill_with_model(jogo)
    contexto = {'editar_path': router.to_path(atualizar, jogo_id),
              'game' : jogo_form}
    return TemplateResponse(contexto, 'temporario/forme.html')
Exemplo n.º 4
0
def editar_form(jogo_id):
    jogo_id = int(jogo_id)
    jogo=Game.get_by_id(jogo_id)
    jogo_form=GameForm()
    jogo_form.fill_with_model(jogo)
    contexto={'salvar_path': router.to_path(salvar, jogo_id),
              'jogo':jogo_form}
    return TemplateResponse(contexto, 'editar/home.html')
Exemplo n.º 5
0
def register():
    global player1
    global player2
    form = GameForm()
    if form.validate_on_submit():
        player1 = Player(name=form.playerOne.data)
        player2 = Player(name=form.playerTwo.data)
        return redirect(url_for('pageGame'))
    return render_template('form.html', title='Form', form=form)
Exemplo n.º 6
0
 def get(self, request):
     form = GameForm(request.GET)
     if form.is_valid():
         game = form.get_game()
         return self.render_to_response({"game": [game]})
     else:
         return self.render_to_response({
             "request_error": form.errors,
             "game": []
         })
Exemplo n.º 7
0
def game_create():
    if current_user.is_admin:
        form = GameForm()
        if form.validate_on_submit():
            new_game = Game(nama=form.nama.data, deskripsi=form.deskripsi.data, is_rental=False)
            db.session.add(new_game)
            db.session.commit()
            return redirect(url_for('game_index'))
        return render_template('game/create.html', form=form, current_user=current_user)
    else:
        return redirect(url_for('game_index'))
Exemplo n.º 8
0
def salvar(**propriedades):
    game_form = GameForm(**propriedades)
    erros = game_form.validate()
    if erros:
            contexto={'criar_modelo': router.to_path(salvar),
                      'game': game_form,
                      'erros': erros}
            return TemplateResponse(contexto, 'criar/form.html')
    else:
        jogo=game_form.fill_model()
        jogo.put()
        return RedirectResponse(router.to_path(continuar))
Exemplo n.º 9
0
def create_game():
    form = GameForm()
    if form.validate_on_submit():
        game = Game(title=form.title.data,
                    desc=form.desc.data,
                    poster=form.poster.data,
                    release_date=form.release_date.data,
                    price=form.price.data,
                    on_sale=form.on_sale.data)
        db.session.add(game)
        db.session.commit()
        return redirect(url_for('get_game', game_id=game.id))
    return render_template('new_game.html', form=form)
Exemplo n.º 10
0
 def to_form(self, game, message=""):
     """Returns a GameForm representation of the Game"""
     form = GameForm(urlsafe_key=game.key.urlsafe(),
                     board = str(game.board),
                     next_move=game.next_move.get().name,
                     game_over=game.game_over,
                     message=message,
                     history=str(game.history),
                     first_user_score=game.first_user_score,
                     second_user_score=game.second_user_score,
                     unmatched_pairs=game.unmatched_pairs)
     if game.winner:
         form.winner = game.winner.get().name
     return form
Exemplo n.º 11
0
def atualizar(jogo_id, **propriedades):
    jogo_id = int(jogo_id)
    jogo = Game.get_by_id(jogo_id)
    game_form = GameForm(**propriedades)
    erros = game_form.validate()
    if erros:
            contexto = {'editar_path': router.to_path(salvar),
                      'game': game_form,
                      'erros': erros}
            return TemplateResponse(contexto, 'temporario/form.html')
    else:
        game_form.fill_model(jogo)
        jogo.put()
        return RedirectResponse(router.to_path(index))
Exemplo n.º 12
0
def salvar(_logged_user, **propriedades):
    game_form = GameForm(**propriedades)
    erros = game_form.validate()
    if erros:
            contexto={'criar_modelo': router.to_path(salvar),
                      'game': game_form,
                      'erros': erros}
            return TemplateResponse(contexto, 'temporario/criar/form.html')
    else:
        jogo = game_form.fill_model()
        game_key = jogo.put()
        user_key = _logged_user.key
        autor = Autor(origin=user_key, destination=game_key)
        autor.put()
        return RedirectResponse(router.to_path(index))
Exemplo n.º 13
0
def game_update(game_id):
    if current_user.is_admin:
        form = GameForm()
        if form.validate_on_submit():
            updated_game = Game.query.filter_by(id=game_id).first()
            updated_game.nama = form.nama.data
            updated_game.deskripsi = form.deskripsi.data
            db.session.commit()
            return redirect(url_for('game_index'))
        else:
            game = Game.query.filter_by(id=game_id).first()
            form = GameForm(id=game.id, nama=game.nama, deskripsi=game.deskripsi)
            return render_template('game/update.html', form=form, current_user=current_user)
    else:
        return redirect(url_for('game_index'))
Exemplo n.º 14
0
def add_game(request):
    user = request.user
    old_game = user.get_current_game()
    
    if old_game:
        return redirect('main:index')
        
    form = GameForm(request.POST or None)

    if form.is_valid():
        game = form.save()
        game.generate_map()
        game.add_user(request.user)
        return redirect('main:index')

    return dict(form=form)
Exemplo n.º 15
0
 def to_form(self):
     """Returns a GameForm representation of the Game"""
     form = GameForm(urlsafe_key = self.key.urlsafe(),
                     board = str(self.board),
                     boardSize = self.boardSize,
                     player_x = self.player_x.get().name,
                     player_o = self.player_o.get().name,
                     nextMove = self.nextMove.get().name,
                     game_over = self.game_over
                     )
     if self.winner:
         # send winner to Game form and get winner's name
         form.winner = self.winner.get().name
     if self.draw:
         form.draw = self.draw
     return form
Exemplo n.º 16
0
 def to_form(self):
     """Returns a GameForm representation of the Game"""
     form = GameForm(urlsafe_key = self.key.urlsafe(),
                     board = str(self.board),
                     boardSize = self.boardSize,
                     player_x = self.player_x.get().name,
                     player_o = self.player_o.get().name,
                     nextMove = self.nextMove.get().name,
                     game_over = self.game_over
                     )
     if self.winner:
         # send winner to Game form and get winner's name
         form.winner = self.winner.get().name
     if self.draw:
         form.draw = self.draw
     return form
Exemplo n.º 17
0
 def to_form(self, result):
     """Returns the response data of the game object"""
     form = GameForm()
     form.urlsafe_key = self.key.urlsafe()
     form.user_name = self.user.get().name
     if ('user_card' in result) and ('bot_card' in result):
         form.user_card = result['user_card']
         form.bot_card = result['bot_card']
     form.user_card_count = len(self.user_deck)
     form.bot_card_count = len(self.bot_deck)
     form.game_over = self.game_over
     form.message = result['message']
     return form
Exemplo n.º 18
0
def index(request):
    games = Game.objects.all()

    if request.method == 'POST':
        new_game = Game()
        form = GameForm(request.POST, instance=new_game)
        if form.is_valid():
            try:
                form.save()
                new_game.add_player(request.user, True)
            except Exception:
                new_game.delete()
                messages.error(request, "Usted ya pertenece a otra partida")
                return render(request, "truco/index.html", {
                    'games': games,
                    'form': form,
                })

            messages.success(request, "Partida creada exitosamente")
            return HttpResponseRedirect(
                reverse('truco:room', args=(new_game.id, )))
        else:
            messages.error(request, "Error al crear partida")
    else:
        form = GameForm()

    return render(request, "truco/index.html", {'games': games, 'form': form})
Exemplo n.º 19
0
def _edit(request, game_id):
	if game_id == None:
		game = None 
	else:
		game = get_object_or_404(GameInfoModel, pk=game_id)

	if request.POST:
		form = GameForm(request.POST, instance=game) # this line is gonna be iffy
		if form.is_valid():
			game = form.save()
			return HttpResponseRedirect(reverse('featured_games-list'))
	else:
		form = GameForm(instance=game)

	return render(request, "featured_games/edit.html", {
		"chunk_size": settings.CHUNK_SIZE,
		"form": form,	
	})
Exemplo n.º 20
0
def index():
    search = GameForm(request.form)

    if request.method == "POST":
        return search_results(search)

    games = Games.get_all_games()
    table = Results(games)
    return flask.render_template("index.html", form=search, table=table)
Exemplo n.º 21
0
def game_edit(game_id):
	form = GameForm()

	form.genres.choices = models.Genre.query.with_entities(models.Genre.id, models.Genre.name) \
		.order_by(models.Genre.name.asc())

	game = models.Game.query.get_or_404(game_id)
	platform = game.platform

	if form.validate_on_submit():
		game.name = form.name.data
		game.desc = form.desc.data
		game.id_genres = form.genres.data
		db.session.add(game)
		db.session.commit()
		return redirect("/Game/%s" % (game_id))
	else:
		form.genres.default = game.id_genres
		form.process()

	return render_template("game_edit.html", title="Game Edit", platform=platform, game=game, form=form)
Exemplo n.º 22
0
def _edit(request, game_id):
	"""
	Edit or create a game
	"""
	if game_id == None:
		game = None
	else:
		game = get_object_or_404(Game, pk=game_id)

	if request.method == "POST":
		form = GameForm(request.POST, instance=game)
		if form.is_valid():
			form.save(user=request.user)
			return HttpResponseRedirect(reverse("games-detail", args=(file.pk,)))
	else:
		form = GameForm(instance=game)

	return render(request, 'games/edit.html', {
		"game": game,	
		"form": form,	
	})
Exemplo n.º 23
0
def game():
    if 'user' not in session:
        return render_template("home.html", message="You are not logged in.")
    else:
        form = GameForm()
        if form.validate_on_submit():
            new_game = Game(game_id=(Game.query.count()) + 1,
                            title=form.game.data)
            db.session.add(new_game)
            try:
                db.session.commit()
            except Exception as e:
                print(e)
                db.session.rollback()
                return render_template("game.html",
                                       form=form,
                                       message="Something went wrong.")
            finally:
                db.session.close()
            return render_template("game.html",
                                   message="Successfully added a game.")
        return render_template('game.html', form=form)
Exemplo n.º 24
0
 def to_form(self):
     """Returns a GameForm representation of the Game"""
     status_list = ['Active', 'Completed']
     status = status_list[self.status]
     date_start = pretty_date(self.start_date)
     form = GameForm(urlsafe_key = self.key.urlsafe(),
         setup = str(self.setup),
         host_name = self.host,
         oppoent_name = self.oppoent,
         turn = self.turn.get().name,
         status = status,
         start_date = date_start)
     return form
Exemplo n.º 25
0
def game_form(username):
    form = GameForm(request.form)
    print("request: ", request.method)
    if form.validate_on_submit():

        game = {
            "nome": form.name.data,
            "categoria": form.categoria.data,
            "url": form.url_game.data,
        }

        if form.url_image.data:
            game["url_image"] = form.url_image.data

        if form.description.data:
            game["description"] = form.description.data

        game["autor"] = username

        flash(add_game(game))

    return render_template('game_form.html', form=form, author=username)
Exemplo n.º 26
0
Arquivo: views.py Projeto: JMaz/athena
def game():
	form = GameForm()

	user = g.user
	games = Game.query.all()
	


        if form.validate_on_submit():
                game_name = form.game_name.data
                game_description = form.game_description.data
                game = Game(game_name=game_name,game_description=game_description)
                db.session.add(game)
                db.session.commit()
                flash('Your game has been added')
                return redirect(url_for('game'))
        
	return render_template("game.html",
				title='Games',
				user=user,
				games=games,
				form=form)
Exemplo n.º 27
0
def edit_game(id):
    """Edit extisting game"""
    check_admin()
    add_game = False
    game = Game.query.get_or_404(id)
    form = GameForm(obj=game)

    # Checks if form is valid
    if form.validate_on_submit():
        game.name = form.name.data
        db.session.commit()
        flash('Game successfully edited')

        return redirect(url_for('admin.list_games'))

    form.name.data = game.name

    return render_template('admin/games/game.html',
                           action='Edit',
                           add_game=add_game,
                           form=form,
                           game=game,
                           title='Edit Game')
Exemplo n.º 28
0
def add_game():
    """Adds game to database"""
    check_admin()
    add_game = True
    form = GameForm()

    # Checks if form is valid
    if form.validate_on_submit():
        game = Game(name=form.name.data)

        try:
            db.session.add(game)
            db.session.commit()
            flash('Game successfully added')
        except:
            flash('Error: game name already exists')

        return redirect(url_for('admin.list_games'))

    return render_template('admin/games/game.html',
                           action='Add',
                           add_game=add_game,
                           form=form,
                           title='Add Game')
Exemplo n.º 29
0
def game_create_direct(request, timeframe_id, location_id):
    timeframe = get_object_or_404(Timeframe, pk=timeframe_id)
    location = get_object_or_404(Location, pk=location_id)

    if request.method == 'POST':
        form = GameForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('tournament_saved')
    else:
        form = GameForm(initial={
            'time': timeframe,
            'location': location,

        })

    return render(request, 'habatu/game_form.html', {
        'form': form,
    })
Exemplo n.º 30
0
def game_edit(request, gid):
    game = Games.objects.select_related().get(pk=gid)

    perm_edit_game = False
    if request.user == game.name or request.user.has_perm('games.change_games'):
        perm_edit_game = True

    form = GameForm(instance = game)

    if request.method == 'POST':
        game.title_cn = request.POST['title_cn']
        game.title_src = request.POST['title_src']
        game.platform = request.POST.getlist('platform')
        game.language = request.POST['language']
        try:
            game.imagefile = request.FILES['imagefile']
        except :
            pass
        game.team = request.POST['team']
        game.level = request.POST['level']
        if request.POST['publish_time']:
            game.publish_time = request.POST['publish_time']
        game.game_size = request.POST['game_size']
        game.tags = request.POST['tags']
        game.publish_url = request.POST['publish_url']
        game.download_link = request.POST['download_link']
        game.content = request.POST['content']
        game.state = request.POST['state']
        if request.POST['review_id']:
            game.review_id = int(request.POST['review_id'])
        else:
            game.review_id = None
        if request.POST['gospel_id']:
            game.gospel_id = int(request.POST['gospel_id'])
        else:
            game.gospel_id = None
        game.save()
        return HttpResponseRedirect('/library/%s/'%gid)
    return render_to_response("games/game_edit.html",{'form': form, 'perm_edit_game': perm_edit_game},\
        context_instance=RequestContext(request))
Exemplo n.º 31
0
def new_game():
    formpage = GameForm()
    formpage.court.choices = [
        (court.name, court.name + ' - Address: ' + court.location)
        for court in Courts.query.filter_by(sport='soccer').all()
    ]
    formpage.slot.choices = [
        (slot.id, 'Court No: ' + str(slot.court_number) + ' | Schedule at: ' +
         slot.slot_date_time + ' | Max Players: ' + str(slot.players_number) +
         ' | Price : ' + slot.price) for slot in Slots.query.filter_by(
             court='Circolo della Stampa - Sporting A.S.D.',
             availability='True').all()
    ]
    if request.method == 'POST':
        try:
            slot = Slots.query.filter_by(id=formpage.slot.data).first()
            slot.availability = 'False'
        except:
            flash('There is no slots available to book!!', 'success')

        else:
            vacant = slot.players_number - 1
            if formpage.team.data == True:
                vacant = 0
            game = Games(title=formpage.title.data,
                         description=formpage.description.data,
                         members=current_user.name + ' Cel: ' +
                         current_user.phone + ' ',
                         vacant=vacant,
                         sport='soccer',
                         creator=current_user,
                         location=formpage.court.data,
                         slot='Court #: ' + str(slot.court_number) + '| at ' +
                         slot.slot_date_time + '| for: ' +
                         str(slot.players_number) + ' players',
                         slot_id=slot.id,
                         price=slot.price)
            db.session.add(game)
            db.session.commit()
            flash('Your post has been created!', 'success')
        return redirect(url_for('soccer'))
    #Map handler
    soccermap = Map(
        identifier="view-side",
        lat=45.0728612,
        lng=7.6474516,
        zoom=12,
        markers=[{
            'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
            'lat': 45.0396017,
            'lng': 7.6452646,
            'infobox': "Circolo della Stampa - Sporting A.S.D."
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
            'lat': 45.0521902,
            'lng': 7.6101512,
            'infobox': "Poligru L'oasi dello sport"
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png',
            'lat': 45.0700943,
            'lng': 7.651680199999987,
            'infobox': "Nuova Golden Goal"
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png',
            'lat': 45.0699097,
            'lng': 7.655949400000054,
            'infobox': "Cit Turin LDE"
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
            'lat': 45.068541,
            'lng': 7.62848699999995,
            'infobox': "Pozzomaina S.R.L. S.S.D."
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png',
            'lat': 45.0601674,
            'lng': 7.644224300000019,
            'infobox': "Centro sportivo Robillant"
        }])
    return render_template('new_soccer_game.html',
                           title='Create Soccer Game',
                           formpage=formpage,
                           soccermap=soccermap)
Exemplo n.º 32
0
def new_game_tennis():
    formpage = GameForm()
    formpage.court.choices = [
        (court.name, court.name + ' - Address: ' + court.location)
        for court in Courts.query.filter_by(sport='tennis').all()
    ]
    formpage.slot.choices = [
        (slot.id, 'Court No: ' + str(slot.court_number) + ' | Schedule at: ' +
         slot.slot_date_time + ' | Max Players: ' + str(slot.players_number) +
         ' | Price : ' + slot.price) for slot in Slots.query.filter_by(
             court='Circolo della Stampa - Sporting A.S.D. - Tennis',
             availability='True').all()
    ]  #Ojo debe ir el primero siempre
    if request.method == 'POST':
        try:
            slot = Slots.query.filter_by(id=formpage.slot.data).first()
            slot.availability = 'False'
        except:
            flash('There is no slot to book!!', 'success')

        else:
            vacant = slot.players_number - 1
            if formpage.team.data == True:
                vacant = 0
            game = Games(title=formpage.title.data,
                         description=formpage.description.data,
                         members=current_user.name + ' Cel: ' +
                         current_user.phone + ' ',
                         vacant=vacant,
                         sport='tennis',
                         creator=current_user,
                         location=formpage.court.data,
                         slot='Court #: ' + str(slot.court_number) + '| at ' +
                         slot.slot_date_time + '| for: ' +
                         str(slot.players_number) + ' players',
                         slot_id=slot.id,
                         price=slot.price)
            db.session.add(game)
            db.session.commit()
            flash('Your post has been created!', 'success')
        return redirect(url_for('tennis'))
    #Map handler
    tennismap = Map(
        identifier="view-side",
        lat=45.0728612,
        lng=7.6474516,
        zoom=12,
        markers=[{
            'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
            'lat': 45.0396017,
            'lng': 7.6452646,
            'infobox': "Circolo della Stampa - Sporting A.S.D."
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
            'lat': 45.0521902,
            'lng': 7.6101512,
            'infobox': "Poligru L'oasi dello sport"
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png',
            'lat': 45.08472099999999,
            'lng': 7.6406868999999915,
            'infobox': "Nord Tennis Sport Club"
        }, {
            'icon': 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png',
            'lat': 45.0601674,
            'lng': 7.644224300000019,
            'infobox': "Centro sportivo Robillant"
        }])
    return render_template('new_tennis_game.html',
                           title='Create Tennis Game',
                           formpage=formpage,
                           tennismap=tennismap)
Exemplo n.º 33
0
def get_calendar():
    form = GameForm()

    today = request.args.get('month')

    if today == None:
        today = datetime.date(datetime.now())

    print today
    # --------calendar begins---------#
    year = [
        'January', 'February', 'March', 'April', 'May', 'June', 'July',
        'August', 'September', 'October', 'November', 'December'
    ]

    # by default the calendar begin the week with Monday (day 0)

    calendar.setfirstweekday(calendar.SUNDAY)

    #stiringify date and reorganize into integers
    current = re.split('-', str(today))

    current_no = int(current[1])
    current_month = year[current_no - 1]
    current_day = int(re.sub('\A0', '', current[2]))
    current_yr = int(current[0])

    month = calendar.monthcalendar(current_yr, current_no)
    nweeks = len(month)

    each_week = []

    for w in range(0, nweeks):
        week = month[w]
        each_week.append(week)
    #---------------calender ends-----------#

    #-----add matches--------#
    all_teams = model.current_teams()

    teams = {}
    for t in all_teams:
        teams[t.id] = t.teamname

    # render template to set games
    form = GameForm()

    games = model.session.query(model.Game).\
      order_by(model.Game.game_date.desc()).all()

    if form.validate_on_submit():
        if form.home_team.data == form.away_team.data:
            flash("Teams cannot be the same")
            return redirect('calendar')
        else:
            new_game= model.session.\
                add(model.Game(game_date = form.game_date.data,
                 home_team = form.home_team.data,
                 away_team = form.away_team.data,
                 home_score = form.home_score.data,
                 away_score = form.away_score.data))

            model.session.commit()
            flash('Game Added!')
            return redirect('calendar')

    #----------render form to change score---#
    form_s = ScoreForm()

    return render_template('calendar.html',
                           title='Calendar',
                           current_month=current_month,
                           current_yr=current_yr,
                           each_week=each_week,
                           user=current_user,
                           form=form,
                           games=games,
                           form_s=form_s,
                           all_teams=all_teams,
                           teams=teams)
Exemplo n.º 34
0
    def to_form(self, message):
        """Returns a GameForm representation of the Game"""
        from utils import get_player_by_game

        # get players
        player1 = get_player_by_game(self.player_names[0], self)
        player2 = get_player_by_game(self.player_names[1], self)

        form = GameForm()
        form.started_on = self.started_on
        form.urlsafe_key = self.key.urlsafe()
        form.player1 = player1.name
        form.player1_hand = str(player1.hand)
        form.player1_matches = player1.num_matches
        form.player2 = player2.name
        form.player2_hand = str(player2.hand)
        form.player2_matches = player2.num_matches
        form.game_over = self.game_over
        form.matches_to_win = self.matches_to_win

        if not self.game_over:
            form.turn = self.turn
        else:
            form.winner = self.winner

        form.message = message
        return form
Exemplo n.º 35
0
def add_game():
    form = GameForm()
    error = ''
    developers = '['
    for developer in Developer.query.filter(Developer.id>0).order_by(Developer.type):
        developer.name = developer.name.replace("'", "\\'")
        developer.name = developer.name.replace('"', '\\"')
        developers += '"'+developer.name+'",'
    developers = developers[:-1]
    developers += ']'
    #creators = '["PunkCabbageRabbit","Akane","flowerthief","Lemma Soft","Zeiva Inc.","ATP Projects","Grey","American Bishoujo","Ren\'Ai Games","Chronoluminaire","Gloranor"]'

    if form.validate_on_submit():
        game_title=form.game_title.data
        slug=form.slug.data
        homepage_link_url=form.homepage_link_url.data
        developer_name=form.creator.data
        maker=developer_name
        creator_type=form.creator_type.data
        description = form.description_.data
        age_rating_id=str(form.age_rating_id.data)
        categories = form.categories.data
        words = form.words.data
        words = words.replace(",", "")
        words = words.replace(".", "")
        try:
            words = int(re.search(r'(0|(-?[1-9][0-9]*))', words).group(0))
        except: # Catch exception if re.search returns None
            words = 0
        if not words:
            words = 0

        playtime = 0
        if form.playtime.data:
            try:
                playtime = float(form.playtime.data)
            except:
                try:
                    playtime = int(re.search(r'(0|(-?[1-9][0-9]*))', form.playtime.data).group(0))
                except: # Catch exception if re.search returns None
                    playtime = 0
            if form.playtime_unit.data == 'hours':
                playtime = playtime * 60
                playtime = int(math.ceil(playtime))
            else:
                playtime = playtime


        if words == 0:
            words_estimate = playtime*200
        else:
            words_estimate = words
        listed_on = form.listed_on.data
        if listed_on:
            listed_on = 3 # both
        else:
            listed_on = 2 # games.renpy.org only

        game = Game(game_title=game_title, slug=slug, maker = maker, description = description, age_rating_id=age_rating_id, words = words, words_estimate=words_estimate, playtime = playtime, developer_id=1, user_id=g.user.id, approved=False, listed_on=listed_on)
        db.session.add(game)
        db.session.commit()

        release = Release(game_id=game.id, release_date=form.release_date.data, release_version=form.release_version.data, engine_id=form.engine_id.data, release_description = form.release_description.data, engine_version = form.engine_version.data, user_id=g.user.id)
        save_release(release, form.platforms.data)

        #save new creator if it doesn't exists:
        developer_name = developer_name.replace("'", "")
        developer = Developer.query.filter(Developer.name==developer_name).first()

        if not developer:
            if creator_type=='person':
                type=1
                person = Person('')
                db.session.add(person)
                db.session.commit()
                developer = Developer (developer_name, type, g.user.id, person_id=person.id)
            if creator_type=='group':
                type=2
                group = Group('')
                db.session.add(group)
                db.session.commit()
                developer = Developer (developer_name, type, g.user.id, group_id=group.id)
            db.session.add(developer)

        #save homepage link to link_game table:
        links_game= LinkGame(game_id=game.id, url=homepage_link_url, name = 'Home Page', link_type_id = '1')
        db.session.add(links_game)

        #save the categories to category_game:
        for category_id in categories:
            categories_game = CategoryGame(game_id=game.id, category_id=category_id)
            db.session.add(categories_game)

        db.session.commit()
        game.developer_id = developer.id
        db.session.commit()

        flash('New game was successfully added. The game must be approved by a moderator, before it will show up on the site. This might take a couple of days, depending on how busy we are.')
        return redirect(url_for("index"))
    return render_template('add_game.html', navigation=return_navigation(), error=error, site_data=site_data(), form=form, developers=developers, edit=False)
Exemplo n.º 36
0
def get_calendar():
	form = GameForm()

	today = request.args.get('month')

	if today == None:
		today = datetime.date(datetime.now())

	print today
	# --------calendar begins---------#
	year = ['January', 
			 'February', 
			 'March', 
			 'April', 
			 'May', 
			 'June', 
			 'July', 
			 'August', 
			 'September', 
			 'October', 
			 'November', 
			 'December'] 

	# by default the calendar begin the week with Monday (day 0)
	
	calendar.setfirstweekday(calendar.SUNDAY)
	
	#stiringify date and reorganize into integers
	current = re.split('-', str(today))

	current_no = int(current[1])
	current_month = year[current_no - 1]
	current_day = int(re.sub('\A0', '',current[2]))
	current_yr = int(current[0])


	month = calendar.monthcalendar(current_yr, current_no) 
	nweeks = len(month) 

	each_week=[]
	
	for w in range(0,nweeks): 
		week = month[w]
		each_week.append(week)
	#---------------calender ends-----------#

	#-----add matches--------#
	all_teams = model.current_teams()

	teams={}	    
	for t in all_teams:
		teams[t.id]=t.teamname

	# render template to set games
	form= GameForm()

	games = model.session.query(model.Game).\
			order_by(model.Game.game_date.desc()).all()

	if form.validate_on_submit():
		if form.home_team.data == form.away_team.data:
			flash("Teams cannot be the same")
			return redirect('calendar')
		else:
			new_game= model.session.\
					  add(model.Game(game_date = form.game_date.data,
								home_team = form.home_team.data,
								away_team = form.away_team.data,
								home_score = form.home_score.data,
								away_score = form.away_score.data))

			model.session.commit()
			flash('Game Added!')
			return redirect('calendar')	

	#----------render form to change score---#
	form_s = ScoreForm()

	return render_template('calendar.html',
						    title='Calendar',
						    current_month= current_month,
						    current_yr= current_yr,
						    each_week = each_week,
						    user= current_user,
						    form=form,
						    games=games,
						    form_s=form_s,
							all_teams=all_teams,
							teams=teams
						    )