Example #1
0
    def _fight_round(self, fighter_opponent, print_resource):
        # TODO: enhance critical success effects and failure

        at_test_result = GameUtil.pass_test(self.at)
        print_resource.ADD_TEXT = "Résultat jet attaque {}".format(at_test_result)
        self.attack_this_turn += 1

        if GameResources.CRITIC_SUCCESS in at_test_result:
            fighter_opponent.take_damage(self.pi, additional_bonus=self.pi_min)  # no parry
        elif GameResources.CRITIC_FAILURE in at_test_result:
            self.attack_this_turn += self.max_attack_per_turn # we lose one round...
            self.pary_this_turn += self.max_pary_per_turn # we lose one round...
        elif GameResources.SUCCESS in at_test_result:
            # Success for attack, try to pary
            if fighter_opponent.pary_this_turn < fighter_opponent.max_pary_per_turn:
                prd_test_result = GameUtil.pass_test(fighter_opponent.prd)
                print_resource.ADD_TEXT = "Résultat jet parade {}".format(prd_test_result)
                fighter_opponent.pary_this_turn += 1
                if GameResources.CRITIC_SUCCESS in prd_test_result:
                    self.attack_this_turn += self.max_attack_per_turn # we lose one round...
                    self.pary_this_turn += self.max_pary_per_turn # we lose one round...
                elif GameResources.CRITIC_FAILURE in prd_test_result:
                    fighter_opponent.attack_this_turn += fighter_opponent.max_attack_per_turn # opponent loses one round...
                    fighter_opponent.pary_this_turn += fighter_opponent.max_pary_per_turn # opponent loses one round...
                elif GameResources.FAILURE in prd_test_result:
                    # Opponent did not manage to parry
                    fighter_opponent.take_damage(self.pi, additional_bonus=self.pi_min)

            else:
                print_resource.ADD_TEXT = "{} ne peut plus parer à ce tour.".format(fighter_opponent.object.name)
Example #2
0
def canSeeCityList(playerOrID):
    """
    Returns True if the active player can see the list of <player>'s cities.
    
    In the unmodified game, this is possible if the players have met and <player>
    is not a vassal of a rival. They must be able to contact (trade with)
    <player>, and OCC must be disabled. You can always see a teammate's cities.
    """
    if GameUtil.isOCC():
        return False
    askedPlayer, askedTeam = getPlayerAndTeam(playerOrID)
    askingPlayer, askingTeam = getActivePlayerAndTeam()

    iDemographicsMission = -1

    if (GameUtil.isEspionage()):
        for iMissionLoop in range(gc.getNumEspionageMissionInfos()):
            if (gc.getEspionageMissionInfo(iMissionLoop).isSeeDemographics()):
                iDemographicsMission = iMissionLoop

    if gc.getGame().isOption(
            GameOptionTypes.GAMEOPTION_CITYCOUNT_TIED_TO_ESPIONAGE):
        if (askedTeam.isEverAlive()):
            if (askingTeam.isHasMet(playerOrID) or CyGame().isDebugMode()):
                if (iDemographicsMission != -1
                        and not askingPlayer.canDoEspionageMission(
                            iDemographicsMission, playerOrID, None, -1)):
                    return False

    if askingPlayer.getTeam() == askedPlayer.getTeam():
        return True
    if askedTeam.isAVassal() and not askedTeam.isVassal(askingTeam.getID()):
        return False
    return TradeUtil.canTrade(askingPlayer, askedPlayer)
Example #3
0
	def testItem(self):
		p = Rock()
		GameUtil.save()
		self.cur.execute("SELECT COUNT(*) FROM item")
		row = self.cur.fetchone()
		self.assert_(row is not None)
		self.assertEqual(row[0], 1)
Example #4
0
	def testPlayer(self):
		p = Player("test player", Alignment.WOOD)
		GameUtil.save()
		self.cur.execute("SELECT COUNT(*) FROM actor WHERE name = %(name)s",
						 { 'name': "test player" })
		row = self.cur.fetchone()
		self.assert_(row is not None)
		self.assertEqual(row[0], 1)
Example #5
0
 def testAddAggregate(self):
     self.p1.inventory.add(self.gp3)
     GameUtil.save()
     self.cur.execute(
         "SELECT COUNT(*) FROM item_owner" + " WHERE item_id = %(iid)s",
         {'iid': self.gp3._id})
     row = self.cur.fetchone()
     self.assert_(row is not None)
     self.assertEqual(row[0], 1)
Example #6
0
	def testLocation(self):
		p = Location(Position(5, -3, "test"))
		GameUtil.save()
		self.cur.execute("SELECT COUNT(*) FROM location "
						 + " WHERE x = %(x)s AND y = %(y)s AND layer = %(layer)s",
						 { 'x': 5, 'y': -3, 'layer': 'test' })
		row = self.cur.fetchone()
		self.assert_(row is not None)
		self.assertEqual(row[0], 1)
Example #7
0
 def setUp(self):
     GameUtil.flush_cache()
     self.cur = DB.cursor()
     self.cur.execute("DELETE FROM account")
     self.cur.execute("DELETE FROM account_actor")
     self.cur.execute("DELETE FROM actor")
     self.cur.execute("DELETE FROM actor_message")
     self.cur.execute("DELETE FROM actor_properties")
     self.cur.execute("DELETE FROM item")
     self.cur.execute("DELETE FROM item_owner")
     self.cur.execute("DELETE FROM item_properties")
     self.cur.execute("DELETE FROM location")
     self.cur.execute("DELETE FROM location_properties")
     self.cur.execute("DELETE FROM log_raw_action")
     DB.commit()
Example #8
0
def getTechTradePartners(playerOrID):
    """
    Returns a list of CyPlayers that can trade technologies with <player>.
    """
    if not GameUtil.isTechTrading():
        return ()
    return getTradePartnersByTeam(playerOrID, lambda fromTeam, toTeam: fromTeam.isTechTrading() or toTeam.isTechTrading())
Example #9
0
 def test_game_util_is_winner(self):
     """GameUtil.is_winner() should give expected results for mentioned cases"""
     for given_playground, expected_result in self.expected_values_is_winner:
         test_game = GameUtil.GameUtil()
         test_game.get_playground().fields = given_playground
         result = test_game.is_winner()
         self.assertEqual(expected_result, result)
def getTechTradePartners(playerOrID):
	"""
	Returns a list of CyPlayers that can trade technologies with <player>.
	"""
	if not GameUtil.isTechTrading():
		return ()
	return getTradePartnersByTeam(playerOrID, lambda fromTeam, toTeam: fromTeam.isTechTrading() or toTeam.isTechTrading())
def canContact(playerOrID, toPlayerOrID):
    """
	Returns True if <player> can attempt to contact <toPlayer> given game settings, 
	initial contact, and war-time situation without regard to willingness to talk.
	
	- They must not be the same player
	- <toPlayer> must be alive, not minor, and not a barbarian
	- Their teams must have met
	- If they are at war, they must be able to sign a peace deal (no Always War or Permanent War/Peace options)
	"""
    playerID, player = PlayerUtil.getPlayerAndID(playerOrID)
    toPlayerID, toPlayer = PlayerUtil.getPlayerAndID(toPlayerOrID)
    if playerID == toPlayerID:
        return False
    if not toPlayer.isAlive() or toPlayer.isBarbarian() or toPlayer.isMinorCiv():
        return False
    if not PlayerUtil.getPlayerTeam(player).isHasMet(toPlayer.getTeam()):
        return False
    if PlayerUtil.getPlayerTeam(player).isAtWar(toPlayer.getTeam()) and (
        GameUtil.isAlwaysWar() or GameUtil.isPermanentWarPeace()
    ):
        return False
    return True
Example #12
0
def canContact(playerOrID, toPlayerOrID):
    """
	Returns True if <player> can attempt to contact <toPlayer> given game settings, 
	initial contact, and war-time situation without regard to willingness to talk.
	
	- They must not be the same player
	- <toPlayer> must be alive, not minor, and not a barbarian
	- Their teams must have met
	- If they are at war, they must be able to sign a peace deal (no Always War or Permanent War/Peace options)
	"""
    playerID, player = PlayerUtil.getPlayerAndID(playerOrID)
    toPlayerID, toPlayer = PlayerUtil.getPlayerAndID(toPlayerOrID)
    if playerID == toPlayerID:
        return False
    if not toPlayer.isAlive() or toPlayer.isBarbarian() or toPlayer.isMinorCiv(
    ):
        return False
    if not PlayerUtil.getPlayerTeam(player).isHasMet(toPlayer.getTeam()):
        return False
    if PlayerUtil.getPlayerTeam(player).isAtWar(
            toPlayer.getTeam()) and (GameUtil.isAlwaysWar()
                                     or GameUtil.isPermanentWarPeace()):
        return False
    return True
Example #13
0
def canSeeCityList(playerOrID):
	"""
	Returns True if the active player can see the list of <player>'s cities.
	
	In the unmodified game, this is possible if the players have met and <player>
	is not a vassal of a rival. They must be able to contact (trade with)
	<player>, and OCC must be disabled. You can always see a teammate's cities.
	"""
	if GameUtil.isOCC():
		return False
	askedPlayer, askedTeam = getPlayerAndTeam(playerOrID)
	askingPlayer, askingTeam = getActivePlayerAndTeam()
	if askingPlayer.getTeam() == askedPlayer.getTeam():
		return True
	if askedTeam.isAVassal() and not askedTeam.isVassal(askingTeam.getID()):
		return False
	return TradeUtil.canTrade(askingPlayer, askedPlayer)
Example #14
0
def canSeeCityList(playerOrID):
	"""
	Returns True if the active player can see the list of <player>'s cities.
	
	In the unmodified game, this is possible if the players have met and <player>
	is not a vassal of a rival. They must be able to contact (trade with)
	<player>, and OCC must be disabled. You can always see a teammate's cities.
	"""
	if GameUtil.isOCC():
		return False
	askedPlayer, askedTeam = getPlayerAndTeam(playerOrID)
	askingPlayer, askingTeam = getActivePlayerAndTeam()
	if askingPlayer.getTeam() == askedPlayer.getTeam():
		return True
	if askedTeam.isAVassal() and not askedTeam.isVassal(askingTeam.getID()):
		return False
	return TradeUtil.canTrade(askingPlayer, askedPlayer)
Example #15
0
def canSeeCityList(playerOrID):
    """
	Returns True if the active player can see the list of <player>'s cities.
	
	In the unmodified game, this is possible if the players have met and <player>
	is not a vassal of a rival. They must be able to contact (trade with)
	<player>, and OCC must be disabled. You can always see a teammate's cities.
	"""
    # In K-Mod, the city list is only visible when at war. - Also, human players will only show their city list if they are willing to talk!
    # Rather than risk getting this wrong..
    return False
    # done. (old code follows, but does nothing.)
    if GameUtil.isOCC():
        return False
    askedPlayer, askedTeam = getPlayerAndTeam(playerOrID)
    askingPlayer, askingTeam = getActivePlayerAndTeam()
    if askingPlayer.getTeam() == askedPlayer.getTeam():
        return True
    if askedTeam.isAVassal() and not askedTeam.isVassal(askingTeam.getID()):
        return False
    return TradeUtil.canTrade(askingPlayer, askedPlayer)
Example #16
0
def api_handler(req):
    ret_value = api_handler_core(req)
    GameUtil.flush_cache()
    return ret_value
Example #17
0
def actor_handler(req, player, target, components):
    """Handle a request for actor information, for the given target ID"""
    # We must have precisely one component in the request URL
    if len(components) != 1:
        return apache.HTTP_NOT_FOUND

    req.content_type = "text/plain"
    actor = Actor.load(target)
    context = player.get_context()

    # Check for actions first -- simplifies the handling of action POSTs
    if components[0] == 'actions':
        if req.method == 'GET':
            # List of actions
            acts = actor.get_actions()
            for id, act in acts.iteritems():
                info = act.context_get(context)
                Util.render_info(info, req)
                req.write("-\n")

        elif req.method == 'POST':
            data = Util.parse_input(req)
            if 'action' in data:
                actor.perform_action(data['action'], data)

            # Save any game state that might have changed
            GameUtil.save()
        else:
            # If it's not GET or POST, complain
            return apache.HTTP_METHOD_NOT_ALLOWED

        return apache.OK

    # Now handle everything else: it's all GETs from here on
    if req.method != 'GET':
        # If it's not a GET, throw a wobbly
        return apache.HTTP_METHOD_NOT_ALLOWED

    log.debug("Actor handler: requested " + str(components))
    if components[0] == 'desc':
        # Description
        info = actor.context_get(context)
        Util.render_info(info, req)
    elif components[0] == 'inventory':
        # Inventory
        info = actor.inventory.context_get_equip(context)
        Util.render_table(info, req)
    elif components[0] == 'equipment':
        # Equipment
        info = actor.equipment.context_get_equip(context)
        Util.render_table(info, req)
    elif components[0] == 'log':
        # Actor logs
        if 'X-WoR-Messages-Since' in req.headers_in:
            since = req.headers_in['X-WoR-Messages-Since']
        else:
            since = getattr(actor, 'last_action', 0)

        info = actor.get_messages(since)
        Util.render_table(info, req)
    else:
        return apache.HTTP_NOT_FOUND

    return apache.OK
Example #18
0
def canTriggerTheVedicAryans(argsList):

    kTriggeredData = argsList[0]
    player = gc.getPlayer(kTriggeredData.ePlayer)

    #   If Barbarians are disabled in this game, this event will not occur.
    if gc.getGame().isOption(GameOptionTypes.GAMEOPTION_NO_BARBARIANS):
        return false

#   At least one civ on the board must know Polytheism.
    bFoundValid = false

    # BUFFY 3.19.003 - start
    # changes one of the key techs to Priesthood instead of Polytheism
    if isEnabled():
        iTech = gc.getInfoTypeForString('TECH_PRIESTHOOD')
    else:
        iTech = gc.getInfoTypeForString('TECH_POLYTHEISM')
# BUFFY 3.19.003 - end

    for iPlayer in range(gc.getMAX_CIV_PLAYERS()):
        loopPlayer = gc.getPlayer(iPlayer)
        if loopPlayer.isAlive():
            if gc.getTeam(loopPlayer.getTeam()).isHasTech(iTech):
                bFoundValid = true
                break

    if not bFoundValid:
        return false

#   At least one civ on the board must know Archery.
    bFoundValid = false
    iTech = gc.getInfoTypeForString('TECH_ARCHERY')
    for iPlayer in range(gc.getMAX_CIV_PLAYERS()):
        loopPlayer = gc.getPlayer(iPlayer)
        if loopPlayer.isAlive():
            if gc.getTeam(loopPlayer.getTeam()).isHasTech(iTech):
                bFoundValid = true
                break

    if not bFoundValid:
        return false

# BUG - 3.17 - Start
    if (GameUtil.isVersion(317)):
        # rest indented but unchanged
        # Can we build the counter unit?
        iCounterUnitClass = gc.getInfoTypeForString('UNITCLASS_ARCHER')
        iCounterUnit = gc.getCivilizationInfo(
            player.getCivilizationType()).getCivilizationUnits(
                iCounterUnitClass)
        if iCounterUnit == -1:
            return false

        (loopCity, iter) = player.firstCity(false)
        bFound = false
        while (loopCity):
            if (loopCity.canTrain(iCounterUnit, false, false)):
                bFound = true
                break

            (loopCity, iter) = player.nextCity(iter, false)

        if not bFound:
            return false
# BUG - 3.17 - End

#	Find an eligible plot
    map = gc.getMap()
    for i in range(map.numPlots()):
        plot = map.plotByIndex(i)
        if (plot.getOwner() == -1 and not plot.isWater()
                and not plot.isImpassable()
                and plot.area().getCitiesPerPlayer(kTriggeredData.ePlayer) > 0
                and plot.isAdjacentPlayer(kTriggeredData.ePlayer, true)):
            return true

    return false
Example #19
0
File: Buffy.py Project: AP-ML/DTM
def canTriggerTheVedicAryans(argsList):

    kTriggeredData = argsList[0]
    player = gc.getPlayer(kTriggeredData.ePlayer)

    #   If Barbarians are disabled in this game, this event will not occur.
    if gc.getGame().isOption(GameOptionTypes.GAMEOPTION_NO_BARBARIANS):
        return false

    #   At least one civ on the board must know Polytheism.
    bFoundValid = false

    # BUFFY 3.19.003 - start
    # changes one of the key techs to Priesthood instead of Polytheism
    if isEnabled():
        iTech = gc.getInfoTypeForString("TECH_PRIESTHOOD")
    else:
        iTech = gc.getInfoTypeForString("TECH_POLYTHEISM")
    # BUFFY 3.19.003 - end

    for iPlayer in range(gc.getMAX_CIV_PLAYERS()):
        loopPlayer = gc.getPlayer(iPlayer)
        if loopPlayer.isAlive():
            if gc.getTeam(loopPlayer.getTeam()).isHasTech(iTech):
                bFoundValid = true
                break

    if not bFoundValid:
        return false

    #   At least one civ on the board must know Archery.
    bFoundValid = false
    iTech = gc.getInfoTypeForString("TECH_ARCHERY")
    for iPlayer in range(gc.getMAX_CIV_PLAYERS()):
        loopPlayer = gc.getPlayer(iPlayer)
        if loopPlayer.isAlive():
            if gc.getTeam(loopPlayer.getTeam()).isHasTech(iTech):
                bFoundValid = true
                break

    if not bFoundValid:
        return false

    # BUG - 3.17 - Start
    if GameUtil.isVersion(317):
        # rest indented but unchanged
        # Can we build the counter unit?
        iCounterUnitClass = gc.getInfoTypeForString("UNITCLASS_ARCHER")
        iCounterUnit = gc.getCivilizationInfo(player.getCivilizationType()).getCivilizationUnits(iCounterUnitClass)
        if iCounterUnit == -1:
            return false

        (loopCity, iter) = player.firstCity(false)
        bFound = false
        while loopCity:
            if loopCity.canTrain(iCounterUnit, false, false):
                bFound = true
                break

            (loopCity, iter) = player.nextCity(iter, false)

        if not bFound:
            return false
    # BUG - 3.17 - End

    # 	Find an eligible plot
    map = gc.getMap()
    for i in range(map.numPlots()):
        plot = map.plotByIndex(i)
        if (
            plot.getOwner() == -1
            and not plot.isWater()
            and not plot.isImpassable()
            and plot.area().getCitiesPerPlayer(kTriggeredData.ePlayer) > 0
            and plot.isAdjacentPlayer(kTriggeredData.ePlayer, true)
        ):
            return true

    return false
Example #20
0
__author__ = 'michal'

import GameUtil

# 'main' executable file

game = GameUtil.GameUtil()
game.print_on_start()
player1 = game.create_player('O')
player2 = game.create_player('X')

game.set_turn(player1)

first_turn = True
one_won = False
game_result = False, ''

while not one_won and game.get_playground().is_any_field_empty():
    if first_turn:
        pass
    else:
        if game.get_turn() == player1:
            game.set_turn(player2)
        else:
            game.set_turn(player1)

    first_turn = False

    game.get_playground().show_playground()
    inp = game.get_player_turn()
    while not game.parse_input(inp):