Ejemplo n.º 1
0
	void Awake ()
	{
		if (instance == null)
			instance = this;
		else if (instance != this)
			Destroy (this.gameObject);
	}
Ejemplo n.º 2
0
        public TestGame()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            this.graphics.PreferredBackBufferWidth  = 640;
            this.graphics.PreferredBackBufferHeight = 480;

            // Game should run as fast as possible.
            IsFixedTimeStep = true;
            graphics.SynchronizeWithVerticalRetrace = true;

            aiEngine = new AIEngine((Game)this);
            this.Components.Add(aiEngine);

            AIWorld newWorld = new DrawableAIWorld();

            aiEngine.AddWorld(ref newWorld);

            pathFinder = new AIPathfinder();


            sEngine = new SEngine((Game)this, graphics);
            //this.Components.Add(sEngine);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            //renderEngine = new RenderEngine(this, RenderEngine.Layout.ONE);
            Render.RenderEngine.defaultView = GraphicsDevice.Viewport;
            inputEngine   = new InputEngine(this);
            physicsEngine = new PhysicsEngine(this);
            aiEngine      = new AIEngine(this);

            pickupEngine = new PickUpEngine(this);

            tests[0] = new PickUpGen(this, new Vector3(20, -320, 20), PickUp.PickUpType.AMMO);
            tests[1] = new PickUpGen(this, new Vector3(20, -320, -20), PickUp.PickUpType.HEALTH);
            tests[2] = new PickUpGen(this, new Vector3(-20, -320, 20), PickUp.PickUpType.LEFT);
            tests[3] = new PickUpGen(this, new Vector3(-20, -320, -20), PickUp.PickUpType.RIGHT);

            players = new Player[0];

            /*players = new Player[3];
             * players[0] = new Player(this, PlayerIndex.One, Vector3.Zero);
             * players[1] = new Player(this, PlayerIndex.Two, Vector3.Zero);
             * players[2] = new Player(this, PlayerIndex.Three, new Vector3(100, 0, 0));*/

            //call the super
            base.Initialize();
        }
Ejemplo n.º 4
0
        private void ShowSelectedGame()
        {
            try
            {
                if (DataContext is Data data)
                {
                    UserListDV ul = data.UsersPanelDV.UserListDV;
                    if (ul.SelectedUser != null)
                    {
                        if (ul.SelectedUser.Games.Count > 0)
                        {
                            UserDV selectedUser = ul.SelectedUser;
                            GameDV game         = ul.SelectedUser.SelectedGame;

                            if (game == null)
                            {
                                return;
                            }

                            JsonCheckStatusRequest checkStatusRequest = new JsonCheckStatusRequest();
                            checkStatusRequest.userToken = selectedUser.Token;
                            checkStatusRequest.gameToken = game.GameToken;

                            JsonCheckStatusResponse response = JsonCommunication.CheckStatus(checkStatusRequest);

                            if (response.winnerId != null)
                            {
                                ul.SelectedUser.SelectedGame = null;
                                ul.SelectedUser.Games.Remove(game);
                            }
                            else
                            {
                                DeskData dd       = new DeskData();
                                bool     isMyTurn = selectedUser.Id == response.actualPlayerId;
                                ESymbol  mySymbol;
                                if (isMyTurn)
                                {
                                    mySymbol = response.actualPlayerId == response.playerCircleId ? ESymbol.Circle : ESymbol.Cross;
                                }
                                else
                                {
                                    mySymbol = response.actualPlayerId == response.playerCircleId ? ESymbol.Cross : ESymbol.Circle;
                                }

                                dd.Fill(response, mySymbol, isMyTurn);
                                data.DeskData = dd;

                                if (isMyTurn && data.AutomaticMode)
                                {
                                    AIEngine.StartAIEngine(game, selectedUser, dd);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 5
0
 public virtual void SetAIEngine(AIEngine aiEngine)
 {
     if (UFE.isAiAddonInstalled){
         UFE.SetAIEngine(aiEngine);
     }else{
         UFE.SetAIEngine(AIEngine.RandomAI);
     }
 }
Ejemplo n.º 6
0
 public void RegisterActors(ref AIEngine engine)
 {
     for (int index = 0; index < actors.Count; index++)
     {
         AIActor actorToRegister = actors[index];
         engine.World.Actors.Add(ref actorToRegister);
     }
 }
Ejemplo n.º 7
0
 public double ValueOfGiveResources()
 {
     return(giveBrick * AIEngine.ValueOfBrick() +
            giveOre * AIEngine.ValueOfOre() +
            giveWood * AIEngine.ValueOfWood() +
            giveGrain * AIEngine.ValueOfGrain() +
            giveSheep * AIEngine.ValueOfSheep());
 }
Ejemplo n.º 8
0
 public double ValueOfGetResources()
 {
     return(getBrick * AIEngine.ValueOfBrick() +
            getOre * AIEngine.ValueOfOre() +
            getWood * AIEngine.ValueOfWood() +
            getGrain * AIEngine.ValueOfGrain() +
            getSheep * AIEngine.ValueOfSheep());
 }
Ejemplo n.º 9
0
 public virtual void SetAIEngine(AIEngine aiEngine)
 {
     if (UFE.isAiAddonInstalled)
     {
         UFE.SetAIEngine(aiEngine);
     }
     else
     {
         UFE.SetAIEngine(AIEngine.RandomAI);
     }
 }
Ejemplo n.º 10
0
        public ArmedNPC(UserControl content)
            : base(content)
        {
            Canvas weaponSurface = (Canvas)content.FindName("cnv_weaponSurface");

            if (weaponSurface == null)
            {
                throw new ArgumentNullException("No cnv_weaponSurface implemented!");
            }
            WeaponEngine = new WeaponEngine(weaponSurface);

            AI = new AIEngine();
        }
Ejemplo n.º 11
0
    public bool IsFairTrade()
    {
        bool fairTrade = Mathf.Abs((float)(ValueOfGetResources() - ValueOfGiveResources())) <= AIEngine.AverageValue();

        if (debugMessages)
        {
            GameEngine.print("GET VALUE: " + ValueOfGetResources());
            GameEngine.print("GIVE VALUE: " + ValueOfGiveResources());
            GameEngine.print("___avg val: " + AIEngine.AverageValue());
            GameEngine.print("IS FAIR TRADE?: " + fairTrade);
        }

        return(fairTrade);
    }
Ejemplo n.º 12
0
        public static void BuildTrain(TileIndex depot, StationID[] stations, Action <TileIndex, string> sign = null)
        {
            var list = new AIEngineList(AIVehicle.VT_RAIL);

            list.Valuate(AIEngine.GetMaxSpeed);
            EngineID passangerWagon = null;
            EngineID mailWagon      = null;

            foreach (var(a, b) in list)
            {
                if (AIEngine.IsBuildable(a) && !AIEngine.IsWagon(a))
                {
                    //AILog.Info(a + ": " + AIEngine.GetName(a) + " | " + AIEngine.GetMaxSpeed(a) + " | " + AIEngine.GetReliability(a) + " | " + AIEngine.GetMaxTractiveEffort(a));
                }
                else if (AIEngine.IsBuildable(a) && AIEngine.IsWagon(a))
                {
                    //AILog.Info(a + ": " + AIEngine.GetName(a) + " | " + AIEngine.GetCargoType(a));
                    if (AICargo.HasCargoClass(AIEngine.GetCargoType(a), AICargo.CC_PASSENGERS))
                    {
                        passangerWagon = a;
                        //AILog.Info("passanger");
                    }
                    else if (AICargo.HasCargoClass(AIEngine.GetCargoType(a), AICargo.CC_MAIL))
                    {
                        mailWagon = a;
                        //AILog.Info("mail");
                    }
                }
            }

            var engineType = list.Begin();
            //AILog.Info("Engine id: " + engineType);
            //AILog.Info("Building: " + AIEngine.GetName(engineType));
            var train          = AIVehicle.BuildVehicle(depot, engineType);
            var firstPassanger = AIVehicle.BuildVehicle(depot, passangerWagon);

            AIVehicle.BuildVehicle(depot, passangerWagon);
            AIVehicle.BuildVehicle(depot, passangerWagon);
            var firstMail = AIVehicle.BuildVehicle(depot, mailWagon);

            AIVehicle.MoveWagonChain(firstMail, 0, train, 0);
            AIVehicle.MoveWagonChain(firstPassanger, 0, train, 0);

            for (var i = 0; i < stations.Length; i++)
            {
                AIOrder.AppendOrder(train, AIStation.GetLocation(stations[i]), AIOrder.OF_NONE);
            }

            AIVehicle.StartStopVehicle(train);
        }
Ejemplo n.º 13
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (DataContext is Data data)
            {
                try
                {
                    UserDV user = data.UsersPanelDV.UserListDV.SelectedUser;
                    GameDV game = user.SelectedGame;

                    AIEngine.StartAIEngine(game, user, data.DeskData);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    public override void SetAIEngine(AIEngine aiEngine)
    {
        if (this.visible)
        {
            base.SetAIEngine(aiEngine);

            if (this.aiEngineName != null)
            {
                aiEngine = UFE.GetAIEngine();

                if (aiEngine == AIEngine.RandomAI)
                {
                    this.aiEngineName.text = "Random";
                }
                else
                {
                    this.aiEngineName.text = "Fuzzy";
                }
            }
        }
    }
Ejemplo n.º 15
0
    private bool evaluateTradeRequest(GameState gamestate, TradeOffer trade)
    {
        bool acceptTradeRequest = false;

        if (!isAI)
        {
            // Allow player to accept / reject / modify trade
        }
        else
        {
            List <AIEngine.Objective> objectives = AIEngine.GetObjectives(this, gamestate.getGamestateBoard(), gamestate);

            foreach (AIEngine.Objective objective in objectives)
            {
                PlayerHand thisPlayerNeedResources = objective.GetCardDifferential();

                PlayerHand thisPlayerGiveResources = trade.convertGetResourcesToPlayerHand();                   // tradeHost gets the resources that this Player gives
                PlayerHand thisPlayerGetResources  = trade.convertGiveResourcesToPlayerHand();                  // tradeHost gives the resources that this Player gets

                if (debugMessages)
                {
                    GameEngine.print(objective.GetObjectiveScore() + ": OBJECTIVE SCORE");
                    GameEngine.print("PLAYER " + this.id + " GIVES TO TRADEHOST:" +
                                     "GIVE " + trade.getBrick + " BRICK, " +
                                     "GIVE " + trade.getOre + " ORE, " +
                                     "GIVE " + trade.getWood + " WOOD, " +
                                     "GIVE " + trade.getGrain + " GRAIN, " +
                                     "GIVE " + trade.getSheep + " SHEEP");

                    GameEngine.print("FOR " + trade.giveBrick + " BRICK, " +
                                     "FOR " + trade.giveOre + " ORE, " +
                                     "FOR " + trade.giveWood + " WOOD, " +
                                     "FOR " + trade.giveGrain + " GRAIN, " +
                                     "FOR " + trade.giveSheep + " SHEEP");

                    int[] x = thisPlayerNeedResources.ToArray();
                    GameEngine.print("PLAYER " + this.id + " (SELLER) NEEDS:" +
                                     x[0] + " BRICK, " +
                                     x[1] + " ORE, " +
                                     x[2] + " WOOD, " +
                                     x[3] + " GRAIN, " +
                                     x[4] + " SHEEP");
                }

                bool resourcesNeededOverlapsWithResourcesReceived = false;
                // Compare Cards Received with Cards Needed
                for (int i = 0; i < 5; i++)
                {
                    if (thisPlayerNeedResources.GetResourceQuantity(i) < 0 && thisPlayerGetResources.GetResourceQuantity(i) > 0)
                    {
                        resourcesNeededOverlapsWithResourcesReceived = true;
                    }
                }

                bool resourcesNeededOverlapsWithResourcesGiven = false;
                for (int i = 0; i < 5; i++)
                {
                    if (thisPlayerNeedResources.GetResourceQuantity(i) >= 0 && thisPlayerNeedResources.GetResourceQuantity(i) - thisPlayerGiveResources.GetResourceQuantity(i) < 0)
                    {
                        resourcesNeededOverlapsWithResourcesGiven = true;
                    }
                }

                if (debugMessages)
                {
                    // If any resources needed and received overlap && any resources needed and given do not overlap
                    GameEngine.print("NEEDS OVERLAPS WITH GET?: " + resourcesNeededOverlapsWithResourcesReceived + "(-true-), " +
                                     "NEEDS OVERLAPS WITH GIVE?: " + resourcesNeededOverlapsWithResourcesGiven + " (-false-)");
                }

                if (resourcesNeededOverlapsWithResourcesReceived && !resourcesNeededOverlapsWithResourcesGiven)
                {
                    if (debugMessages)
                    {
                        GameEngine.print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GET NEEDED RESOURCES & ONLY TRADE SURPLUS RESOURCES @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    }

                    if (trade.IsFairTrade() || trade.isGoodTradeForSeller())
                    {
                        acceptTradeRequest = true;
                    }
                    else
                    {
                        System.Random rand = new System.Random();

                        if (rand.Next(100) < 25)                                                // 25% Chance to accept an unfair trade (technically could be better for them, but sometimes worse for them)
                        {
                            acceptTradeRequest = true;
                        }
                    }
                }

                if (acceptTradeRequest)
                {
                    if (debugMessages)
                    {
                        GameEngine.print("# # # # # # # # # # # # # # # # # # # # # # # # # # # ACCEPT TRADE # # # # # # # # # # # # # # # # # # # # # # # # # # #");
                    }

                    break;
                }
            }
        }

        return(acceptTradeRequest);
    }
Ejemplo n.º 16
0
        internal bool MakeRoute(TownNode fromTown, TownNode toTown)
        {
            AILog.Warning($"Building a route from {fromTown.Name} to {toTown.Name}.");
            RoadStationInfo fromStationTile = stations[fromTown.TownId];
            RoadStationInfo toStationTile   = stations[toTown.TownId];

            Edge <TownNode> foundEdge = null;

            foreach (var edge in this.Graph.Edges)
            {
                if (((edge.Node1 == fromTown) && (edge.Node2 == toTown)) || ((edge.Node2 == fromTown) && (edge.Node1 == toTown)))
                {
                    foundEdge = edge;
                }
            }

            if (foundEdge == null)
            {
                AILog.Warning($"No route found from {fromTown.Name} to {toTown.Name}.");
                return(false);
            }

            var list = new AIEngineList(AIVehicle.VT_ROAD);

            list.Valuate(AIEngine.GetMaxSpeed);
            VehicleID vehicleId = null;

            foreach (var(engineType, _) in list)
            {
                if (AICargo.HasCargoClass(AIEngine.GetCargoType(engineType), AICargo.CC_PASSENGERS))
                {
                    var price = AIEngine.GetPrice(engineType);
                    CsTestAi.EnsureMoney(price + 1000);
                    vehicleId = AIVehicle.BuildVehicle(depots[fromTown.TownId].tile, engineType);
                    break;
                }
            }

            if (vehicleId == null)
            {
                AILog.Error("No passnger vehicle found.");
            }

            if (AIVehicle.IsValidVehicle(vehicleId))
            {
                AIOrder.AppendOrder(vehicleId, fromStationTile.tile, AIOrder.OF_NONE);
                AIOrder.AppendOrder(vehicleId, toStationTile.tile, AIOrder.OF_NONE);
                AIVehicle.StartStopVehicle(vehicleId);
                if (!vehicles.ContainsKey(foundEdge))
                {
                    vehicles.Add(foundEdge, new List <VehicleID>());
                }

                var vehicleList = vehicles[foundEdge];
                vehicleList.Add(vehicleId);
                AILog.Info($"Route contains now {vehicleList.Count} vehicles.");
                return(true);
            }

            AILog.Error("Invalid vehicle.");
            return(false);
        }
Ejemplo n.º 17
0
 public double HandValueOfSheep()
 {
     return(sheep * AIEngine.ValueOfSheep());
 }
Ejemplo n.º 18
0
 public double HandValueOfGrain()
 {
     return(grain * AIEngine.ValueOfGrain());
 }
Ejemplo n.º 19
0
    public bool IsFairTrade(PlayerHand a, PlayerHand b)
    {
        PlayerHand get  = a;
        PlayerHand give = b;

        bool fairTrade = Mathf.Abs((float)(get.ValueOfHand() - give.ValueOfHand())) <= AIEngine.AverageValue();

        return(fairTrade);
    }
Ejemplo n.º 20
0
 public static void SetAIEngine(AIEngine engine)
 {
     UFE.config.aiOptions.engine = engine;
 }
Ejemplo n.º 21
0
 public double HandValueOfWood()
 {
     return(wood * AIEngine.ValueOfWood());
 }
Ejemplo n.º 22
0
        private void ShowSelectedGame()
        {
            try
            {
                if (DataContext is Data data)
                {
                    foreach (var bsdi in data.BulkSolveData.Data)
                    {
                        Task.Run(() =>
                        {
                            UserDV user = bsdi.User;
                            GameDV game = bsdi.Game;

                            if (game == null)
                            {
                                return;
                            }

                            JsonCheckStatusRequest checkStatusRequest = new JsonCheckStatusRequest();
                            checkStatusRequest.userToken = user.Token;
                            checkStatusRequest.gameToken = game.GameToken;

                            JsonCheckStatusResponse response = JsonCommunication.CheckStatus(checkStatusRequest);

                            if (response.winnerId != null)
                            {
                                DeskData dd = bsdi.DeskData.Copy();
                                if (response.winnerId == user.Id)
                                {
                                    dd.Winner = user.Nickname;
                                }
                                else
                                {
                                    dd.Winner = "Opponent";
                                }
                                bsdi.DeskData = dd;
                            }
                            else
                            {
                                DeskData dd   = new DeskData();
                                bool isMyTurn = user.Id == response.actualPlayerId;
                                ESymbol mySymbol;
                                if (isMyTurn)
                                {
                                    mySymbol = response.actualPlayerId == response.playerCircleId ? ESymbol.Circle : ESymbol.Cross;
                                }
                                else
                                {
                                    mySymbol = response.actualPlayerId == response.playerCircleId ? ESymbol.Cross : ESymbol.Circle;
                                }

                                dd.SquareSize = 5;
                                dd.Fill(response, mySymbol, isMyTurn);
                                bsdi.DeskData = dd;

                                if (isMyTurn)
                                {
                                    AIEngine.StartAIEngine(game, user, dd);
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 23
0
    /*
     * Handles interactions with game FSM and player input.
     */
    void Update()
    {
        Player currentTurnPlayer = gamestate.GetCurrentTurnPlayer();

        UpdateHumanCardCounts();

        long   elapsedTicksSinceLastAIAction = DateTime.Now.Ticks - lastAIActionTime.Ticks;
        double secondsSinceLastAIAction      = new TimeSpan(elapsedTicksSinceLastAIAction).TotalSeconds;


        //AI Interaction
        if (currentTurnPlayer.isAI)
        {
            if (secondsSinceLastAIAction >= FORCED_TIME_BETWEEN_AI_ACTIONS)
            {
                System.Random rand = new System.Random();

                //Initial settlement placement
                if (curState == GameState.State.placeSettlement)
                {
                    List <Node> locationOptions = AIEngine.GetFavorableStartingLocations(board);

                    //Attempt to place elements in decreasing score order
                    for (int i = 0; i < locationOptions.Count; i++)
                    {
                        if (board.CanBuildSettlementHere(locationOptions[i].visual.transform, currentTurnPlayer, true))
                        {
                            lastStructurePlaced = board.PlaceSettlement(locationOptions[i].visual.transform, currentTurnPlayer, false);
                            break;
                        }
                    }
                    IncrementState();
                    UpdateTurnInfo("Placing Initial Road", currentTurnPlayer.id);
                }
                //Initial road placement
                else if (curState == GameState.State.placeRoad)
                {
                    List <Edge> favorableRoads = AIEngine.GetFavorableRoadExpansions(currentTurnPlayer, board, lastStructurePlaced);

                    foreach (Edge road in favorableRoads)
                    {
                        if (board.CanBuildRoadHere(road.visual.transform, currentTurnPlayer))
                        {
                            lastRoadPlaced = board.PlaceRoad(road.visual.transform, currentTurnPlayer, false);
                            break;
                        }
                    }

                    IncrementState();
                }
                //Roll dice
                else if (curState == GameState.State.roll)
                {
                    if (rollForAI)
                    {
                        if (Input.GetMouseButtonDown(0))
                        {
                            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                            RaycastHit hit;
                            if (interactDebug)
                            {
                                print("mouse press");
                            }
                            if (Physics.Raycast(ray, out hit))
                            {
                                if (hit.transform == dice.transform)
                                {
                                    IncrementState();
                                    updateDice();
                                }
                            }
                        }
                    }
                    else
                    {
                        IncrementState();
                        updateDice();
                    }
                }
                //Trade with players
                else if (curState == GameState.State.trade)
                {
                    proposedObjective = null;

                    if (debugMessages)
                    {
                        print("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~");
                    }

                    //TODO
                    List <AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate);

                    // Trade With Other Players
                    int  tradeOffersThisTurn     = 0;
                    bool hasAnyOfferBeenAccepted = false;
                    foreach (AIEngine.Objective objective in objectives)
                    {
                        if (objective.Score() > 0 && objective.TotalCardsNeeded() > 0 && tradeOffersThisTurn < 3 && !hasAnyOfferBeenAccepted)
                        {
                            TradeOffer offer = currentTurnPlayer.generateAITradeRequest(gamestate.getTurnCounter(), objective);

                            if (null != offer)
                            {
                                if (debugMessages)
                                {
                                    print("TRADENUM: " + tradeOffersThisTurn + " | " + gamestate.GetCurrentTurnPlayer() + "\nATTEMPTING TO TRADE WITH OTHER PLAYERS TO ACHIEVE OBJECT: " + objective.GetObjectiveScore());
                                }

                                tradeOffersThisTurn++;
                                hasAnyOfferBeenAccepted = tradeManager.ExecuteTradeOfferNotification(offer);
                                proposedObjective       = objective;
                            }
                        }
                    }

                    // Trade With Bank
                    foreach (AIEngine.Objective objective in objectives)
                    {
                        if (objective.Score() > 0 && objective.TotalCardsNeeded() > 0 && !hasAnyOfferBeenAccepted)
                        {
                            if (debugMessages)
                            {
                                print(gamestate.GetCurrentTurnPlayer() + " ATTEMPTING TO TRADE WITH BANK");
                            }

                            TradeOffer offer = currentTurnPlayer.generateAITradeWithBank(objective);

                            if (null != offer)
                            {
                                tradeManager.ExecuteTradeWithBank(offer, gamestate.GetCurrentTurnPlayer());
                                hasAnyOfferBeenAccepted = true;
                            }
                        }
                    }

                    if (!hasAnyOfferBeenAccepted && debugMessages)
                    {
                        print(gamestate.GetCurrentTurnPlayer() + " MADE NO TRADES THIS TURN");
                    }

                    IncrementState();
                    FORCED_TIME_BETWEEN_AI_ACTIONS = 0f;                     //TODO Remove
                }
                //Building phase
                else if (curState == GameState.State.place)
                {
                    FORCED_TIME_BETWEEN_AI_ACTIONS = 0f;                     //TODO Remove

                    //TODO
                    List <AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate);
                    foreach (AIEngine.Objective objective in objectives)
                    {
                        print(objective);
                    }

                    foreach (AIEngine.Objective objective in objectives)
                    {
                        if (objective.TotalCardsNeeded() == 0)
                        {
                            AIEngine.PerformObjective(objective, board);
                            break;
                        }
                    }

                    /*//Attempt main objective that we traded for
                     * if (proposedObjective != null) {
                     *      AIEngine.PerformObjective(proposedObjective, board);
                     * }
                     * //Attempt to get -any- objective to work
                     * else {
                     *      List<AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate);
                     *      foreach (AIEngine.Objective objective in objectives) {
                     *              if (AIEngine.PerformObjective(objective, board)) {
                     *                      break;
                     *              }
                     *      }
                     * }*/

                    IncrementState();
                }
                //Place robber
                else if (curState == GameState.State.robber)
                {
                    Player      competitorPlayer   = gamestate.BiggestCompetitorToPlayer(currentTurnPlayer);
                    List <Tile> possiblePlacements = AIEngine.GetListOfRobberPlacements(currentTurnPlayer, competitorPlayer, board);

                    bool robberPlaced = false;

                    //Attempt to place robber on recommended tiles
                    foreach (Tile tile in possiblePlacements)
                    {
                        int index = board.tiles.IndexOf(tile);
                        if (board.PlaceRobber(board.tileHitboxes[index].transform))
                        {
                            robberPlaced = true;
                            break;
                        }
                    }

                    //If for some reason we're out of recommendations...
                    while (!robberPlaced)
                    {
                        print("ERROR: ATTEMPTING TO RANDOMLY PLACE ROBBER!");
                        int tileIndex = rand.Next(board.tiles.Count);
                        robberPlaced = board.PlaceRobber(board.tileHitboxes[tileIndex].transform);
                    }

                    IncrementState();
                }

                lastAIActionTime = DateTime.Now;                 //Prevent AI from acting too quickly
            }
        }
        //Human Interaction
        else
        {
            if (Input.GetMouseButtonDown(0))
            {
                Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (interactDebug)
                {
                    print("mouse press");
                }
                if (Physics.Raycast(ray, out hit))
                {
                    //Need to place something
                    if (curState == GameState.State.placeSettlement || curState == GameState.State.placeRoad || curState == GameState.State.place)
                    {
                        bool isSetup = (curState == GameState.State.placeSettlement || curState == GameState.State.placeRoad);

                        //Choose what to build or use preselected
                        if (curState == GameState.State.place)
                        {
                            if (hit.transform == roadSelector.transform && currentTurnPlayer.CanBuildRoad())
                            {
                                objectToBuild = hit.transform;
                                if (interactDebug)
                                {
                                    print("on a building");
                                }
                            }
                            else if (hit.transform == citySelector.transform && currentTurnPlayer.CanBuildCity())
                            {
                                objectToBuild = hit.transform;
                                if (interactDebug)
                                {
                                    print("on a building");
                                }
                            }
                            else if (hit.transform == settlementSelector.transform && currentTurnPlayer.CanBuildSettlement())
                            {
                                objectToBuild = hit.transform;
                                if (interactDebug)
                                {
                                    print("on a building");
                                }
                            }
                            else if (hit.transform == endTurnButton.transform)
                            {
                                IncrementState();
                            }
                        }
                        else if (curState == GameState.State.placeSettlement)
                        {
                            objectToBuild = settlementSelector.transform;
                        }
                        else if (curState == GameState.State.placeRoad)
                        {
                            objectToBuild = roadSelector.transform;
                        }

                        if (objectToBuild != null)
                        {
                            if (objectToBuild == roadSelector.transform && board.roadHitboxes.ContainsKey(hit.transform))
                            {
                                Node structureToBuildNear = (curState == GameState.State.placeRoad) ? lastStructurePlaced : null;

                                if (board.CanBuildRoadHere(hit.transform, currentTurnPlayer, structureToBuildNear, true))
                                {
                                    lastRoadPlaced = board.PlaceRoad(hit.transform, currentTurnPlayer, !isSetup);
                                    objectToBuild  = null;
                                    if (interactDebug)
                                    {
                                        print("road built!");
                                    }
                                    if (curState == GameState.State.placeRoad)
                                    {
                                        IncrementState();
                                    }
                                }
                            }
                            else if (objectToBuild == settlementSelector.transform && board.settlementHitboxes.ContainsKey(hit.transform))
                            {
                                if (board.CanBuildSettlementHere(hit.transform, currentTurnPlayer, isSetup, true))
                                {
                                    lastStructurePlaced = board.PlaceSettlement(hit.transform, currentTurnPlayer, !isSetup);
                                    objectToBuild       = null;
                                    if (interactDebug)
                                    {
                                        print("settlement built!");
                                    }
                                    if (curState == GameState.State.placeSettlement)
                                    {
                                        IncrementState();
                                    }
                                }
                            }
                            else if (objectToBuild == citySelector.transform && board.settlements.ContainsKey(hit.transform))
                            {
                                if (board.CanBuildCityHere(hit.transform, currentTurnPlayer, true))
                                {
                                    lastStructurePlaced = board.PlaceCity(hit.transform, currentTurnPlayer);
                                    objectToBuild       = null;
                                    if (interactDebug)
                                    {
                                        print("city built!");
                                    }
                                }
                            }
                        }
                    }
                    //Place robber on a chit
                    else if (curState == GameState.State.robber)
                    {
                        if (board.PlaceRobber(hit.transform))
                        {
                            IncrementState();                              //increment if successfully placed
                        }
                    }
                    //Request trades with other players or bank
                    else if (curState == GameState.State.trade)
                    {
                        UpdateTradePanel(hit.transform);
                        if (hit.transform == endTradeButton.transform)
                        {
                            IncrementState();
                        }
                        else if (hit.transform == offerTradeButton.transform)
                        {
                            OfferTrade();
                        }
                        else if (hit.transform == endTurnButton.transform)
                        {
                            IncrementState();
                            IncrementState();
                        }


                        //tradeManager.ExecuteTradeWithBank(offer, gamestate.GetCurrentTurnPlayer());
                    }
                    //listen for click on dice
                    else if (curState == GameState.State.roll)
                    {
                        if (interactDebug)
                        {
                            print(hit.transform == dice.transform);
                        }
                        if (hit.transform == dice.transform)
                        {
                            IncrementState();
                            updateDice();
                        }
                    }
                    else
                    {
                        if (interactDebug)
                        {
                            print("should not be here");
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 24
0
    // Returns a TradeOffer if the trade is valid (an identical request has not recently been made); If this is not true, returns null
    public TradeOffer generateAITradeRequest(int currentTurn, AIEngine.Objective objective)
    {
        TradeOffer trade = BuildFairTrade (currentTurn, objective.GetCardDifferential ());

        if(trade.TotalGetResources() > 1 && trade.TotalGiveResources() > 1)
        {
            trade.RandomUnequalizeTrade ();	// Introduces an element of randomness to the trade algorithm
        }

        if(debugMessages)
        {
            GameEngine.print ("PLAYER HAND: \n" +
                              hand.brick + " BRICK\n" +
                              hand.ore + " ORE\n" +
                              hand.wood + " WOOD\n" +
                              hand.grain + " GRAIN\n" +
                              hand.sheep + " SHEEP");

            GameEngine.print ("CARDS NEEDED: \n" +
                              objective.GetCardsNeeded().brick + " BRICK\n" +
                              objective.GetCardsNeeded ().ore + " ORE\n" +
                              objective.GetCardsNeeded ().wood + " WOOD\n" +
                              objective.GetCardsNeeded ().grain + " GRAIN\n" +
                              objective.GetCardsNeeded ().sheep + " SHEEP");

            GameEngine.print ("CARD DIFFERENTIAL: \n" +
                              objective.GetCardsNeeded().GetHandSize() + " CARDS NEEDED\n" +
                              objective.GetCardDifferential ().brick + " BRICK\n" +
                              objective.GetCardDifferential ().ore + " ORE\n" +
                              objective.GetCardDifferential ().wood + " WOOD\n" +
                              objective.GetCardDifferential ().grain + " GRAIN\n" +
                              objective.GetCardDifferential ().sheep + " SHEEP");
        }

        if(GetPermissionToRetryTradeRequest (currentTurn, trade))
        {
            return trade;
        }

        return null;
    }
Ejemplo n.º 25
0
 public ComputerConsolePlayer(ActivePlayer color, DifficultyLevel difficulty, IODevice iODevice)
     : base(color, iODevice)
 {
     engine = new AIEngine(difficulty);
 }
Ejemplo n.º 26
0
    // Returns a TradeOffer if the trade is valid; If the ratio is not 4:1 or player does not have enough resources, returns null
    public TradeOffer generateAITradeWithBank(AIEngine.Objective objective)
    {
        if(debugMessages)
        {
            GameEngine.print ("-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#- BANK TRADE REQUEST -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-");
        }

        return BuildTradeWithBank (objective.GetCardDifferential ());
    }
Ejemplo n.º 27
0
        private void Play()
        {
            try
            {
                if (DataContext is Data data)
                {
                    foreach (var d in data.BulkSolveData.Data)
                    {
                        if (d.DeskData.Winner != null)
                        {
                            if (RemoveCounter.ContainsKey(d))
                            {
                                RemoveCounter[d]++;
                            }
                            else
                            {
                                RemoveCounter.Add(d, 0);
                            }

                            if (RemoveCounter[d] >= 5)
                            {
                                data.BulkSolveData.Data.Remove(d);
                                RemoveCounter.Remove(d);
                            }
                        }
                    }

                    if (!stop)
                    {
                        while (data.BulkSolveData.Data.Count < 24)
                        {
                            BulkSolveDataItem bsdi = CreateGame();
                            data.BulkSolveData.Data.Add(bsdi);
                        }
                    }


                    foreach (var item in data.BulkSolveData.Data)
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                UserDV user = item.User;
                                GameDV game = item.Game;

                                if (game == null)
                                {
                                    return;
                                }

                                JsonCheckStatusRequest checkStatusRequest = new JsonCheckStatusRequest();
                                checkStatusRequest.userToken = user.Token;
                                checkStatusRequest.gameToken = game.GameToken;

                                JsonCheckStatusResponse response = JsonCommunication.CheckStatus(checkStatusRequest);

                                if (response.winnerId != null)
                                {
                                    DeskData dd = item.DeskData.Copy();
                                    if (response.winnerId == user.Id)
                                    {
                                        dd.Winner = user.Nickname;
                                    }
                                    else
                                    {
                                        dd.Winner = "Opponent";
                                    }
                                    item.DeskData = dd;
                                }
                                else
                                {
                                    DeskData dd   = new DeskData();
                                    bool isMyTurn = user.Id == response.actualPlayerId;
                                    ESymbol mySymbol;
                                    if (isMyTurn)
                                    {
                                        mySymbol = response.actualPlayerId == response.playerCircleId ? ESymbol.Circle : ESymbol.Cross;
                                    }
                                    else
                                    {
                                        mySymbol = response.actualPlayerId == response.playerCircleId ? ESymbol.Cross : ESymbol.Circle;
                                    }

                                    dd.SquareSize = 5;
                                    dd.Fill(response, mySymbol, isMyTurn);
                                    item.DeskData = dd;

                                    if (isMyTurn)
                                    {
                                        AIEngine.StartAIEngine(game, user, dd);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 28
0
    public override void SetAIEngine(AIEngine aiEngine)
    {
        if (this.visible){
            base.SetAIEngine(aiEngine);

            if (this.aiEngineName != null){
                aiEngine = UFE.GetAIEngine();

                if (aiEngine == AIEngine.RandomAI){
                    this.aiEngineName.text = "Random";
                }else{
                    this.aiEngineName.text = "Fuzzy";
                }
            }
        }
    }
Ejemplo n.º 29
0
 public static void NewMaster()
 {
     master = new GameMaster ();
     TheAI = new AIEngine (master);
 }
Ejemplo n.º 30
0
 public double HandValueOfBrick()
 {
     return(brick * AIEngine.ValueOfBrick());
 }
Ejemplo n.º 31
0
 public double HandValueOfOre()
 {
     return(ore * AIEngine.ValueOfOre());
 }
    public override void OnShow()
    {
        base.OnShow();
        this.visible = true;

        if (this.music != null)
        {
            UFE.DelayLocalAction(delegate(){ UFE.PlayMusic(this.music); }, this.delayBeforePlayingMusic);
        }

        if (this.stopPreviousSoundEffectsOnLoad)
        {
            UFE.StopSounds();
        }

        if (this.onLoadSound != null)
        {
            UFE.DelayLocalAction(delegate(){ UFE.PlaySound(this.onLoadSound); }, this.delayBeforePlayingMusic);
        }

        if (this.musicToggle != null)
        {
            this.musicToggle.isOn = UFE.config.music;
        }

        if (this.musicSlider != null)
        {
            this.musicSlider.value = UFE.config.musicVolume;
        }

        if (this.soundToggle != null)
        {
            this.soundToggle.isOn = UFE.config.soundfx;
        }

        if (this.soundSlider != null)
        {
            this.soundSlider.value = UFE.config.soundfxVolume;
        }

        int difficultySettingsLength    = UFE.config.aiOptions.difficultySettings.Length;
        AIDifficultySettings difficulty = UFE.GetAIDifficulty();

        if (this.difficultySlider != null)
        {
            this.difficultySlider.minValue     = 0;
            this.difficultySlider.maxValue     = difficultySettingsLength - 1;
            this.difficultySlider.wholeNumbers = true;
            this.difficultySlider.value        = this.GetDifficultyIndex(difficulty);
        }

        if (this.difficultyName != null)
        {
            this.difficultyName.text = difficulty.difficultyLevel.ToString();
        }

        if (this.aiEngineName != null)
        {
            AIEngine aiEngine = UFE.GetAIEngine();

            if (aiEngine == AIEngine.RandomAI)
            {
                this.aiEngineName.text = "Random";
            }
            else
            {
                this.aiEngineName.text = "Fuzzy";
            }
        }

        if (this.debugModeToggle != null)
        {
            this.debugModeToggle.isOn = UFE.config.debugOptions.debugMode;
        }

        if (this.diagnosticModeToggle != null)
        {
            GameObject nameObj = GameObject.Find("Name");
            if (nameObj != null)
            {
                NameHolder name = nameObj.GetComponent <NameHolder>();
                if (name != null)
                {
                    this.diagnosticModeToggle.isOn = name.diagnosticMode;
                }
                else
                {
                    Debug.Log("Could not find nameholder script");
                }
            }
            else
            {
                Debug.Log("Could not find name object");
            }
        }
        if (this.changeControlsButton != null)
        {
            this.changeControlsButton.gameObject.SetActive(
                UFE.isCInputInstalled && UFE.config.inputOptions.inputManagerType == InputManagerType.cInput
                );
        }

        this.HighlightOption(this.FindFirstSelectable());
    }
Ejemplo n.º 33
0
    public static List <Tile> GetListOfRobberPlacements(Player currentTurnPlayer, Player competitorPlayer, Board board)
    {
        //Get list of current player's tiles
        List <Tile> myTiles = new List <Tile>();

        foreach (Node structure in currentTurnPlayer.structures)
        {
            foreach (Tile tile in structure.getTiles())
            {
                myTiles.Add(tile);
            }
        }

        List <ScoredTile> scoredCompetitorTiles = new List <ScoredTile> ();

        //Get scored lists of top competitors tiles that don't neighbor current player
        foreach (Node structure in competitorPlayer.structures)
        {
            foreach (Tile tile in structure.getTiles())
            {
                //Doesn't neighbor current player
                if (!myTiles.Contains(tile))
                {
                    int cityModifier = (structure.occupied == Node.Occupation.city) ? 2 : 1;

                    double score   = AIEngine.TileScore(tile) * cityModifier;
                    bool   updated = false;

                    //Append score if already discovered
                    foreach (ScoredTile scoredTile in scoredCompetitorTiles)
                    {
                        if (scoredTile.tile == tile)
                        {
                            scoredTile.score += score;
                            updated           = true;
                        }
                    }

                    //Add to list of discovered if not already
                    if (!updated)
                    {
                        scoredCompetitorTiles.Add(new ScoredTile(tile, score));
                    }
                }
            }
        }

        List <Tile> competitorTiles = new List <Tile>();

        //Return sorted list of tile options if available
        if (scoredCompetitorTiles.Count > 0)
        {
            scoredCompetitorTiles = scoredCompetitorTiles.OrderByDescending(t => t.score).ToList();

            foreach (ScoredTile scoredTile in scoredCompetitorTiles)
            {
                competitorTiles.Add(scoredTile.tile);
            }
        }
        //If all else fails, just return the desert tile
        else
        {
            Tile desert = null;

            foreach (Tile tile in board.tiles)
            {
                if (tile.GetResource() == Tile.Resource.none)
                {
                    desert = tile;
                    break;
                }
            }

            competitorTiles.Add(desert);
        }

        return(competitorTiles);
    }