当前位置: 首页>>代码示例>>Python>>正文


Python Game.save方法代码示例

本文整理汇总了Python中game.models.Game.save方法的典型用法代码示例。如果您正苦于以下问题:Python Game.save方法的具体用法?Python Game.save怎么用?Python Game.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在game.models.Game的用法示例。


在下文中一共展示了Game.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def create(request):
    """ User will create games.

        Keyword arguments:
        request -
    """
    if request.method == "POST":
        form = GameForm(request.POST)
        if form.is_valid():
            sport = Sport.objects.get(sport=form.cleaned_data["sport"])
            # player = Player.objects.get(user=request.user) # unused var

            game = Game()
            game.sport = sport
            game.owner = request.user
            game.start_date_and_time = datetime.combine(
                form.cleaned_data["start_date"], form.cleaned_data["start_time"]
            )
            game.address = form.cleaned_data["address"]
            game.minimum_players = form.cleaned_data["minimum_players"]
            game.restrictions = form.cleaned_data["restrictions"]
            game.active = True

            if request.POST["lng"] and request.POST["lat"]:
                game.longitude = request.POST["lng"]
                game.latitude = request.POST["lat"]
                game.save()

                return HttpResponseRedirect("/game/%s/" % game.id)

    else:
        form = GameForm()
    return render(request, "create.html", {"form": form})
开发者ID:nsnitesh7,项目名称:courtside,代码行数:35,代码来源:views.py

示例2: new_game

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def new_game(request,pk):
    if request.method=='GET':
        player = Player.objects.get(pk=pk)
        players = Player.objects.all()
        genres  = Genre.objects.all()
        return render(request,'player/new_game.html',{'players':players,'genres':genres,'player':player})
    else:
        print '## Adding New Game ##'
        game = Game(name = request.POST['name'],date = timezone.now(),active=False)
        genres = request.POST.getlist('genres')
        game.save()
        for genre in genres:
            game.genres.add(Genre.objects.get(pk=genre))
        game.save()
        print '## Saved Game ID: %s with name %s ##' % (game.id,game.name)
        player = Player.objects.get(pk=pk)
        PG = Player_Game(game = game, player = player, score = 0,accepted = True, declined = False)
        print '## The first player in the game is %s with ID %s ##' % (player.name, player.id)
        PG.save()
        players = request.POST.getlist('players')
        for p in players:
            player = Player.objects.get(pk = int(p))
            PG = Player_Game(game = game, player = player, score = 0, accepted = False, declined = False)
            PG.save()
            print '## Player %s with ID %s was invited to this game ##' % (player.name,player.id)
        return HttpResponseRedirect("/player/%s/"%pk)
开发者ID:rlmeyers,项目名称:FiveWordsOrLess,代码行数:28,代码来源:views.py

示例3: create

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def create(request):
    """ User will create games.

        Keyword arguments:
        request -
    """
    if request.method == 'POST':
        form = GameForm(request.POST)
        if form.is_valid():
            sport = Sport.objects.get(sport=form.cleaned_data['sport'])
            #player = Player.objects.get(user=request.user) # unused var

            game = Game()
            game.sport = sport
            game.owner = request.user
            game.start_date_and_time = datetime.combine(form.cleaned_data['start_date'], form.cleaned_data['start_time'])
            game.address = form.cleaned_data['address']
            game.minimum_players = form.cleaned_data['minimum_players']
            game.restrictions = form.cleaned_data['restrictions']
            game.active = True

            if request.POST['lng'] and request.POST['lat']:
                game.longitude = request.POST['lng']
                game.latitude = request.POST['lat']
                game.save()

                return HttpResponseRedirect('/game/%s/' % game.id)

    else:
        form = GameForm()
    return render(request, 'create.html', {'form': form})
开发者ID:timonweb,项目名称:courtside,代码行数:33,代码来源:views.py

示例4: new_game

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def new_game(request):
    if request.is_ajax():
        if request.method == 'POST':
            desc = request.POST['game_description']
            if desc == '': desc = 'New Game'
            g = Game(description = desc)
            g.save()
            data = {'description': desc, 'id': g.id}
            html_str = Utils.game_info_template().substitute(
                                    game_id=g.id,
                                    description = desc,
                                    num_players = '0',
                                    max_players = g.max_players)
            data['html_str'] = html_str
            return HttpResponse(json.dumps(data))
开发者ID:tihuang,项目名称:politically-correct,代码行数:17,代码来源:views.py

示例5: index

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def index(request):
    player = get_player(request)
    if player is not None:
        # Delete old player and game objects
        if player.game and player == player.game.master:
            player.game.delete()
        player.delete()
        del request.session['player_pk']

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['player_name']
            create_game = form.cleaned_data['create_game']

            checkin = CheckIn()
            checkin.save()
            player = Player(name=name, rand_id=Player.generate_rand_id(), checkin=checkin)

            if create_game:
                checkin = CheckIn()
                checkin.save()
                bot = Bot()
                bot.save()
                game = Game(checkin=checkin, bot=bot)
                game.save()
                player.game = game
                player.index = 1

            player.save()
            
            if create_game:
                game.master = player
                game.players.add(player)
                game.save()

            request.session['player_pk'] = player.pk
            request.session['player_rand_id'] = player.rand_id
            request.session['player_name'] = name

            if create_game:
                return redirect('/create-game')
            else:
                return redirect('/join-game')
    else:
        form = LoginForm(initial={'player_name': request.session.get('player_name', '')})

    return render(request, 'game/index.html', {'form': form})
开发者ID:ReshNesh,项目名称:Zombies,代码行数:50,代码来源:views.py

示例6: new_game

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def new_game(request):
    form = GameForm()

    if request.method == 'POST':
        form = GameForm(request.POST)
        if form.is_valid():
            g = Game()
            g.acronym = form.get_acronym()
            g.max_players = int(form.cleaned_data['max_players'])
            g.minutes_per_round = int(form.cleaned_data['minutes_per_round'])
            g.save()
            g.add_player(request.user)

            return redirect('game.views.game', g.pk)

    return render(request, 'new_game.html', form=form)
开发者ID:dcrosta,项目名称:nymwit,代码行数:18,代码来源:views.py

示例7: index

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
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
      })
开发者ID:ZzCalvinzZ,项目名称:minesweeper,代码行数:49,代码来源:views.py

示例8: create

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
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))
开发者ID:andyyc,项目名称:socialbum,代码行数:47,代码来源:views.py

示例9: process

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
    def process(self):
        account_1 = self.cleaned_data['player_1']
        account_2 = self.cleaned_data['player_2']
        score_1 = self.cleaned_data['score_1']
        score_2 = self.cleaned_data['score_2']

        if account_1.rank > account_2.rank:
            upset = True
        else:
            upset = False

        new_game = Game(
            winner=account_1,
            loser=account_2,
            winning_score=score_1,
            losing_score=score_2,
            upset=upset
        )
        new_game.save()
开发者ID:Yipit,项目名称:yipit-matchup,代码行数:21,代码来源:forms.py

示例10: create

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def create(request):
    response_data = {}

    try:
        hashkey = _generate_hashkey()
        with transaction.atomic():
            while ( Game.objects.get_or_none(hashkey=hashkey) != None ) :
                hashkey = _generate_hashkey()
            g = Game(
                    num_players=request.POST['num_players'],
                    edition=Edition.objects.get(name=request.POST['edition']),
                    hashkey=hashkey,
                )
            g.save()
        response_data['success'] = True
        response_data['game_id'] = g.hashkey
    except (MultiValueDictKeyError, IntegrityError) as e:
        response_data['success'] = False
        response_data['errmsg'] = type(e).__name__ + ": " + e.message

    return HttpResponse(json.dumps(response_data, indent=2), content_type="application/json")
开发者ID:iizs,项目名称:aor,代码行数:23,代码来源:views.py

示例11: match

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def match(first, second):
    first_push_id = first.push_id[1:-1]
    first_push_id = re.sub(r'\s', '', first_push_id)
    second_push_id = second.push_id[1:-1]
    second_push_id = re.sub(r'\s', '', second_push_id)

    first.status = PLAYER_STATUS_ONLINE
    second.status = PLAYER_STATUS_ONLINE

    first.save()
    second.save()

    game = Game()
    game.status = settings.GAME_STATUS_NEW
    game.save()

    game.players.add(first)
    game.players.add(second)

    r       = Round()
    r.game  = game
    r.owner = random.choice((first, second))
    r.turn  = r.owner
    r.current = 1
    r.save()

    if len(first_push_id) == 64:
        print ('--- sending notifications for ', first.login)
        connection.send(first_push_id, {
            'changed': [{'entity': 'user', 'entity_id': first.id}],
            'new': [{'entity': 'game', 'entity_id': game.id}],
        })
    if len(second_push_id) == 64:
        print ('--- sending notifications for ', second.login)
        connection.send(second_push_id, {
            'changed': [{'entity': 'user', 'entity_id': second.id}],
            'new': [{'entity': 'game', 'entity_id': game.id}],
        })
开发者ID:ado666,项目名称:skirmish_server,代码行数:40,代码来源:uncle.py

示例12: create_game

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def create_game(request):
	words = ""
	if request.method == "POST":
		words = []
		players = request.POST.getlist('player')
		players = map(int, players)
		numberWords = int(request.POST.get('number_words'))
		nameGame = request.POST.get('name_game')
		
		password = random.randint(1, 100)
		newGame = Game(name=nameGame, creator = request.user, password = password)
		newGame.save()
		
		for player in players:
			newGame.user.add(User.objects.get(id = player))
			words += UserWord.objects.filter(user = User.objects.get(id=player))[0:numberWords]
		
		for word in words:
			newGame.userword_set.add(word)
			
		#words = map(lambda x: {'word': x.word.word, 'id': x.id}, words)
		#json = simplejson.dumps({'gameId':newGame.id, 'words':words})
		gameId = newGame.id
	return request_words(request, gameId, password)
开发者ID:KashinYana,项目名称:hat,代码行数:26,代码来源:views.py

示例13: test_get_games_in_state

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
    def test_get_games_in_state(self):
        g1 = Game(map=self.map, players="['', '']", state=Game.LOBBY)
        g1.save()
        g2 = Game(map=self.map, players="['', '']", state=Game.LOBBY)
        g2.save()

        g3 = Game(map=self.map, players="['', '']", state=Game.ACTIVE)
        g3.save()

        lobby_games = set(list(Game.get_games_in_state(Game.LOBBY)))
        self.assertEqual(lobby_games, set([g1, g2]))

        active_games = set(list(Game.get_games_in_state(Game.ACTIVE)))
        self.assertEqual(active_games, set([g3]))

        finished_games = set(list(Game.get_games_in_state(Game.FINISHED)))
        self.assertEqual(finished_games, set([]))
开发者ID:hellochar,项目名称:the_game_bazaar,代码行数:19,代码来源:tests.py

示例14: new_game

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def new_game(request):
    "Create a new game and redirect to its url."
    game = Game()
    perform_move(game)  # Computer goes first
    game.save()
    return redirect(game)
开发者ID:mirhampt,项目名称:Tic-Tac-Toe,代码行数:8,代码来源:views.py

示例15: request_game

# 需要导入模块: from game.models import Game [as 别名]
# 或者: from game.models.Game import save [as 别名]
def request_game(request):
  session_id = request.session.get('_auth_user_id', -1)
  if(session_id == -1):
    return login_page(request)
  username = User.objects.get(pk=session_id)
  platform = get_platform(request.get_signed_cookie('platform', 'x86'))
  if(request.get_signed_cookie('at_index', default='False') == 'True'):
    if(len(GameRequest.objects.filter(host=username)) >= 1):
      #return HttpResponse("Can Only host one game at a time!!")
      csrf_request = {'username' : str(username)}
      return render_to_response('delete_req.html',csrf_request, context_instance=RequestContext(request))
    num_players = get_request_param(request,'num_players', 0)
    has_cpu = get_request_param(request,'has_cpu', 0)
    gamerequest = GameRequest(requested_players=num_players, accepted_players=1, has_cpu=has_cpu, host=username)
    gamerequest.save()
    gamerequest.player_names.add(username)
    gamerequest.save()
    game = Game(num_players=num_players, has_cpu=False, log = '', num_cpu_dice = 0, turn=1, pk=gamerequest.id, cpu_roll=0, num_dice = NUM_DICE*num_players, timestamp=0)
    game.save()
    #chat related?
    room = Room(id=game.id)
    room.save()
    userprofile = UserProfile.objects.get(user=username)
    userprofile.turn=1
    userprofile.num_dice = NUM_DICE 
    userprofile.save()
    csrf_request = {'message' : 'waiting'} 
    csrf_request.update(csrf(request))
    response = render_to_response('wait.html',  csrf_request, context_instance=RequestContext(request))
    response.set_signed_cookie('at_index', 'False')
    response.set_signed_cookie('gamerequest_id', str(gamerequest.id))
    #originally i stored turn in a cookie.  then i realized it was not feasible because
    #one player must know the turns of the others, so i now store in db.  I may remove the
    #cookie later
    response.set_signed_cookie('turn', 1)
    response.set_signed_cookie('playing_cpu', 0)
    return response
  else:
    int_gamerequest_id = int(request.get_signed_cookie('gamerequest_id'))
    try:
      gamerequest = GameRequest.objects.get(pk=int_gamerequest_id)
    except:
      gamerequest = -1
    if(gamerequest == -1):
      csrf_request = {} 
      csrf_request.update(csrf(request))
      return render_to_response(index_page[platform],  csrf_request, context_instance=RequestContext(request))
       
    #during development, >= will save me time.  later should make ==
    #if(gamerequest.accepted_players >= gamerequest.requested_players):
    if(gamerequest.accepted_players == gamerequest.requested_players):
      try:
        game = Game.objects.get(pk=gamerequest.id)
      except:
        game = -1
      if(game == -1):
        csrf_request = {} 
        csrf_request.update(csrf(request))
        return render_to_response(index_page[platform],  csrf_request, context_instance=RequestContext(request))
      game.players = gamerequest.player_names.all()
      game.save()
      csrf_request = {'multiplayer_begin':True, 
                      'host' : gamerequest.host, 
                      'num_players' : gamerequest.requested_players,
                      'game_fsm' : 0,
                      'playing_cpu' : 0,
                      'username' : str(username),
                      'dice_list' : [],
                      'game_id' : gamerequest.id#this doesn't seem to be working due to auto refresh 
                     }
      csrf_request.update(csrf(request))
      response = render_to_response(main_page[platform],  csrf_request, context_instance=RequestContext(request))
      response.set_signed_cookie('inagame', 'True')
      response.set_signed_cookie('game_id', gamerequest.id)
      response.set_signed_cookie('game_fsm', 0)
      response.set_signed_cookie('bullshit_timestamp', 0)
      return response
    elif(gamerequest.accepted_players < gamerequest.requested_players):
      csrf_request = {'message' : 'still waiting'} 
      csrf_request.update(csrf(request))
      response = render_to_response('wait.html',  csrf_request, context_instance=RequestContext(request))
      return response
    else:
      #if accepted_players > requested players then the user has probably hit back on browser
      #and attempted to reentered.  don't allow, redirect to index
      csrf_request = {} 
      csrf_request.update(csrf(request))
      return render_to_response(index_page[platform],  csrf_request, context_instance=RequestContext(request))
开发者ID:joshyg,项目名称:liarsdice,代码行数:90,代码来源:views.py


注:本文中的game.models.Game.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。