Пример #1
0
    def __init__(self):
        self.world = World(10)
        self.gridWidth = 15
        self.gridHeight = 20
        self.playerSize = 0.5

        self.speed = 0.03
        self.killLine = -0.1

        self.platforms = [Platform(PhysicsVector(0, 0, 0), PhysicsVector(gridWidth, 0, 0))]

        self.minPlatformWidth = 1.0
        self.maxPlatformWidth = 6.0
        self.maxPlatformGaps = 8.0
        self.probabilityOfNoPlatforms = 0.2
        self.gapProbability = 0.8

        self.lastLevelGenerated = 0

        self.skipped = 0
        self.maxConsecutiveSkips = 2

        self.player = Player(
            PhysicsVector(self.gridWidth / 3.0, 0, self.gridHeight / 2.0),
            PhysicsVector(0, 0, 0)
        )
        self.world.objects = [self.player]

        self.generateUntilLevel(int(self.gridHeight) - 5)
Пример #2
0
    def post(self):
        try:
            tReply = json.loads(self.request.body)
            sender = Player.get_by_key_name(tReply["sender"])
            recipient = Player.get_by_key_name(tReply["recipient"])

            if tReply['action']=="rejected":
                sender.move += 1
                db.delete(tReply["key"])
            elif tReply['action']=="accepted":
                #credit and debit gem
                sender.gem -= tReply["price"]
                recipient.gem += tReply["price"]

                #credit and debit goods
                if tReply["goods"]=="fuel":
                    sender.fuel += int(tReply["amount"])
                    recipient.fuel -= int(tReply["amount"])
                elif tReply["goods"]=="cargo":
                    sender.cargo += tReply["amount"]
                    recipient.cargo -= tReply["amount"]
                elif tReply["goods"]=="food":
                    sender.food += tReply["amount"]
                    recipient.food -= tReply["amount"]

                sender.put()
                recipient.put()

                db.delete(tReply["key"])

            self.response.out.write("Successful")
        except:
            self.response.out.write(sender)
Пример #3
0
	def get(self):
		try:
			#email,gem,move,fuel,cargo,food
			deyang = Player.newPlayer(Player(key_name='deyang'),'deyang',10,10,10,40,20,0,0)
			kelvin = Player.newPlayer(Player(key_name='kelvin'),'kelvin',20,10,20,50,70,0,0)
			siewlin = Player.newPlayer(Player(key_name='siewlin'),'siewlin',30,10,30,20,50,0,0)
			brian = Player.newPlayer(Player(key_name='brian'),'brian',40,10,40,50,60,0,0)
			deyang.put()
			kelvin.put()
			siewlin.put()
			brian.put()
		
			trade = TradeRequest.newTradeRequest(TradeRequest(key_name='*****@*****.**'),'*****@*****.**','*****@*****.**',10,10,20,'onging')
			trade.put()
			trade2 = TradeRequest.newTradeRequest(TradeRequest(key_name='*****@*****.**'),'*****@*****.**','*****@*****.**',10,10,20,'onging')
			trade2.put()
			trade3 = TradeRequest.newTradeRequest(TradeRequest(key_name='*****@*****.**'),'*****@*****.**','*****@*****.**',10,10,20,'onging')
			trade3.put()
			trade4 = TradeRequest.newTradeRequest(TradeRequest(key_name='*****@*****.**'),'*****@*****.**','*****@*****.**',10,10,20,'onging')
			trade4.put()
		
			answer = ['help3','me']
			answer.append('please')
			question1 = Question.newQuestion(Question(key_name='help'),'test','MCQ',answer,answer,'*****@*****.**',answer)
			question1.put()

			self.response.out.write('Successful in creating Player Object & trade Object & question Object')

		except:
			self.response.out.write()
Пример #4
0
def test_base():
    factory = WorldGetter(3)
    _map = Map(factory.get_map())
    _map.pos = factory.get_pos()
    objects = Objects(factory.get_objects())
    player = Player(factory.get_player())
    i = 30
    gui = GUI(player, _map, objects, None)
    gui.fps = 30
    gui.paused = True
    while player.is_alive:
        gui.turn()
        if gui.paused == False:
            objects.trains[1].line_idx = 1
            if objects.trains[1].position == 4:
                objects.trains[1].speed = -1
            elif objects.trains[1].position == 0:
                objects.trains[1].speed = 1
            objects.trains[1].position += objects.trains[1].speed
            objects.trains[1].line_idx = 10
            if objects.trains[2].position == 5:
                objects.trains[2].speed = -1
            elif objects.trains[2].position == 0:
                objects.trains[2].speed = 1
            objects.trains[2].position += objects.trains[2].speed
            if i > 0:
                i -= 1
            else:
                player.is_alive = False

    gui.close()
Пример #5
0
    def test_one_winner_with_one_multiple_same_value_card(self):
        #init player 1
        cards_player1 = []
        cards_player1.append(Card(0, 1))
        cards_player1.append(Card(3, 10))
        hand_player1 = Hand(cards_player1)
        player1 = Player("Player 1", hand_player1)

        # init player 2
        cards_player2 = []
        cards_player2.append(Card(2, 9))
        cards_player2.append(Card(1, 8))
        hand_player2 = Hand(cards_player2)
        player2 = Player("Player 2", hand_player2)

        #init Table
        cards_table = []
        cards_table.append(Card(0, 3))
        cards_table.append(Card(1, 8))
        cards_table.append(Card(2, 4))
        cards_table.append(Card(0, 7))
        cards_table.append(Card(0, 2))

        players = []
        players.append(player1)
        players.append(player2)

        pack = Pack()

        table = Table(players, pack)
        table.set_cards(cards_table)

        expected_winner = []
        expected_winner.append(player2)
        self.assertEqual(expected_winner, get_winners(players, table))
Пример #6
0
 def enterPlayer(self, ctx: dgdlParser.PlayerContext):
     data = str(ctx.getText())
     player = Player()
     if str(ctx.NAME()) in data:
         player.name = StringParser.between(data, str(ctx.NAME()) + COLON,
                                            COMMA if (ctx.roles()) else CLOSE_BRACE)
     if ctx.roles():
         roles = self.visit(ctx.roles())
         player.roles = roles
     self.game.players.list.append(player)
Пример #7
0
    def __init__(self, num_tiles, num_mines):
        super(MineSweeper, self).__init__()
        self.n = num_tiles
        self.num_mines = num_mines
        self.player = Player()
        self.setWindowTitle("Minesweeper")

        squareGame = QAction("&Square", self)
        squareGame.triggered.connect(self.generate_square_map)

        hexGame = QAction("&Hexagonal", self)
        hexGame.triggered.connect(self.generate_hex_map)

        coloredGame = QAction("&Colored", self)
        coloredGame.triggered.connect(self.generate_colored_map)

        quitGame = QAction("&Quit", self)
        quitGame.triggered.connect(self.quit_game)

        self.statusBar()

        mainMenu = self.menuBar()
        gameMenu = mainMenu.addMenu('&Game')
        gameMenu.addAction(squareGame)
        gameMenu.addAction(hexGame)
        gameMenu.addAction(coloredGame)
        gameMenu.addAction(quitGame)

        w = QWidget()

        

        self.clock = QLabel()
        self.clock.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        self.clock.setText("000")
        self.grid = QGridLayout()
        self.grid.setSpacing(5)

        self.gameStatus = 1

        vb = QVBoxLayout()
        vb.addWidget(self.clock)
        vb.addLayout(self.grid)
        w.setLayout(vb)
        self.setCentralWidget(w)

        self.show()
Пример #8
0
    def read_player(self):
        if not self.read_boolean():
            return None

        return Player(self.read_long(), self.read_boolean(),
                      self.read_string(), self.read_boolean(), self.read_int(),
                      self.read_enum(Faction))
Пример #9
0
def test_valid():
    factory = WorldGetter(3)

    player = Player(factory.get_player())
    map_graph = Map(factory.get_map())
    objects = Objects(factory.get_objects())

    strategy = Strategy(player, map_graph, objects)
    strategy.get_invalid_pos = lambda x: {}

    reserv_pos = {
        1: {
            0: Position(None, 1, 3),
            1: Position(2),
            2: Position(None, 12, 1)
        },
        2: {
            0: Position(None, 2, 2),
            1: Position(None, 2, 1),
            2: Position(None, 2, 2)
        }
    }

    strategy.trains_reservations = reserv_pos
    train = objects.trains[1]
    print(strategy.valid(train, Position(None, 1, 1), Position(1)))
Пример #10
0
def get_match_team(formation: List[Formation], verbose: bool = True):
    db = PlayerSimpleDbConnect()
    used_players = []
    selected_players = []

    player_count = 0
    for f in formation:
        player_count += f.quantity
        players = db.get_best_players(f.position,
                                      f.quantity + len(selected_players))
        for p in players:
            player = Player.convert_from_tuple(p)
            try:
                used_players.index(player.id)
            except:
                player.my_pos = f.position.upper()
                used_players.append(player.id)
                selected_players.append(player)
                if len(used_players) == player_count:
                    break

    if verbose:
        for p in selected_players:
            print('%s - %s, %s' % (p.my_pos, p.name, p.bpos))

    return selected_players
Пример #11
0
    def __init__(self, base, mapNo):
        self.isListening = False

        # Holds rigid bodies, joints, controls global params
        self.world = OdeWorld()
        self.world.setGravity(0, 0, -9.8)

        st = SurfaceType()
        st.load(self.world)
        del st

        self.contactgroup = OdeJointGroup()

        self.space = OdeHashSpace()
        self.space.setAutoCollideWorld(self.world)
        self.space.setAutoCollideJointGroup(self.contactgroup)
        self.space.setCollisionEvent(EventType.ODE_COLLISION)
        base.accept(EventType.ODE_COLLISION, self.onCollision)

        self.ball = Ball(self.world, self.space, "Johanneksen pallo")

        self.level = Level(self, mapNo)
        self.player = Player("Johannes")

        self.camera = Camera(base, self.ball)
Пример #12
0
	def get(self):
		getEmail = self.request.get('email')
		#if email passed in, then return stats for player
		if (getEmail):
			players = db.GqlQuery("SELECT * FROM Player where email=:email",email=getEmail)
			a = {}
			if players.count()==1:
				for player in players:
					stats = {
						"email":player.email,
						"gem":player.gem,
						"move":player.move,
						"fuel":player.fuel,
						"cargo":player.cargo,
						"food":player.food,
						"spend":player.spend,
						"share":player.share
					}
			result = json.dumps(stats)
			self.response.out.write(result)
		#if no email passed in, return email of all players
		else:
			q = Player.all(keys_only=True)
			player_keys = q.fetch(1000)
			random_keys = random.sample(player_keys, 15)
			list = db.get(random_keys)
			list2 = []
			for x in list:
				player = x
				player.put()
				list2.append(player.email)
			result = json.dumps(list2)
			self.response.out.write(result)
Пример #13
0
 def create_new_character(self, name, classtype):
     # Kolla ifall namnet redan finns. Om ja, returnera False. Annars skapa ny player och returnera True
     if self.get_character_by_name(name):
         return False
     else:
         self.list_of_characters.append(Player(name, classtype))
         self.save_list_characters()
         return True
Пример #14
0
def create_player(nicks, tokens):

    players = []

    for i in range(len(nicks)):
        players.append(Player(nicks[i], tokens[i]))

    return players
Пример #15
0
def testGetMinutesMalikBeasley():
    player = Player("1627736", "Malik Beasley", "Minnesota Timberwolves")
    actual = playerService.get2020Minutes(player.id)

    assert actual == [
        TeamMinutes('Minnesota Timberwolves', 463),
        TeamMinutes('Denver Nuggets', 746)
    ]
Пример #16
0
def get_world():
    factory = WorldGetter(3)

    player = Player(factory.get_player())
    map_ = Map(factory.get_map())
    map_.pos = factory.get_pos()
    objects = Objects(factory.get_objects())

    return World(player, map_, objects)
Пример #17
0
def user_exist():
    username = "******"
    if users.get_current_user() != None:
        username = users.get_current_user().nickname()
    q = Player.all()
    q.filter('email =', username)
    result = q.fetch(1)
    for r in result:
        return r.email == username
Пример #18
0
def init_table(number_players):
    #initialise pack of card"""
    pack = init_pack()
    #initialise players"""
    i = 1
    players = []
    while i <= number_players:
        players.append(Player("Player " + str(i), Hand(remove_cards(2, pack))))
        i += 1
    return Table(players, pack)
Пример #19
0
 def get(self):
     username = users.get_current_user().nickname()
     q = Player.all()
     q.filter('email =', username)
     result = q.fetch(1)
     for r in result:
         if r.email == username:
             self.response.out.write("true")
         else:
             self.response.out.write("false")
Пример #20
0
 def __init__(self):
     self.fps = 60
     self.towers_position = []
     self.enemies_positions = []
     self.game_player = Player("Player 1", 0, 100)
     self.main_window = MainWindow(self.game_player)
     self.timer = QTimer()
     self.timer.timeout.connect(self.main_window.updateUI)
     self.timer.start(self.REFRESH_RATE)
     self.start_game()
Пример #21
0
    def read_player(self):
        if not self.read_boolean():
            return None

        return Player(self.read_long(),
                      self.read_boolean(), self.read_string(), self.read_int(),
                      self.read_boolean(), self.read_double(),
                      self.read_double(), self.read_double(),
                      self.read_double(), self.read_double(),
                      self.read_double(), self.read_boolean(),
                      self.read_boolean())
Пример #22
0
 def multi_login(self,
                 name,
                 game_name='Conway',
                 num_players=4,
                 security_key=None):
     message = {"name": name, "game": game_name, "num_players": num_players}
     if security_key:
         message.update({"security_key": security_key})
     response = self.write_message('LOGIN', message)
     assert (response[0] == 0)
     return Player(response[1])
Пример #23
0
	def init(self):
		Logic.init(self)

		# Init state of the game...
		self.player = Player(50, 50, "@", self.msgBus)#, aiType=AIType.AIType_Zombie)
		self.addEntity(self.player)

		# Force camera to follow player entity
		msg = Message(sender=self, target=None, msgType=MsgType.eMsgType_CameraFollowEntity, data=self.player)
		self.msgBus.postMessage(msg)

		self.generateMap(100, 100)
Пример #24
0
def get_best_players_by_skill(skill: str, min_value: int = 15, verbose: bool = True):
    db = PlayerSimpleDbConnect()
    selected_players = db.get_best_players_by_skill(skill, min_value)
    i = 1
    result = []
    for p in selected_players:
        player = Player.convert_from_tuple(p)
        result.append(player)
        if verbose:
            print('%.2d. %s, %s, %s: %s' % (i, player.name, player.bpos, skill, player.__getattribute__(skill)))
        i += 1
    return result
Пример #25
0
    def test_Payment(self):

        handler = process()
        handler.request = Request({
            'REQUEST_METHOD': 'post',
            'PATH_INFO': '/process',
            })
        handler.response = Response()
        
        self.assertEqual(200, handler.response.status)
        test = Player.newPlayer(Player(key_name='*****@*****.**'),'*****@*****.**',10,10,10,40,20,0,0)
        test.put()
Пример #26
0
    def post(self):
     startingGem = 100
     startingMove = 5
     user = users.get_current_user()
     info = json.loads(self.request.body)


     #email,gem,move,fuel,cargo,food
     player = Player.newPlayer(Player(key_name=user.nickname()),user.nickname(),startingGem,startingMove,info ['fuel'],info ['cargo'],info ['food'],0,0)
     player.put()

     self.response.out.write("success");
Пример #27
0
def get_best_players_for_position(position: str,
                                  players_number: int = 5,
                                  verbose: bool = True):
    db = PlayerSimpleDbConnect()
    selected_players = db.get_best_players_by_position(position,
                                                       players_number)
    result = []
    for p in selected_players:
        player = Player.convert_from_tuple(p)
        result.append(player)
        if verbose:
            print('%s %s' % (player.name, player.bpos))
    return result
Пример #28
0
    def read_player(self):
        flag = self.read_signed_byte()

        if flag == 0:
            return None

        if flag == 127:
            return self.previous_player_by_id[self.read_long()]

        player = Player(self.read_long(), self.read_boolean(),
                        self.read_boolean(), self.read_int(), self.read_int())
        self.previous_player_by_id[player.id] = player
        return player
    def read_player(self):
        flag = self.read_signed_byte()

        if flag == 0:
            return None

        if flag == 100:
            return self.player_by_id[self.read_long()]

        player = Player(self.read_long(), self.read_boolean(),
                        self.read_string(), self.read_boolean(),
                        self.read_int(), self.read_enum(Faction))
        self.player_by_id[player.id] = player
        return player
Пример #30
0
    def test_testPage(self):

        handler = Page()
        form = ''
        handler.request = Request({
            'REQUEST_METHOD': 'get',
            'PATH_INFO': '/test',
            'wsgi.input': StringIO(form),
            'CONTENT_LENGTH': len(form),
            'SERVER_NAME': 'hi',
            'SERVER_PORT': '80',
            'wsgi.url_scheme': 'http',
        })
        handler.response = Response()
        handler.get()
        self.assertEqual(200, handler.response.status)

        entity = Player(email='*****@*****.**')
        key = entity.put()
        self.assertEqual('*****@*****.**', db.get(key).email)

        entity = Player(email='*****@*****.**')
        self.assertEqual('*****@*****.**', entity.email)
Пример #31
0
    def test_updateWorld(self):
        physics = Physics()
        location = PhysicsVector(5, 0, 50)
        velocity = PhysicsVector(0, 0, 0)
        player = Player(location, velocity)
        world = World(5)
        dt = 3

        world.objects.append(player)

        physics.updateWorld(player, world, dt)

        self.assertTrue(player.velocity.x == 0)
        self.assertTrue(player.velocity.y == 0)
        self.assertTrue(player.velocity.z == -15)
Пример #32
0
    def getAllPlayers(_):
        players = {}
        stats = NbaStats(
            requests.get(ALL_PLAYERS_PATH, headers=NBA_STATS_HEADERS).json())
        idColumnIndex = stats.getColumnIndex('PERSON_ID')
        nameColumnIndex = stats.getColumnIndex('DISPLAY_FIRST_LAST')
        teamCityColumnIndex = stats.getColumnIndex('TEAM_CITY')
        teamNameColumnIndex = stats.getColumnIndex('TEAM_NAME')

        for row in stats.getRows():
            playerName = row[nameColumnIndex]
            players[playerName] = Player(
                row[idColumnIndex], playerName,
                row[teamCityColumnIndex] + ' ' + row[teamNameColumnIndex])
        return players
Пример #33
0
    def read_player(self):
        flag = self.read_signed_byte()

        if flag == 0:
            return None

        if flag == 127:
            return self.previous_player_by_id[self.read_long()]

        player = RemoteProcessClient.PLAYER_STRUCT.unpack(self.read_bytes(50))

        player = Player(player[0], player[1] != 0, player[2] != 0, player[3],
                        player[4], player[5], player[6], player[7], player[8],
                        player[9])
        self.previous_player_by_id[player.id] = player
        return player
Пример #34
0
    def read_players(self):
        player_count = self.read_int()
        if player_count < 0:
            return None

        players = []

        for player_index in range(player_count):
            if self.read_boolean():
                player = Player(self.read_string(), self.read_int(),
                                self.read_boolean())
                players.append(player)
            else:
                players.append(None)

        return players
Пример #35
0
	def post(self):
		newStats = json.loads(self.request.body)
		
		#Retrieve player object
		player = Player.get_by_key_name(newStats["email"])
		#Modify player object
		player.spend += newStats["spend"]
		player.share += newStats["share"]
		if player.move > 0 or newStats["move"]>=0:
			player.food += newStats["food"]
			player.cargo += newStats["cargo"]
			player.fuel += newStats["fuel"]
			player.move += newStats["move"]
			player.gem += newStats["gem"]
			player.put()
		else:
			self.response.out.write("Insufficient moves")
Пример #36
0
    def read_player(self):
        flag = self.read_signed_byte()

        if flag == 0:
            return None

        if flag == 127:
            return self.previous_player_by_id[self.read_long()]

        byte_array = self.read_bytes(50)
        player = struct.unpack(
            RemoteProcessClient.BYTE_ORDER_FORMAT_STRING + "q2b3iqi2d",
            byte_array)

        player = Player(player[0], player[1] != 0, player[2] != 0, player[3],
                        player[4], player[5], player[6], player[7], player[8],
                        player[9])
        self.previous_player_by_id[player.id] = player
        return player
Пример #37
0
    def test_detectPlatformCollision(self):
        physics = Physics()

        platform_start = PhysicsVector(3, 0, 5)
        platform_end = PhysicsVector(6, 0, 5)

        platform = Platform(platform_start, platform_end, 0)

        dt = 3

        location = PhysicsVector(4, 0, 6)
        velocity = PhysicsVector(0, 0, -1)
        player = Player(location, velocity)
        potentialLocation = physics.computePotentialLocation(player, dt)

        actual = physics.detectPlatformCollision(player, potentialLocation,
                                                 platform)

        self.assertTrue(actual)
Пример #38
0
def get_player_with_potential(min_talent: float = 3.5,
                              min_teamwork: int = 10,
                              min_consistency: int = 10,
                              max_age: int = None,
                              verbose: bool = True):
    db = PlayerSimpleDbConnect()
    players = db.get_players_with_potential(min_talent, min_teamwork,
                                            min_consistency, max_age)
    if verbose:
        print('players with potential: %d' % len(players))
    result = []
    for p in players:
        player = Player.convert_from_tuple(p)
        result.append(player)
        if verbose:
            print(
                '%s (%s)\n\ttalent: %.1f\n\tteamwork: %d\n\tconsistency: %d' %
                (player.name, player.bpos, player.talent, player.teamwork,
                 player.consistency))
    return result
Пример #39
0
 def _get_players(self, details):
     """
     Get all of the player names, heroes, IDs, team affiliation, and win/loss.
     """
     parsed_players = []
     players = details['m_playerList']
     for player in players:
         name = player['m_name']
         hero = player['m_hero']
         team_id = player['m_teamId']
         working_slot_id = player['m_workingSetSlotId']
         result = player['m_result']
         parsed_player = Player(
             name=name,
             hero=hero,
             team=team_id,
             id=working_slot_id,
             winner=(result == 1),
         )
         parsed_players.append(parsed_player)
     return parsed_players
Пример #40
0
 def load(node):
     answer = Team();
     data = ModelObject.extractData(node)
     value = data.get('name', None)
     if value != None:
         answer.name = value[0].text
     value = data.get('id', None)
     if value != None:
         answer.id = value
     value = data.get('player', None)
     if value != None:
         for child in value:
             player = Player.load(child)
             answer.players[player.id] = player
     value = data.get("pointsDeduction")
     if value != None:
         for child in value:
             points = int(child.find("points").text)
             reason = child.find("reason").text
             answer.deductions.append([points, reason])
     return answer
Пример #41
0
 def get(self):
     try:
         p = Player.newPlayer(Player(key_name='lol'),'*****@*****.**',500,500,500,500,0,0)
         p.put()
     except:
         self.response.out.write('failed')
Пример #42
0
 def test_new_player(self):
     test = Player.newPlayer(Player(key_name='*****@*****.**'),'*****@*****.**',10,10,10,40,20,0,0)
     test.put()
Пример #43
0
 def test_new_player(self):
     test = Player()
     deyang = Player.newPlayer(Player(key_name='*****@*****.**'),'*****@*****.**',10,10,10,40,20,0,0)
Пример #44
0
 def test_saved_entity(self):
     entity = Player(email='*****@*****.**')
     key = entity.put()
     self.assertEqual('*****@*****.**', db.get(key).email)
Пример #45
0
 def setUp(self):
     # Populate test entities.
     entity = Player(email='*****@*****.**')
     self.setup_key = entity.put()