記錄

Pet_6) State 관리 본문

Game/Phaser

Pet_6) State 관리

surhommejk 2018. 4. 6. 21:00

1) 각 State 별로 파일을 만들고 코딩


var BootState = {
    //initiate some game-level settings
init: function() {
//scaling options
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
},
preload: function() {
  this.load.image('preloadBar', 'assets/images/bar.png');
  this.load.image('logo', 'assets/images/logo.png');
},
create: function() {
  this.game.stage.backgroundColor = '#ff6600';

  this.state.start('PreloadState') <-- 끝나고 항상 다음 state를 실행해주어야
state가 순환한다
}
};


끝나고 항상 다음 state를 실행해주어야 state가 순환한다







2) main.js에서 add


//initiate the Phaser framework
var game = new Phaser.Game(360, 640, Phaser.AUTO);

game.state.add('GameState', GameState);
game.state.add('HomeState', HomeState);
game.state.add('PreloadState', PreloadState);
game.state.add('BootState', BootState);
game.state.start('BootState'); <-- 스타트 state를 반드시 잘 선택해서 실행하고
스타트 state 내부에는 연쇄적으로 다음 state로
갈 수 있도록 call 처리가 되어 있어야 한다







3) html에서 추가

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1, minimum-scale=1, user-scalable=no" />
        <title>Learn Game Development at ZENVA.com</title>
        <script type="text/javascript" src="js/phaser.js"></script>     
        <style>
         body {
         padding: 0px;
         margin: 0px;
         background-color: black;
         }
         </style>
    </head>

    <body>
        <script src="js/states/GameState.js"></script>
        <script src="js/states/PreloadState.js"></script>
        <script src="js/states/BootState.js"></script>
        <script src="js/states/HomeState.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>








*********************************************************************




이전 State에서 loading한 asset을

다음 State에서 사용할 수 있다!!





BootState

var BootState = {
    //initiate some game-level settings
init: function() {
//scaling options
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
},
preload: function() {
  this.load.image('preloadBar', 'assets/images/bar.png');
  this.load.image('logo', 'assets/images/logo.png');
},
create: function() {
  this.game.stage.backgroundColor = '#fff';

  this.state.start('PreloadState');
}
};


PreloadState

var PreloadState = {
    //load the game assets before the game starts
preload: function() {

this.logo = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');
this.logo.anchor.setTo(0.5);

this.preloadBar = this.add.sprite(this.game.world.centerX,
this.game.world.centerY + 128, 'preloadBar');
this.preloadBar.anchor.setTo(0.5);
this.load.setPreloadSprite(this.preloadBar);

this.load.image('backyard', 'assets/images/backyard.png');
this.load.image('apple', 'assets/images/apple.png');
this.load.image('candy', 'assets/images/candy.png');
this.load.image('rotate', 'assets/images/rotate.png');
this.load.image('toy', 'assets/images/rubber_duck.png');
this.load.image('arrow', 'assets/images/arrow.png');
this.load.spritesheet('pet', 'assets/images/pet.png', 97, 83, 5, 1, 1);
},
create: function() {
this.state.start('HomeState');
}
};




HomeState

var HomeState = {

init: function(message) {
this.message = message;
},
create: function() {
var background = this.game.add.sprite(0,0,'backyard');
background.inputEnabled = true;
background.events.onInputDown.add(function(){
this.state.start('GameState');
}, this);
var style = {font: '35px Arial', fill: '#fff'};
this.game.add.text(30, this.game.world.centerY + 200, 'TOUCH TO START', style);
if(this.message) {
this.game.add.text(60, this.game.world.centerY - 200, this.message, style);
}
}
};


GameState

//this game will have only 1 state
var GameState = {

//executed after everything is loaded
create: function() {
this.background = this.game.add.sprite(0, 0, 'backyard');
this.background.inputEnabled = true;
this.background.events.onInputDown.add(this.placeItem, this);

this.pet = this.game.add.sprite(100, 400, 'pet');
this.pet.anchor.setTo(0.5);

//spritesheet animation
this.pet.animations.add('funnyfaces', [1, 2, 3, 2, 1], 7, false);

//custom properties
this.pet.customParams = {health: 100, fun: 100};

//draggable pet
this.pet.inputEnabled = true;
this.pet.input.enableDrag();

this.apple = this.game.add.sprite(72, 570, 'apple');
this.apple.anchor.setTo(0.5);
this.apple.inputEnabled = true;
this.apple.customParams = {health: 20};
this.apple.events.onInputDown.add(this.pickItem, this);

this.candy = this.game.add.sprite(144, 570, 'candy');
this.candy.anchor.setTo(0.5);
this.candy.inputEnabled = true;
this.candy.customParams = {health: -10, fun: 10};
this.candy.events.onInputDown.add(this.pickItem, this);

this.toy = this.game.add.sprite(216, 570, 'toy');
this.toy.anchor.setTo(0.5);
this.toy.inputEnabled = true;
this.toy.customParams = {fun: 20};
this.toy.events.onInputDown.add(this.pickItem, this);

this.rotate = this.game.add.sprite(288, 570, 'rotate');
this.rotate.anchor.setTo(0.5);
this.rotate.inputEnabled = true;
this.rotate.events.onInputDown.add(this.rotatePet, this);

this.buttons = [this.apple, this.candy, this.toy, this.rotate];

//nothing is selected
this.selectedItem = null;

//the user interface (UI) is not blocked at the start
this.uiBlocked = false;

var style = { font: '20px Arial', fill: '#fff'};
this.game.add.text(10, 20, 'Health:', style);
this.game.add.text(140, 20, 'Fun:', style);

this.healthText = this.game.add.text(80, 20, '', style);
this.funText = this.game.add.text(185, 20, '', style);

this.refreshStats();

//decrease the health every 5 seconds
this.statsDecreaser = this.game.time.events.loop(Phaser.Timer.SECOND * 5,
this.reduceProperties, this);

},
pickItem: function(sprite, event) {
//if the UI is blocked we can't pick an item
if(!this.uiBlocked) {
console.log('pick item');

this.clearSelection();

//alpha to indicate selection
sprite.alpha = 0.4;

this.selectedItem = sprite;
}
},
rotatePet: function(sprite, event) {

if(!this.uiBlocked) {

//we want the user interface (UI) to be blocked until the rotation ends
this.uiBlocked = true;

this.clearSelection();

//alpha to indicate selection
sprite.alpha = 0.4;

var petRotation = this.game.add.tween(this.pet);

//make the pet do two loops
petRotation.to({angle: '+720'}, 1000);

petRotation.onComplete.add(function(){
//release the UI
this.uiBlocked = false;

sprite.alpha = 1;

//increse the fun of the pet
this.pet.customParams.fun += 10;
//update the visuals for the stats
this.refreshStats();
}, this);

//start the tween animation
petRotation.start();
}

},
clearSelection: function() {

//remove transparency from all buttons
this.buttons.forEach(function(element, index){
element.alpha = 1;
});

//we are not selecting anything now
this.selectedItem = null;
},
placeItem: function(sprite, event) {

if(this.selectedItem && !this.uiBlocked) {
var x = event.position.x;
var y = event.position.y;

var newItem = this.game.add.sprite(x, y, this.selectedItem.key);
newItem.anchor.setTo(0.5);
newItem.customParams = this.selectedItem.customParams;

this.uiBlocked = true;

//move the pet towards the item
var petMovement = this.game.add.tween(this.pet);
petMovement.to({x: x, y: y}, 700);
petMovement.onComplete.add(function(){

//destroy the apple/candy/duck
newItem.destroy();

//play animation
this.pet.animations.play('funnyfaces');

//release the ui
this.uiBlocked = false;

var stat;
for(stat in newItem.customParams) {
//we only want the properties of the customParams object, not properties
that may existing in customParams.prototype
//this filters out all non-desired properties
if(newItem.customParams.hasOwnProperty(stat)) {
this.pet.customParams[stat] += newItem.customParams[stat];
}
}

//update the visuals for the stats
this.refreshStats();

}, this);

//start the tween animation
petMovement.start();
}
},
refreshStats: function() {
this.healthText.text = this.pet.customParams.health;
this.funText.text = this.pet.customParams.fun;
},
reduceProperties: function() {
this.pet.customParams.health -= 10;
this.pet.customParams.fun -= 15;
this.refreshStats();
},
//executed multiple times per second
update: function() {
if(this.pet.customParams.health <= 0 || this.pet.customParams.fun <= 0) {
this.pet.frame = 4;
this.uiBlocked = true;

this.game.time.events.add(2000, this.gameOver, this);
}
},
gameOver: function() {
// 메세지를 보냄과 동시에 게임을 끝내는 것이 아니라
// HomeState로 보낸다

// true : game world를 깨끗하게 하고 재시작을 하게 만든다
// flase : 기존에 preload로 불러온 asset을 버릴지 결정. false는 keep
// 'GAME OVER!' : HomeState에 전달할 메세지
this.state.start('HomeState', true, false, 'GAME OVER!');
}
};


Comments