コード例 #1
0
    def post(self, request):
        """Check form data, and send the result if form is valid"""
        form = GameForm(request.POST)
        context = {'form': form}
        if form.is_valid():
            # Initialize instance of game
            game = GameManager(number_of_players=form.cleaned_data.get(
                'number_of_players', 0),
                               sequence=form.cleaned_data.get('board', ''),
                               deck=form.cleaned_data.get('deck', ''))
            game_result = game.result()

            # Save game data at database
            self.model.objects.create(
                players=form.cleaned_data.get('number_of_players', None),
                squares=form.cleaned_data.get('number_of_squares', None),
                cards=form.cleaned_data.get('number_of_cards', None),
                sequence=form.cleaned_data.get('board', None),
                deck=form.cleaned_data.get('deck', None),
                result=game_result)

            # Send result of game to client side
            context['result'] = game_result
        else:
            context['error'] = 'Form is not valid!'
        return render(request, self.template_name, context)
コード例 #2
0
ファイル: views.py プロジェクト: hellochar/the_game_bazaar
    def post(self, request):
        """ Create a new game """

        form = GameForm(request.POST)
        if form.is_valid():
            game, players_json = Game.create_new_game(form.cleaned_data["map_id"], request.user)
            # Render the context with our parameters.
            return redirect(reverse("game_view", kwargs={"gameid": game.id}))
        else:
            # Needs better error handling
            raise Http404
コード例 #3
0
ファイル: views.py プロジェクト: ZzCalvinzZ/minesweeper
def index(request):
  if request.method == 'POST':
    post = (request.POST)
    form = GameForm(post)
    if form.is_valid():
      #create the user if they don't exist already
      user = User.objects.filter(name=post['name'])[:1]
      if not user:
        new_user = User(name=post['name'])
        new_user.save()
      try:
        user = User.objects.get(name=post['name'])
      except User.DoesNotExist:
        return HttpResponse('database error', status=404)  

      #create the game including minefield then save it to database
      if post['difficulty'] == 'beginner':
        game = Game(width=9,height=9,number_of_mines=10,difficulty='beginner',user=user)
      elif post['difficulty'] == 'intermediate':
        game = Game(width=16,height=16,number_of_mines=40,difficulty='intermediate',user=user)
      elif post['difficulty'] == 'expert':
        game = Game(width=30,height=16,number_of_mines=99,difficulty='expert',user=user)
      game.create_minefield()
      game.fields_left = game.width * game.height
      game.save()

      #redirect to the game page
      args = {'name': user.name, 'game_id': str(game.id)}
      return HttpResponseRedirect(reverse('game_start', kwargs=args))
  else:
    form = GameForm()

  top_beginner_users = User.objects.filter(game__difficulty='beginner', game__won=True).order_by('game__won')
  beginner_dict = create_high_scores(top_beginner_users)

  top_inter_users = User.objects.filter(game__difficulty='intermediate', game__won=True)
  inter_dict = create_high_scores(top_inter_users)

  top_expert_users = User.objects.filter(game__difficulty='expert', game__won=True)
  expert_dict = create_high_scores(top_expert_users)

  return render(request, 'index.html', {
      'form': form, 
      'beginner_dict': beginner_dict, 
      'inter_dict': inter_dict,
      'expert_dict': expert_dict
      })
コード例 #4
0
ファイル: views.py プロジェクト: andyyc/socialbum
def create(request):
    if request.method == 'POST':
        gf = GameForm(request.POST)
        if gf.is_valid():
            users = gf.cleaned_data['users']
            
            g = Game()
            g.save()

            for user in users:
                p = Player.objects.create(user=user, 
                                           game=g,
                                           points=0)
            p = Player.objects.create(user=request.user,
                                       game=g,
                                       points=0)
            

            topics = Topic.objects.filter(deleted=False).order_by('?')
            for topic in topics:
                game_topic = GameTopic.objects.create(topic=topic,
                                                        game=g)
            #create turn
            turn = Turn.objects.create(game=g,
                                       num=1,
                                       judge=request.user)
            g.current_turn = turn
            g.save()
            
            return HttpResponseRedirect(reverse('game', kwargs={'game_id':g.id}))
    else:
        gf = GameForm()

    try:
        fb_profile = FacebookSession.objects.get(user=request.user)
    except FacebookSession.DoesNotExist:
        raise Http404

    user_friends_list, user_friends_queryset, only_fb_friends_list = get_friends_list(fb_profile)

    gf.fields["users"].queryset = user_friends_queryset
    template_context = {'gf': gf,
                        'user_friends_list':user_friends_list,
                        'fb_friends_list':only_fb_friends_list}
    return render_to_response('create_game.html', template_context, context_instance=RequestContext(request))
コード例 #5
0
    def post(self, request):
        form = GameForm(self.current_game, request.POST)
        game = self.current_game

        if not form.is_valid():
            games = Games.objects.all()
            return render(
                request,
                'game/edit-game.html',
                {
                    'games': games,
                    'game': game,
                    'form': form
                },
            )

        game.name = form.cleaned_data['name']
        game.starting_place = form.cleaned_data['starting_place']
        game.save()
        return HttpResponseRedirect(reverse('events'))
コード例 #6
0
    def post(self, request):
        form = GameForm(None, request.POST)

        if not form.is_valid():
            games = Game.objects.all()
            return render(request, 'game/create-game.html', {
                'form': form,
                'games': games
            })

        game = Game.objects.create(
            name=form.cleaned_data['name'],
            author=request.user,
        )
        request.session['game'] = game.pk
        messages.add_message(
            request,
            messages.INFO,
            'Selected {0}'.format(game.name),
        )
        return HttpResponseRedirect(reverse('events'))
コード例 #7
0
ファイル: views.py プロジェクト: Zhang9494/Game_Rango
def add_game(request, category_name_slug):
    # Get the category, the add_game.html will use this to decide what to show
    try:
        category = Category.objects.get(slug=category_name_slug)
    except Category.DoesNotExist:
        category = None

    # This page include input, use this form to get input
    form = GameForm()
    if request.method == 'POST':
        form = GameForm(request.POST, request.FILES)
        if form.is_valid():
            if category:
                game = form.save(commit=False)
                game.category = category
                game.mark = 0
                game.save()
                # Success, turn to the category page(which we are add game to)
                return show_category(request, category_name_slug)
            else:
                print(form.errors)

    context_dict = {'form': form, 'category': category}
    return render(request, 'game/add_game.html', context_dict)
コード例 #8
0
ファイル: views.py プロジェクト: Yipit/yipit-matchup
def process_game(request):
    if request.POST:
        winning_score = request.POST.get('score_1')
        losing_score = request.POST.get('score_2')
        if not losing_score:
            losing_score = 0
            winning_score = 0
        if losing_score and not winning_score:
            winning_score = 21
        winner_id = request.POST.get('player_1')[1:]
        loser_id = request.POST.get('player_2')[1:]
        postdict = {u'score_1': unicode(winning_score), u'player_2': loser_id, u'score_2': unicode(losing_score), u'player_1': winner_id}
        try:
            form = GameForm(postdict)
            if form.is_valid():
                form.process()
            else:
                print "hello"
        except:
            return HttpResponseRedirect(reverse('dashboard'))
        else:
            return HttpResponseRedirect(reverse('dashboard'))
    else:
        return HttpResponseRedirect(reverse('dashboard'))
コード例 #9
0
ファイル: views.py プロジェクト: Radniforg/dj_session
def show_home(request):
    if not request.session.exists(request.session.session_key):
        request.session.create()
    current_player = request.session.get('player', 'new')
    if current_player == 'new':
        Player.objects.create(session_id=request.session.session_key)
        request.session['player'] = 'old'
    player = Player.objects.get(session_id=request.session.session_key)
    if not Game.objects.filter(ongoing=True):
        if not player.playergameinfo_set.filter(announce=False):
            # Нет активных игр и все результаты для игрока были объявлены: создание новой игры
            if request.method == 'POST':
                form = GameForm(request.POST)
                if form.is_valid():
                    game_save = form.save(commit=False)
                    game_save.save()
                    game_save.players.add(player)
                    game_save.save()
                    creator = game_save.playergameinfo_set.filter(player=player)[0]
                    creator.creator = True
                    creator.save()
                    return render(request,
                                  'input.html')
            else:
                form = GameForm()
                return render(request, 'home.html', context={'form': form})
        else:
            #если нет активных игр, но результаты прошлых игр игроку не объявлялись
            current_game = player.playergameinfo_set.filter(announce=False)[0]
            game_id = current_game.game
            tries = game_id.final_tries
            creator = current_game.creator
            current_game.announce = True
            current_game.save()
            return render(request, 'result.html', context={
                'tries': tries, 'creator': creator,
                'number': game_id.number})
    else:
        #если есть активная игра
        game = Game.objects.filter(ongoing=True).first()
        if not player.games.filter(ongoing=True):
            player.games.add(game)
            player.save()
        if not game.playergameinfo_set.filter(creator=False):
            #Проверяет, является ли игрок создателем активной игры
            return render(request,
                          'input.html',
                          context={'key': request.session.session_key})
        else:
            current = player.playergameinfo_set.get(game=game)
            if request.method == 'POST':
                form = TryForm(request.POST)
                if form.is_valid():
                    game_save = form.save(commit=False)
                    if game_save.last_number == game.number:
                        #Если угадал
                        game.final_tries = current.tries + 1
                        game.ongoing = False
                        current.announce = True
                        current.last_number = game_save.last_number
                        current.save()
                        game.save()
                        return render(request, 'success.html',
                                      context={'tries': game.final_tries,
                                               'number': game.number})
                    else:
                        #Если не угадал
                        current.last_number = game_save.last_number
                        current.tries += 1
                        current.save()
                        return render(request, 'again.html',
                                      context={'number': current.last_number,
                                               'original': game.number,
                                               'form': form,
                                               'tries': current.tries})
            form = TryForm()
            tries = current.tries
            original = game.number
            number = current.last_number
            return render(
                request,
                'again.html',
                context={'form': form,
                         'original': original,
                         'tries': tries,
                         'number': number}
            )
コード例 #10
0
def show_home(request, *args, **kwargs):
    success_attempt = None
    data_player = Player.objects
    games = Game.objects
    number = randint(0, 11)
    players = list(data_player.values())
    session = request.session.items()

    #если игрок уже завершил игру в сесcии
    try:
        if request.session['gameover'] == True:
            request.session.delete()
    except:
        pass

    # определения кто загадывает, кто отгадывает
    #добавление в DB и определение данных сессии
    if  str(session) == 'dict_items([])':
        if str(players) == '[]':
            first_player = Player.objects.create(player_id=1)
            first_player.save()
            first_game = Game.objects.create(game_id=1, number=number)
            first_game.save()
            Membership = PlayerGameInfo.objects.create(game=first_game, player=first_player)
            request.session['player'] = 1
            request.session['number'] = number

        else:
            player_id = players[-1]['id']
            if player_id == 1:
                second_player = Player.objects.create(player_id=player_id+1)
                second_player.save()
                game = games.all()[0]
                Membership = PlayerGameInfo.objects.create(game=game, player=second_player)
                request.session['player'] = 2
                number_result = games.values()[0]['number']
                request.session['number'] = number_result
                request.session['attempt'] = 0

            # для последующих игроко добавление DB и сохранения сессии
            if player_id % 2 == 0 and player_id > 1:
                primary_player = player_id + 1
                player = Player.objects.create(player_id=primary_player)
                player.save()
                game_info_id = list(games.values())[-1]['id'] + 1
                game = Game.objects.create(game_id=game_info_id, number=number)
                game.save()
                Membership = PlayerGameInfo.objects.create(game=game, player=player)
                request.session['player'] = primary_player
                request.session['number'] = number

            elif player_id % 2 != 0 and player_id > 1:
                second_player = player_id + 1
                player = Player.objects.create(player_id=second_player)
                player.save()
                game_info_id = (list(games.values())[-1]["id"])
                game = games.all().filter(id = game_info_id)[0]
                Membership = PlayerGameInfo.objects.create(game=game, player=player)
                games.values()
                number_result = list(games.values())[-1]['number']
                request.session['player'] = second_player
                request.session['number'] = number_result
                request.session['attempt'] = 0

    #определение создателя и второго игрока
    id_user = list(session)[0][1]

    if id_user % 2 != 0 or id_user == 1:
        user = 1
        for item in data_player.values():
            if int(item['player_id']) == int(request.session['player']) and item['success_attempt'] != None:
                request.session['gameover'] = True
    else:
        user = 2

    number_result = list(session)[1][1]
    form = GameForm
    context = {
        'form': form,
        'id': user,
        'number': number_result,
        'success_attempt': success_attempt,
    }

    if request.method == 'POST':
        form = GameForm(request.POST)
        print(form)
        if form.is_valid():
            request.session['attempt'] += 1
            example_number = request.POST['example_number']
            #нахождение и отправка уведомление 1 игроку
            if int(example_number) == int(number_result):
                search_game = Game.objects.values()
                for game in search_game:
                    if game['number'] == int(number_result):
                        game_id = game['id']
                        for player in PlayerGameInfo.objects.values():
                            if player['game_id'] == game_id and request.session['player'] != player['player_id']:
                                first_player = data_player.get(player_id=player['player_id'])
                                first_player.success_attempt = int(request.session['attempt'])
                                first_player.save()
                                request.session['gameover'] = True
            context = {
                'form': form,
                'id': user,
                'number': int(number_result),
                'example_number': int(example_number)
            }

    return render(
        request,
        'home.html',
        context
        )