• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.Game类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: post

 def post(self):
     """
     CREATE a new Game entity 
     """
     self.record_usage()
     namespace_manager.set_namespace(users.get_current_user().user_id())
     param_map = {}
     param_map['player_faction'] = self.request.get('player_faction')
     param_map['player_warcaster'] = self.request.get('player_warcaster')
     param_map['opponent_name'] = self.request.get('opponent_name', '')
     param_map['opponent_faction'] = self.request.get('opponent_faction')
     param_map['opponent_warcaster'] = self.request.get('opponent_warcaster')
     param_map['result'] = self.request.get('result')
     param_map['size'] = int(self.request.get('size', 0))
     param_map['won'] = self.request.get('won') == 'true'
     param_map['draw'] = self.request.get('draw') == 'true'
     param_map['teaching'] = self.request.get('teaching') == 'true'
     param_map['location'] = self.request.get('location', '')
     param_map['game_type'] = self.request.get('game_type', '')
     date = self.request.get('date')
     try:
         real_date = datetime.datetime.strptime(date,'%m/%d/%Y')
     except (ValueError):
         real_date = datetime.datetime.strptime(date,'%Y-%m-%d')
     param_map['date'] = real_date
     param_map['created_at'] = datetime.datetime.now()
     logging.error(param_map)
     game = Game(**param_map)
     game.put()
     self.response.out.write(game.key.urlsafe())
开发者ID:dbsmash,项目名称:field-promotion,代码行数:30,代码来源:rest_handler.py


示例2: startGame

def startGame(session):
    """
    Starts the new game in one of the sessions.
    """

    game = Game()
    game.session = session
开发者ID:Vycas,项目名称:online1000,代码行数:7,代码来源:game.py


示例3: get_sendable_board

def get_sendable_board(game, side):
    board = game.get_board()

    # Only continue if the game hasn't finished
    if game.has_ended():
        if side == 1:
            return Game.reverse_board(board)
        else:
            return board

    if side == 0 and not game.blue_setup:
        board[0] = unknown_row(side)
        board[1] = unknown_row(side)
        board[2] = unknown_row(side)
        board[3] = unknown_row(side)

        return board

    else:
        hidden_side_board = hide_side(board, side)

        if side == 1:
            return Game.reverse_board(hidden_side_board)
        else:
            return hidden_side_board
开发者ID:benletchford,项目名称:stratego.io,代码行数:25,代码来源:board_utils.py


示例4: post

    def post(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url("/"))
            return

        game_name = self.request.get("game_name")
        if not game_name:
            self.response.write("No game name specified")
            return

        game_key = db.Key.from_path("Game", game_name)
        game = db.get(game_key)

        if not game:
            game = Game(key_name=game_name)
            game.put()

        logging.info("Game: {0}".format(game))

        player = Player(user=user, parent=game)
        player.put()

        token = channel.create_channel("{0}:{1}".format(game_name, user.user_id()))

        logging.info("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
        self.redirect("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
开发者ID:dillonbly,项目名称:oh-the-humanity,代码行数:27,代码来源:join_game_handler.py


示例5: open_or_new_games

def open_or_new_games(request):
    if not request.COOKIES.get('nickname', ''):
        return HttpResponseRedirect(reverse(set_nickname))

    if request.method == 'POST':
        form = NewGameForm(request.POST)
        if form.is_valid():
            nickname = re.sub(r'\W', '', request.COOKIES.get('nickname', ''))
            num_players = form.cleaned_data['number_of_players']
            game = Game(name=nickname, num_players=num_players)
            game.save()
            try:
                player = game.add_player(nickname, True)
                request.session['player_id'] = player.id
                request.session['game_id'] = game.id
            except Game.InvalidPlayer as x:
                pass
                #TODO: add session error message

            return HttpResponseRedirect(reverse(current_game))
    else:
        form = NewGameForm()

    return direct_to_template(request, 
            'open_or_new_games.html', {'form': form })
开发者ID:MattConrad,项目名称:Liars-Dice-Django,代码行数:25,代码来源:views.py


示例6: cancel_game

 def cancel_game(self, request):
     """
     Cancels a Blackjack Marathon game based on key.
     """
     profile_key = Profile.get_profile_from_user().key
     Game.cancel_game(profile_key, request.urlsafe_game_key)
     return StringMessage(message='Game cancelled successfully.')
开发者ID:prestononeal,项目名称:blackjack_marathon,代码行数:7,代码来源:api.py


示例7: test_make_deck_shuffle_hit

 def test_make_deck_shuffle_hit(self):
     # setup
     player = Player('cory', 'password')
     game = Game('Blackjack')
     game.players.append(player)
     h = Hand()
     h2 = Hand()
     game.hands.append(h)
     player.hands.append(h2)
     cards = piece_maker(suits, card_values, 1)
     h.cards.extend(cards)
     cards_app.session.commit()
     # end of setup
     # deck is made in setUp() with piece_maker() ha
     game.deck = h
     game.hands.append(h2)
     deck = game.deck
     hand2 = h2
     cards_app.session.flush()
     assert deck.cards != shuffle(deck)
     hand_before_hit = len(hand2.cards)
     deck_before_hit = len(deck.cards)
     hit(hand2, 1)
     cards_app.session.commit()
     # do we still have 52 cards after hitting?
     assert len(set(deck.cards)) + len(set(hand2.cards)) == 52
     assert len(deck.cards) == deck_before_hit-1
     assert len(hand2.cards) == hand_before_hit+1
开发者ID:maddencs,项目名称:cards,代码行数:28,代码来源:tests.py


示例8: post

    def post(self):
        game = Game()

        #Check logged in
        user = users.get_current_user()
        if not user:
            self.response.write(json.dumps(dict(error="Dude, you gotta be logged in! Try reloading this page.")))
            return

        this_player = game.selectOne(config.JIVE_PROFILE_TBL, "fullname, title, picture_binary, id", "`email` = {}", [user.email()])
        if this_player is None:
            logging.info("couldn't find player in jive_profile table (email: '{0}')".format(email))
            self.response.write(json.dumps({"result":"refresh"}))
            return

        #Get the json passed from the client page
        jsonstring = self.request.body
        jsdict = json.loads(jsonstring)

        if 'filterchange' not in jsdict:
            ret = self.choice_picked(game, this_player, jsdict)
        else:
            ret = self.new_filter(game, this_player, jsdict)
            
        self.response.write(json.dumps(ret))
开发者ID:mdsol,项目名称:jive,代码行数:25,代码来源:views.py


示例9: createGame

    def createGame(self, request):
        """
        a player creates a game of a unique name
        """
        if request.game_name is None:
            raise endpoints.UnauthorizedException(
                'game_name is required to create a game')
        player = Player.query(Player.displayName == request.player_name).get()
        if not player:
            raise endpoints.NotFoundException(
                'No player found with name: {}' .format(request.player_name))
        elif Game.query(Game.name == request.game_name).get():
            raise endpoints.ConflictException(
                    'A Game with that name already exists!')
        else:
            # allocate new Game ID with Player key as parent
            # allocate_ids(size=None, max=None, parent=None, **ctx_options)
            # returns a tuple with (start, end) for the allocated range,
            # inclusive.
            p_key = player.key
            g_id = Game.allocate_ids(size=1, parent=p_key)[0]
            # make Game key from ID; assign initial values to the game entity
            g_key = ndb.Key(Game, g_id, parent=p_key)
            data = {}  # is a dict
            data['key'] = g_key
            data['name'] = request.game_name
            data['board'] = ['' for _ in range(9)]
            Game(**data).put()

            taskqueue.add(params={'email': player.mainEmail,
                          'gameInfo': repr(request)},
                          url='/tasks/send_confirmation_email')
            game = g_key.get()
            return game._copyGameToForm
开发者ID:zhangtreefish,项目名称:Project-4-for-Full-Stack-Nanodegree-at-Udacity,代码行数:34,代码来源:api.py


示例10: create_game

  def create_game(self, request) :
    """Create new conference."""
    #get the user ID first and make sure they're authorised
    user = endpoints.get_current_user()
    if not user:
      raise endpoints.UnauthorizedException('Authorization required')
    
    user_id = getUserId(user)

    #now create the game entity and insert it
    game = Game(owner=user_id, 
      player1=GameMiniForm.get('player1'), 
      player2=GameMiniForm.get('player2'),
      name=GameMiniForm.get('name'))

    playerTurn = 1
    #set the player turn randomly
    if bool(random.getrandbits(1)) :
      playerTurn = 1
    else :
      playerTurn = 2

    game.playerTurn = playerTurn

    game_key = game.put()
    url_key = game_key.urlsafe() 

    #return all of the game details, including a game key
    return GameForm(id=url_key, owner=user_id, 
      player1=game.player1, 
      player2=game.player2,
      name=game.name) 
开发者ID:danielblignaut,项目名称:Battleships,代码行数:32,代码来源:battleship_api.py


示例11: _get_team_win_loss

def _get_team_win_loss(team):
    team_a_count = Game.query().filter(Game.team_a == team.name).count()
    team_b_count = Game.query().filter(Game.team_b == team.name).count()
    game_count = team_b_count + team_a_count
    win_count = Game.query().filter(Game.winner == team.name).count()
    per = round(100 * float(win_count)/game_count)
    return [_get_team_name_link(team.name), team.elo, game_count, win_count, per]
开发者ID:bojoer,项目名称:battle-code-runner,代码行数:7,代码来源:main.py


示例12: _get_team_map_win_loss

def _get_team_map_win_loss(team, map):
    team_a_count = Game.query().filter(Game.map == map).filter(Game.team_a == team.name).count()
    team_b_count = Game.query().filter(Game.map == map).filter(Game.team_b == team.name).count()
    win_count = Game.query().filter(Game.map == map).filter(Game.winner == team.name).count()
    game_count = team_b_count + team_a_count
    per = 0 if not game_count else round(100 * float(win_count)/game_count)
    return [map, game_count, win_count, per]
开发者ID:bojoer,项目名称:battle-code-runner,代码行数:7,代码来源:main.py


示例13: get

    def get(self):     
      # Can't provide an ordering here in case inequality filters are used.      
       base_query = Game.all()
       count = base_query.count()
       
       results = base_query.fetch(count)
       #db.delete(results)
   #    for game in results:
    #   	 		resultsobj = resultsobj + simplejson.dumps({"latitude":game.location.lat,"longitude":game.location.lon,"name":game.name,"type":game.game_type})
    #   objs = simplejson.dumps(resultsobj)
       
       public_attrs = Game.public_attributes()
      
       results_obj = [
          _merge_dicts({
            'lat': result.location.lat,
            'lng': result.location.lon,
            },
            dict([(attr, getattr(result, attr))
                  for attr in public_attrs]))
          for result in results]
		#for song in results:
    	#print song.type
  #     for result in query:
  # 				 resultsobj.push( "Title: " + result.address
       self.response.out.write(simplejson.dumps({
       'status': 'success',
       'count': count,
       'results': results_obj
     	}))
开发者ID:westinedu,项目名称:handsupmain,代码行数:30,代码来源:service.py


示例14: GameView

class GameView(TemplateView):
    template_name = 'gameshow/game.html'

    def _start_game(self):
        player = Player.objects.create(name="Some Name", score=0)
        self.thegame = Game()
        self.thegame.players = player
        self.thegame.title = 'My Game Title'
        self.thegame.description = "Blah Blah Blah"
        self.thegame.save()

    def post(self, request, *args, **kwargs):
        form = GameScore(request.POST)
        if form.is_valid():
            messages.add_message(self.request, messages.INFO, message="Enjoy your game!")
            return redirect('game_main')
        else:
            return self.get(request, form=form)

    def get_context_data(self, **kwargs):
        self._start_game()
        return {
            'form': GameScore() if not kwargs.get('form') else kwargs['form'],
            'game': self.thegame,
            }
开发者ID:kbarr,项目名称:PSAM-5150,代码行数:25,代码来源:views.py


示例15: test_blackjack_player_wins

 def test_blackjack_player_wins(self):
     player = Player('cory','password')
     game = Game('Blackjack')
     hand = Hand()
     player.bank = 100
     player.hands.append(hand)
     game.hands.append(hand)
     game.players.append(player)
     bank_before_bet = player.bank
     # cards_app.session.commit()
     cards_app.session.flush()
     bet(hand, 50)
     cards = [Card(sequence=1), Card(sequence=10)]
     hand.cards.extend(cards)
     count_blackjack(hand)
     evaluate_hit(hand)
     # player wins with nautral evaluate_hit
     assert player.bank == bank_before_bet - 50
     # player stands on 18, dealer stands on 17
     hand.cards = [Card(sequence=10), Card(sequence=8)]
     bet(hand, 50)
     game.dealer = Player('cory','password')
     dealer = game.dealer
     dealer.cards = [Card(sequence=10), Card(sequence=17)]
     dealer_hand = Hand()
     dealer_hand.cards = dealer.cards
开发者ID:maddencs,项目名称:cards,代码行数:26,代码来源:tests.py


示例16: game

def game(request):

    #check if authed
    # print "user " + str(request.user)
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    if request.method == 'GET':
        #return a list of games available
        return get_json(list(Game.objects.all()))
    elif request.method == 'POST':
        # make sure authed

        try:
            json_data = json.loads(request.body)
            # user = this user
            new_game = Game(status = Game.OPEN)
            new_game.save()
            new_game.players.add(request.user)
            amounts = json_data['amounts']
            for i, amount in enumerate(amounts):
                new_pile = Pile(
                    position = i,
                    amount = amount,
                    game = new_game
                )
                new_pile.save()
            return get_json(new_game)
        except Exception, e:
            return HttpResponseServerError("Malformed data!")
开发者ID:nznelson,项目名称:anran-python,代码行数:30,代码来源:views.py


示例17: test_points_multiple_games

 def test_points_multiple_games(self):
     game1 = Game(
         #tournament = self.tournament1,
         time = self.time,
         location = self.location,
         teamA=self.team1,
         teamB=self.team2,
         score_teamA=3,
         score_teamB=1,
     )
     
     game2 = Game(
         #tournament = self.tournament1,
         time = self.time,
         location = self.location,
         teamA=self.team1,
         teamB=self.team2,
         score_teamA=1,
         score_teamB=1,
     )
     
     game1.save()
     game2.save()
     self.assertEquals(self.team1.points, 4)
     self.assertEquals(self.team2.points, 1)
     game1.delete()
     game2.delete()
开发者ID:gloggi,项目名称:habatu,代码行数:27,代码来源:tests.py


示例18: create_game

def create_game(game_type, room_id):
    if request.method == 'GET':
        dealer = Player()
        session.add(dealer)
        game = Game(game_type)
        session.add(game)
        deck = Hand()
        session.add(deck)
        game.deck = deck
        if game_type == 'Blackjack':
            i = 1
            while i <= 5:
                seat = Seat(i)
                game.seats.append(seat)
                session.commit()
                i += 1
        game.time = datetime.datetime.now()
        game.dealer = dealer
        dealer_hand = Hand()
        dealer.hands.append(dealer_hand)
        game.players.append(current_user)
        session.commit()
        if room_id != 0:
            room = session.query(GameRoom).filter(GameRoom.id == room_id).all()[0]
            room.current_game = game
            return redirect(url_for('game_room', room_id=room_id))
        else:
            room = GameRoom()
            room.current_game = game
            session.commit()
            return redirect(url_for('game_room', room_id=room.id))
开发者ID:maddencs,项目名称:cards,代码行数:31,代码来源:cards_app.py


示例19: get

    def get(self, name):
        if not users.get_current_user():
            self.redirect(users.create_login_url(self.request.uri))
        logging.info('Iniciando busca')
        results = search_metacritic(name, 'game')
        logging.info('Fetch concluido')
        output = []

        for result in results:
            query = Img.all()
            query.filter('url =', result[1])
            img = query.fetch(1)[0]
            query = Game.all()
            query.filter('cover =', img)
            if not query.count():
                platform = str(result[1])[:str(result[1]).rfind('/')].replace('/game/','')
                game = Game(name=str(result[0]),cover=img,platform=platform,score=str(result[2]))
                game.put()
            else:
                game = query.fetch(1)[0]
            output.append([img.key().id(), result[0], game.key().id()])

        template_values = {'results': output}

        path = os.path.join(os.path.dirname(__file__), 'search.html')
        self.response.out.write(template.render(path, template_values))
开发者ID:fabiomdiniz,项目名称:arcateca,代码行数:26,代码来源:views.py


示例20: __setupGame

 def __setupGame(self, startingBoard, turns):
     startingBoard = self.__translateBoard(startingBoard)
     player1 = Player(name="player1")
     player2 = Player(name="player2")
     game = Game(player1=player1, player2=player2)
     game.board = startingBoard
     game.turn = turns
     return game
开发者ID:mmatthews06,项目名称:Tic-Tac-Toe_original,代码行数:8,代码来源:tests.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Group类代码示例发布时间:2022-05-27
下一篇:
Python models.Form类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap