Exemplo n.º 1
0
def act_createGame(data):
	user = dbi.getXbyY('User', 'sid', data['sid'])
	if user.gameId: raise BadFieldException('alreadyInGame')
	map_ = dbi.getXbyY('Map', 'id', data['mapId'])
	descr = None
	if 'gameDescription' in data:
		descr = data['gameDescription']
	randseed = math.trunc(time.time())
	if 'randseed' in data:
		randseed = data['randseed']
	ai = data['ai'] if 'ai' in data else 0
	if ai > map_.playersNum:
		raise BadFieldException('tooManyPlayersForMap')
	newGame = Game(data['gameName'], descr, map_, randseed, data['ai'] if 'ai' in\
		data else None)
	dbi.addUnique(newGame, 'gameName')
	initRegions(map_, newGame)
	
	if ai < map_.playersNum:
		user.game = newGame
		user.priority = 1
		user.inGame = True
		dbi.flush(user)
		if not misc.TEST_MODE:
			data['randseed'] = randseed
		dbi.updateGameHistory(user.game, data)
		
	return {'result': 'ok', 'gameId': newGame.id}
Exemplo n.º 2
0
def act_createGame(data):
    user = dbi.getXbyY('User', 'sid', data['sid'])
    if user.gameId: raise BadFieldException('alreadyInGame')
    map_ = dbi.getXbyY('Map', 'id', data['mapId'])
    descr = None
    if 'gameDescription' in data:
        descr = data['gameDescription']
    randseed = math.trunc(time.time())
    if 'randseed' in data:
        randseed = data['randseed']
    ai = data['ai'] if 'ai' in data else 0
    if ai > map_.playersNum:
        raise BadFieldException('tooManyPlayersForMap')
    newGame = Game(data['gameName'], descr, map_, randseed, data['ai'] if 'ai' in\
     data else None)
    dbi.addUnique(newGame, 'gameName')
    initRegions(map_, newGame)

    if ai < map_.playersNum:
        user.game = newGame
        user.priority = 1
        user.inGame = True
        dbi.flush(user)
        if not misc.TEST_MODE:
            data['randseed'] = randseed
        dbi.updateGameHistory(user.game, data)

    return {'result': 'ok', 'gameId': newGame.id}
Exemplo n.º 3
0
def act_aiJoin(data):
    game = dbi.getXbyY('Game', 'id', data['gameId'])
    if game.state != GAME_WAITING:
        raise BadFieldException('badGameState')
    maxPlayersNum = game.map.playersNum
    if len(game.players) >= maxPlayersNum:
        raise BadFieldException('tooManyPlayers')
    maxPriority = max(game.players, key=lambda x: x.priority).priority if len(
        game.players) else 0
    aiCnt = len(filter(lambda x: x.isAI == True, game.players))
    sid = getSid()
    ai = User('AI%d' % sid, None, True)
    ai.sid = sid
    ai.gameId = game.id
    ai.isReady = True
    ai.priority = maxPriority + 1
    ai.inGame = True
    dbi.add(ai)
    dbi.flush(ai)
    game.aiRequiredNum -= 1
    readyPlayersNum = dbi.query(User).filter(User.gameId == game.id).filter(
        User.isReady == True).count()
    if maxPlayersNum == readyPlayersNum:
        misc_game.startGame(game, ai, data)
    return {'result': 'ok', 'sid': ai.sid, 'id': ai.id}
Exemplo n.º 4
0
def act_selectRace(data):
	user = dbi.getXbyY('User', 'sid', data['sid'])
	if user.currentTokenBadge:
		raise BadFieldException('badStage')
	game = user.game
	if not (game and user.inGame): 
		raise BadFieldException('notInGame')
	checkStage(GAME_SELECT_RACE, user)
	if (user.game.state == misc.GAME_START):
                user.game.state = misc.GAME_PROCESSING
	chosenBadge = game.getTokenBadge(data['position'])
	position = chosenBadge.pos
	tokenBadges = dbi.query(TokenBadge).order_by(TokenBadge.pos).all()
	tokenBadges = tokenBadges[:6]
	price = position
	if user.coins < price : 
		raise BadFieldException('badMoneyAmount')
	raceId, specialPowerId = chosenBadge.raceId, chosenBadge.specPowId
	addUnits = callRaceMethod(raceId, 'turnStartReinforcements')
	tokensNum = races.racesList[raceId].initialNum + races.specialPowerList[specialPowerId].tokensNum					
	user.coins += chosenBadge.bonusMoney - price
	user.currentTokenBadge = chosenBadge
	user.tokensInHand = tokensNum + addUnits
	chosenBadge.inDecline = False
	chosenBadge.bonusMoney = 0
	chosenBadge.totalTokensNum = tokensNum + addUnits
	chosenBadge.specPowNum = races.specialPowerList[specialPowerId].bonusNum
	chosenBadge.pos = None
	dbi.flush(chosenBadge)
	updateRacesOnDesk(game, position)
	dbi.updateHistory(user, GAME_SELECT_RACE, chosenBadge.id)
	dbi.updateGameHistory(game, data)
	return {'result': 'ok', 'tokenBadgeId': chosenBadge.id}
Exemplo n.º 5
0
def act_selectRace(data):
    user = dbi.getXbyY('User', 'sid', data['sid'])
    if user.currentTokenBadge:
        raise BadFieldException('badStage')
    game = user.game
    if not (game and user.inGame):
        raise BadFieldException('notInGame')
    checkStage(GAME_SELECT_RACE, user)
    if (user.game.state == misc.GAME_START):
        user.game.state = misc.GAME_PROCESSING
    chosenBadge = game.getTokenBadge(data['position'])
    position = chosenBadge.pos
    tokenBadges = dbi.query(TokenBadge).order_by(TokenBadge.pos).all()
    tokenBadges = tokenBadges[:6]
    price = position
    if user.coins < price:
        raise BadFieldException('badMoneyAmount')
    raceId, specialPowerId = chosenBadge.raceId, chosenBadge.specPowId
    addUnits = callRaceMethod(raceId, 'turnStartReinforcements')
    tokensNum = races.racesList[raceId].initialNum + races.specialPowerList[
        specialPowerId].tokensNum
    user.coins += chosenBadge.bonusMoney - price
    user.currentTokenBadge = chosenBadge
    user.tokensInHand = tokensNum + addUnits
    chosenBadge.inDecline = False
    chosenBadge.bonusMoney = 0
    chosenBadge.totalTokensNum = tokensNum + addUnits
    chosenBadge.specPowNum = races.specialPowerList[specialPowerId].bonusNum
    chosenBadge.pos = None
    dbi.flush(chosenBadge)
    updateRacesOnDesk(game, position)
    dbi.updateHistory(user, GAME_SELECT_RACE, chosenBadge.id)
    dbi.updateGameHistory(game, data)
    return {'result': 'ok', 'tokenBadgeId': chosenBadge.id}
Exemplo n.º 6
0
	def throwDice(self, game, dice = None):
                if misc.TEST_MODE: 
                        return dice if dice is not None else 0
                game.prevGeneratedNum = (misc.A * game.prevGeneratedNum) % misc.M
                dbi.flush(game)
                dice = game.prevGeneratedNum % 6
                if dice > 2: dice = 0
                return dice
Exemplo n.º 7
0
 def throwDice(self, game, dice=None):
     if misc.TEST_MODE:
         return dice if dice is not None else 0
     game.prevGeneratedNum = (misc.A * game.prevGeneratedNum) % misc.M
     dbi.flush(game)
     dice = game.prevGeneratedNum % 6
     if dice > 2:
         dice = 0
     return dice
Exemplo n.º 8
0
def endOfGame(game, coins = None): 
	game.state = GAME_ENDED
	if misc_const.TEST_MODE:
		return {'result': 'ok', 'coins': coins}
	else:
		gameState = getGameState(game)
		game.resetPlayersState()
		dbi.delete(game)
		dbi.flush(game)
		return {'result': 'ok', 'gameState': gameState}
Exemplo n.º 9
0
def endOfGame(game, coins=None):
    game.state = GAME_ENDED
    if misc.TEST_MODE:
        return {"result": "ok", "coins": coins}
    else:
        gameState = getGameState(game)
        game.resetPlayersState()
        dbi.delete(game)
        dbi.flush(game)
        return {"result": "ok", "gameState": gameState}
Exemplo n.º 10
0
def endOfGame(game, coins=None):
    game.state = GAME_ENDED
    if misc.TEST_MODE:
        return {'result': 'ok', 'coins': coins}
    else:
        gameState = getGameState(game)
        game.resetPlayersState()
        dbi.delete(game)
        dbi.flush(game)
        return {'result': 'ok', 'gameState': gameState}
Exemplo n.º 11
0
def showNextRace(game, lastIndex, vRace = None, vSpecialPower = None):
	raceId, specPowerId = getNextRaceAndPowerFromStack(game, vRace, vSpecialPower)
	tokenBadges = dbi.query(TokenBadge).filter(TokenBadge.gameId == game.id).all()
	tokenBadgesInStack = filter(lambda x: not x.Owner() and not x.inDecline and x.pos > lastIndex, tokenBadges) 
	for tokenBadge in tokenBadgesInStack: 
		tokenBadge.pos -= 1
		dbi.flush(tokenBadge)
	tokBadge = TokenBadge(raceId, specPowerId, game.id)
	dbi.add(tokBadge)
	dbi.flush(tokBadge)
	return races.racesList[raceId].name, races.specialPowerList[specPowerId].name, 
Exemplo n.º 12
0
def updateRacesOnDesk(game, position):
	for tokenBadge in filter(lambda x: x.pos < position, game.tokenBadges):
		tokenBadge.bonusMoney += 1
	if len(filter(lambda x: x.pos is not None, game.tokenBadges)) < 6:
		showNextRace(game, position)
	else:
		tokenBadges = dbi.query(TokenBadge).filter(TokenBadge.gameId == game.id).all()
		tokenBadgesInStack = filter(lambda x: not x.Owner() and not x.inDecline and x.pos > position, tokenBadges) 
		for tokenBadge in tokenBadgesInStack: 
			tokenBadge.pos -= 1
			dbi.flush(tokenBadge)
Exemplo n.º 13
0
def updateRacesOnDesk(game, position):
    for tokenBadge in filter(lambda x: x.pos < position, game.tokenBadges):
        tokenBadge.bonusMoney += 1
    if len(filter(lambda x: x.pos is not None, game.tokenBadges)) < 6:
        return showNextRace(game, position)
    else:
        tokenBadges = dbi.query(TokenBadge).filter(
            TokenBadge.gameId == game.id).all()
        tokenBadgesInStack = filter(
            lambda x: not x.Owner() and not x.inDecline and x.pos > position,
            tokenBadges)
        for tokenBadge in tokenBadgesInStack:
            tokenBadge.pos -= 1
            dbi.flush(tokenBadge)
Exemplo n.º 14
0
def startGame(game, user, data):
    game.activePlayerId = min(game.players, key=lambda x: x.priority).id
    game.state = misc.GAME_START
    dbi.flush(game)
    #generate first 6 races
    if misc.TEST_MODE and 'visibleRaces' in data and 'visibleSpecialPowers' in data:
        vRaces = data['visibleRaces']
        vSpecialPowers = data['visibleSpecialPowers']
        for i in range(min(len(vRaces), len(vSpecialPowers))):
            showNextRace(game, 0, vRaces[i], vSpecialPowers[i])
    else:
        for i in range(misc.VISIBLE_RACES):
            showNextRace(game, 0)

    dbi.updateHistory(user, misc.GAME_START, None)
Exemplo n.º 15
0
def startGame(game, user, data):
	game.activePlayerId = min(game.players, key=lambda x: x.priority).id
	game.state = misc_const.GAME_START
	dbi.flush(game)
	#generate first 6 races
	if misc_const.TEST_MODE and 'visibleRaces' in data and 'visibleSpecialPowers' in data:
		vRaces = data['visibleRaces']
		vSpecialPowers = data['visibleSpecialPowers']
		for i in range(min(len(vRaces), len(vSpecialPowers))):
			showNextRace(game, 0, vRaces[i], vSpecialPowers[i])
	else:
		for i in range(misc_const.VISIBLE_RACES):
			showNextRace(game, 0)
			
	dbi.updateHistory(user, misc_const.GAME_START, None)
Exemplo n.º 16
0
def showNextRace(game, lastIndex, vRace=None, vSpecialPower=None):
    raceId, specPowerId = getNextRaceAndPowerFromStack(game, vRace,
                                                       vSpecialPower)
    tokenBadges = dbi.query(TokenBadge).filter(
        TokenBadge.gameId == game.id).all()
    tokenBadgesInStack = filter(
        lambda x: not x.Owner() and not x.inDecline and x.pos > lastIndex,
        tokenBadges)
    for tokenBadge in tokenBadgesInStack:
        tokenBadge.pos -= 1
        dbi.flush(tokenBadge)
    tokBadge = TokenBadge(raceId, specPowerId, game.id)
    dbi.add(tokBadge)
    dbi.flush(tokBadge)
    return races.racesList[raceId].name, races.specialPowerList[
        specPowerId].name,
Exemplo n.º 17
0
def act_setReadinessStatus(data):
	user = dbi.getXbyY('User', 'sid', data['sid'])
	game = user.game
	if not (game and user.inGame): 
		raise BadFieldException('notInGame')

	
	if game.state != GAME_WAITING:
		raise BadFieldException('badGameState')

	user.isReady = data['isReady']
	dbi.flush(user)
	maxPlayersNum = game.map.playersNum
	readyPlayersNum = dbi.query(User).filter(User.game==game).filter(User.isReady==True).count()
	if maxPlayersNum == readyPlayersNum:
		misc_game.startGame(game, user, data)
	dbi.updateGameHistory(user.game, data)
	return {'result': 'ok'}
Exemplo n.º 18
0
def act_setReadinessStatus(data):
    user = dbi.getXbyY('User', 'sid', data['sid'])
    game = user.game
    if not (game and user.inGame):
        raise BadFieldException('notInGame')

    if game.state != GAME_WAITING:
        raise BadFieldException('badGameState')

    user.isReady = data['isReady']
    dbi.flush(user)
    maxPlayersNum = game.map.playersNum
    readyPlayersNum = dbi.query(User).filter(User.game == game).filter(
        User.isReady == True).count()
    if maxPlayersNum == readyPlayersNum:
        misc_game.startGame(game, user, data)
    dbi.updateGameHistory(user.game, data)
    return {'result': 'ok'}
Exemplo n.º 19
0
def act_aiJoin(data):
	game = dbi.getXbyY('Game', 'id', data['gameId'])
	if game.state != GAME_WAITING:
		raise BadFieldException('badGameState')
	maxPlayersNum = game.map.playersNum
	if len(game.players) >= maxPlayersNum:
		raise BadFieldException('tooManyPlayers')
	maxPriority = max(game.players, key=lambda x: x.priority).priority if len(game.players) else 0
	aiCnt = len(filter(lambda x: x.isAI == True, game.players))
	sid = getSid()
	ai = User('AI%d' % sid, None, True)
	ai.sid = sid
	ai.gameId = game.id
	ai.isReady = True
	ai.priority = maxPriority + 1
	ai.inGame = True
	dbi.add(ai)
	dbi.flush(ai)
	game.aiRequiredNum -= 1
	readyPlayersNum = dbi.query(User).filter(User.gameId == game.id).filter(User.isReady==True).count()
	if maxPlayersNum == readyPlayersNum:
		misc_game.startGame(game, ai, data)
	return {'result': 'ok', 'sid' : ai.sid, 'id' : ai.id}
Exemplo n.º 20
0
def doAction(data, force = True):
	try:
		if force:
			dbi.session = dbi.Session()
		func = 'act_%s' % data['action'] 
		if not(func in globals()):
			raise BadFieldException('badAction')
		if force: checkFieldsCorrectness(data)
		res = globals()[func](data)
		dbi.commit() if force else dbi.flush()
		return res
	except BadFieldException, e: 
		print e
		dbi.rollback()
		return {'result': e.value}
Exemplo n.º 21
0
def generateNextNum(game):
    game.prevGeneratedNum = (misc.A * game.prevGeneratedNum) % misc.M
    dbi.flush(game)
    return game.prevGeneratedNum
Exemplo n.º 22
0
def generateNextNum(game):
	game.prevGeneratedNum = (misc_const.A * game.prevGeneratedNum) % misc_const.M
	dbi.flush(game)
	return game.prevGeneratedNum
Exemplo n.º 23
0
def act_conquer(data):
	user = dbi.getXbyY('User', 'sid', data['sid'])
	print user.currentTokenBadge
	game = user.game
	if not (game and user.inGame): 
		raise BadFieldException('notInGame')
	if not user.currentTokenBadge or  not user.tokensInHand:
		raise BadFieldException('badStage') 
	checkStage(GAME_CONQUER, user)
	region = game.map.getRegion(data['regionId'])
	regState = region.getState(game.id)
	victimTokenBadge = regState.tokenBadge
	owner = regState.owner
	if owner == user and not regState.inDecline: 
		raise BadFieldException('badRegion')
	tokenBadge = user.currentTokenBadge
	raceId, specialPowerId = tokenBadge.raceId, tokenBadge.specPowId
	if not regState.inDecline:
		user.checkForFriends(owner)
	f1 = callRaceMethod(raceId, 'canConquer', region, tokenBadge)
	f2 = callSpecialPowerMethod(specialPowerId, 'canConquer',  region,  tokenBadge)
	if not (f1 and f2):
		raise BadFieldException('badRegion')
	regState.checkIfImmune()
	attackedRace = None
	attackedSpecialPower = None
	if regState.tokenBadge:
		attackedRace = regState.tokenBadge.raceId
		attackedSpecialPower = regState.tokenBadge.specPowId
	enemyDefenseBonus = 0
	if attackedRace:
		enemyDefenseBonus = callRaceMethod(attackedRace, 'defenseBonus')
	defense = regState.tokensNum
	unitPrice = max(misc_const.BASIC_CONQUER_COST + defense + region.mountain + 
		regState.encampment + regState.fortified +  enemyDefenseBonus +
		callRaceMethod(raceId, 'attackBonus', region, tokenBadge) + 
		callSpecialPowerMethod(specialPowerId, 'attackBonus', region, tokenBadge)
			, 1)
	unitsNum = user.tokensInHand
	if unitsNum + 3 < unitPrice:
		raise BadFieldException('badTokensNum') 
	t = user.game.getLastState() == misc_const.GAME_THROW_DICE
	dice = t and user.game.history[-1].dice
	if not dice and unitsNum < unitPrice : 
		dice = misc_game.throwDice(game)
	unitPrice -= (dice or 0)
	unitPrice = max(unitPrice, 1)
	if unitsNum < unitPrice:
		dbi.updateHistory(user, GAME_UNSUCCESSFULL_CONQUER, user.currentTokenBadge.id)
		return {'result': 'badTokensNum', 'dice': dice}
	clearFromRace(regState)					# Not sure if it's necessary
	victimBadgeId = regState.tokenBadgeId
	regState.owner = user
	regState.tokenBadge = user.currentTokenBadge
	regState.inDecline = False
	regState.tokensNum = unitPrice
	if victimTokenBadge:
		callRaceMethod(victimTokenBadge.raceId, 'sufferCasualties', victimTokenBadge)
		owner.tokensInHand += defense - callRaceMethod(victimTokenBadge.raceId, 'getCasualties')
	callRaceMethod(raceId, 'conquered', regState, tokenBadge)
	dbi.updateWarHistory(user, victimBadgeId, tokenBadge.id, dice, 
		region.id, defense, ATTACK_CONQUER)
	user.tokensInHand -= unitPrice
	dbi.updateGameHistory(game, data)
	dbi.flush(user)
	dbi.flush(regState)
	return {'result': 'ok', 'dice': dice} if (dice and not t) else {'result': 'ok'}