Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

ChickenOutbreak2 Demo

 import QtQuick 2.0
 import Felgo 4.0
 import QtSensors 5.3

 Item {
   id: windowMainItem
   // all properties assigned here are accessible from all entities!
   // the reason for that is, because entities get created through the EntityManager here in this GameWindow, and only the parent items of the item where it was created are known to the dynamically created entities
   property alias player: gameScene.player

   // for loading the stored highscore and displaying on GameOverScreen when a new highscore is reached
   // these get accessed from the MainScene and the ChickenOutbreakScene
   property int lastScore: 0
   property int teleportCount : 0
   property int parachuteCount : 0
   property int advertDeaths: 0
   property int maxAdvertDeaths: 1
   property bool firstAppStart : true
   property double positionChange: 0

   Component.onCompleted: {
     var storedScore = settings.getValue("maximumHighscore");
     // if first-time use, nothing can be loaded and storedScore is undefined
     if(storedScore)
       maximumHighscore = storedScore;

     var storedFirstAppStart = settings.getValue("firstAppStart")
     if(storedFirstAppStart) {
       flurry.logTimedEvent("Start")
       firstAppStart = false
       teleportCount = settings.getValue("teleports");
       parachuteCount = settings.getValue("parachutes");
     } else {
       teleportCount = 3
       parachuteCount = 3
       store.giveItem("currency_saveit_id",2)
       settings.setValue("facebookLinked",0)
     }

     // Authenticate player to gamecenter
 //    gameCenter.authenticateLocalPlayer();
   }

   Accelerometer {
     id: accelerometer
     active: !system.desktopPlatform
     onReadingChanged: {
       gameScene.player.updateWithAccData(reading)
     }
   }

   function maximumHighscoreChanged() {
     var storedScore = settings.getValue("maximumHighscore");
     // if not stored anything yet, store the new value
     // or if a new highscore is reached, store that
     if(!storedScore || maximumHighscore > storedScore) {
       console.debug("stored improved highscore from", storedScore, "to", maximumHighscore);
       settings.setValue("maximumHighscore", maximumHighscore);
       // this call posts the highscore both to Felgo Game Network and GameCenter, because gameCenterItem is set in VPGN
       gameNetwork.reportScore(maximumHighscore)
     }

     // Post highscore to gameCenter
 //    if (gameCenter.authenticated)
 //      gameCenter.reportScore(maximumHighscore);
   }

   onTeleportCountChanged: {
     settings.setValue("teleports", teleportCount)
   }

   onParachuteCountChanged: {
     settings.setValue("parachutes", parachuteCount)
   }

   // for creating & removing entities
   EntityManager {
     id: entityManager
     entityContainer: gameScene.entityContainer// sceneLoader.entityContainer
     poolingEnabled: true // entity pooling works since version 0.9.4, so use it
   }

   ChickenOutbreakStore {
     id: store
   }

   FelgoGameNetwork {
    id: gameNetwork

    // created in the Felgo Web Dashboard; this is the dev version of the game
    gameId: 24
    // the production password is not public, but this is the dev password
    secret: "chicken2Dev"

    gameNetworkView: vplayGameNetworkScene.gameNetworkView
    facebookItem: facebook
 //   gameCenterItem: gameCenter
 //   clearOfflineSendingQueueAtStartup: true
 //   clearAllUserDataAtStartup: true

    achievements: [

      Achievement {
        key: "cob2_grains10"
        name: "Hobby Collector"
        iconSource: Qt.resolvedUrl("../assets/achievement_10grains.png")
        target: 10
        points: 10
        description: "Collect at least 10 grains in one game"
        descriptionAfterUnlocking: "Collected at least 10 grains in one game"
      },
      Achievement {
        key: "cob2_grains25"
        name: "Passionate Collector"
        iconSource: Qt.resolvedUrl("../assets/achievement_25grains.png")
        target: 25
        points: 25
        description: "Collect at least 25 grains in one game"
        descriptionAfterUnlocking: "Collected at least 25 grains in one game"
      },
      Achievement {
        key: "cob2_grains50"
        name: "Obsessed Collector"
        iconSource: Qt.resolvedUrl("../assets/achievement_50grains.png")
        target: 50
        points: 50
        description: "Collect at least 50 grains in one game"
        descriptionAfterUnlocking: "Collected at least 50 grains in one game"
      },
      Achievement {
        key: "cob2_grains100"
        name: "Addicted Collector"
        iconSource: Qt.resolvedUrl("../assets/achievement_100grains.png")
        target: 100
        points: 100
        description: "Collect at least 100 grains in one game"
        descriptionAfterUnlocking: "Collected at least 100 grains in one game"
      },
      Achievement {
        key: "cob2_badgrains10"
        name: "Suicidal Collector"
        iconSource: Qt.resolvedUrl("../assets/achievement_10badGrains.png")
        target: 10
        points: 10
        description: "The chicken eats 10 bad grains in one game"
        descriptionAfterUnlocking: "The chicken ate 10 bad grains in one game"
      },
      Achievement {
        key: "cob2_teleported10"
        name: "Scotty"
        iconSource: Qt.resolvedUrl("../assets/achievement_teleported.png")
        target: 10
        points: 10
        description: "The chicken beams 10 times in one game"
        descriptionAfterUnlocking: "The chicken beamed 10 times in one game"
      },
      Achievement {
        key: "cob2_parachute10"
        name: "Skydiver"
        iconSource: Qt.resolvedUrl("../assets/achievement_para.png")
        target: 10
        points: 10
        description: "The chicken uses 10 parachutes in one game"
        descriptionAfterUnlocking: "The chicken used 10 parachutes in one game"
      },
      Achievement {
        key: "cob2_chickendead1"
        name: "Empty Henhouse"
        iconSource: Qt.resolvedUrl("../assets/achievement_chickendead.png")
        target: 10
        points: 10
        description: "The chicken dies 10 times in a row"
        descriptionAfterUnlocking: "The chicken died 10 times in a row"
      }

    ]

    onUserScoresInitiallySyncedChanged: {
      if(userScoresInitiallySynced) {
        console.debug("the Felgo Game Network user highscore got synced with the server, maximumHighScore:", maximumHighscore, ", userHighscoreForCurrentActiveLeaderboard:", gameNetwork.userHighscoreForCurrentActiveLeaderboard)

        // if no value is in the highscore list yet, -1 is returned; thus add the check if the maxHighscore is bigger 0
        if(maximumHighscore>0 && maximumHighscore > gameNetwork.userHighscoreForCurrentActiveLeaderboard) {
          // if the user already reached a highscore BEFORE the gameNetwork was used, we initially send the maximumHighscore to the server
          console.debug("there was a highscore reached in a previous version before Felgo Game Network was used - upload it to the server now..")

          gameNetwork.reportScore(maximumHighscore)
        } else if(gameNetwork.userHighscoreForCurrentActiveLeaderboard > maximumHighscore) {
          console.debug("there was a higher score reached on a different device - update the local maximumHighscore now")
          // updating the maximumHighscore here leads to a call of gameNetwork.reportScore(), which then updates the score on GameCenter
          maximumHighscore = gameNetwork.userHighscoreForCurrentActiveLeaderboard
        }

      }
    }

    onAchievementUnlockedAfterServerApproval: {
      var ach = getAchievementFromKey(key)
      if(sceneLoader && sceneLoader.item && sceneLoader.item.achievementOverlay) {
         sceneLoader.item.achievementOverlay.showAchievement(ach)
      }
    }

    onNewHighscoreAfterServerApproval: {
      positionChange = posChange
      updatePlayerNameIfNotSet()
    }

    // facebook signal and property handling:
    onFacebookSuccessfullyConnected: {
      if(facebookConnectionSuccessful) {
        var fbAlreadyConnected = settings.getValue("facebookLinked")
        if(!fbAlreadyConnected) {
          settings.setValue("facebookLinked",1)
          NativeUtils.displayMessageBox(qsTr("Facebook Connected"), qsTr("You just successfully connected to facebook and you got 40 coins, congrats!"))
          store.giveItem("currency_money_id",40)
          audioManager.play(audioManager.idPLING)
        }
      }
    }
    onFacebookSuccessfullyDisconnected: {
      NativeUtils.displayMessageBox(qsTr("Facebook Disconnected"), qsTr("You just successfully disconnected from facebook..."))
    }
    onFacebookConnectionError: {
      // also show this in publish builds, useful for finding the issue if customer requests are sent
      NativeUtils.displayMessageBox(qsTr("Facebook Error"), JSON.stringify(error))
    }

   }// FelgoGameNetwork

   function updatePlayerNameIfNotSet() {
     // call gameNetwork so the user can enter his user name, when gameNetwork is visible we will check again and call the dialog
     if(gameNetwork && !gameNetwork.isUserNameSet(gameNetwork.userName)) {
       window.state = "gameNetwork"
       gameNetwork.showProfileView()

       // like that the dialog would be called immediatelly, not with a timer
       // this is not ideal, because then the scene is not switched (there is an opacity animation at switching)
       // thus start the timer first and then show the dialog
 //      vplayGameNetworkScene.gameNetworkView.profileView.showPlayerNameChangeDialog(qsTr("Change Playername"), qsTr("Congratulations - you reached a new highscore! Please enter your player name:"))

       showUserNameInputTimer.start()
     }
   }

   Timer {
     id: showUserNameInputTimer
     interval: 600
     onTriggered: {
       vplayGameNetworkScene.gameNetworkView.profileView.showPlayerNameChangeDialog("Change Playername", "Congratulations - you reached a new highscore! Please enter your player name:")
     }
   }

   property alias sceneLoader: sceneLoader
   property bool loadAfterSplash: true
   Loader {
     id: sceneLoader
     anchors.left: windowMainItem.left
     anchors.top: windowMainItem.top

     property variant entityContainer: item ? item.entityContainer : undefined

     source: Qt.resolvedUrl("MainScene.qml")
     onLoaded: {
       window.activeScene = sceneLoader.item
       if(!loadAfterSplash) {
         sceneLoader.item.enterScene()
       }
       console.debug("SceneLoader: loaded item with width<"+sceneLoader.item.width+"> and height <"+sceneLoader.item.height+">")
       console.debug("SceneLoader: at position<"+sceneLoader.item.x+"> and height <"+sceneLoader.item.y+">")
       console.debug("SceneLoader: in windowMainItem<"+windowMainItem.x+"> and height <"+windowMainItem.y+">")
     }
   }

   ChickenOutbreakScene {
     id: gameScene
   }

   // can not be loaded by loader because different components need it for initialisation.
   FelgoGameNetworkScene {
     id: vplayGameNetworkScene
   }

   // this gets used for analytics, to know which state was ended before
   property string lastActiveState: ""
   property string lastState: ""

   onStateChanged: {

     console.debug("ChickenBreakoutMain: changed state to", state)

     if(lastActiveState === "main") {
       flurry.endTimedEvent("Display.Main");
     } else if(lastActiveState === "game") {
       flurry.endTimedEvent("Display.Game");
     } else if(lastActiveState === "gameOver") {
       flurry.endTimedEvent("Display.GameOver");
     } else if(lastActiveState === "credits") {
       flurry.endTimedEvent("Display.Credits");
     } else if(lastActiveState === "gameNetwork") {
       flurry.endTimedEvent("Display.FelgoGameNetwork");
     }

     lastState = lastActiveState

     if(state === "main") {
       flurry.logTimedEvent("Display.Main");
     } else if(state === "game") {
       flurry.logTimedEvent("Display.Game");
     } else if(state === "gameOver") {
       flurry.logTimedEvent("Display.GameOver");
     } else if(state === "credits") {
       flurry.logTimedEvent("Display.Credits");
     } else if(state === "gameNetwork") {
       flurry.logTimedEvent("Display.FelgoGameNetwork");
     }

     lastActiveState = state;
   }

   function activateMain() {
     // fade in
     state = "main"
     loadAfterSplash = false
     sceneLoader.item.enterScene()
   }

   // these states are switched when the play button is pressed in MainScene, when the game is lost and when the Continue button is pressed in GameOverScene
   states: [
     State {
       name: "main"
       // by switching the property to 1, which is by default set to 0 above, the Behavior defined in SceneBase takes care of animating the opacity of the new Scene from 0 to 1, and the one of the old scene from 1 to 0
       StateChangeScript {
         script: {
           gameScene.opacity = 0
           sceneLoader.source = "MainScene.qml"
         }
       }
     },
     State {
       name: "tutorial"
       StateChangeScript {
         script: {
           sceneLoader.source = "TutorialScene.qml"
         }
       }
     },
     State {
       name: "game"
       StateChangeScript {
         script: {
           sceneLoader.source = ""
           window.activeScene = gameScene
           gameScene.opacity = 1
           gameScene.enterScene()
           //sceneLoader.source = "ChickenOutbreakScene.qml"
         }
       }
     },
     State {
       name: "credits"
       StateChangeScript {
         script: {
           sceneLoader.source = "CreditsScene.qml"
         }
       }
     },
     State {
       name: "gameOver"
       StateChangeScript {
         script: {
           gameScene.opacity = 0
           sceneLoader.source = "GameOverScene.qml"
         }
       }
     },
     State {
       name: "gameNetwork"
       PropertyChanges { target: vplayGameNetworkScene; opacity: 1}
       PropertyChanges { target: sceneLoader; opacity: 0.0}
       PropertyChanges { target: window; activeScene: vplayGameNetworkScene}
     },
     State {
       name: "shop"
       StateChangeScript {
         script: {
           sceneLoader.source = "ShopScene.qml"
         }
       }
     }
   ]

   function pauseGame() {
Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded