'Turn based game, how do you decide the turn between player and computer
Trying to code a turn based battle mode for a game and i can not manage to get it to change turns between the player and the computer.
I'm using random number to set first turn but after that it wont change character
what i have tried so far is a while loops and if statements
I'm using the enchant.js framework but plain java-script would do if any one can help
this is my code:
var Battle = Class.create(Scene,{
initialize: function(){
var battle = Game.instance;
Scene.apply(this);
console.log('Battle Screne');
/*
* Background
*/
var bg = new Sprite(320, 320);
bg.image = game.assets['./assets/BS.png'];
this.addChild(bg);
/*
* Player Battle Sprite
*/
BattleHero = Class.create(Sprite,{
initialize:function(x,y){
Sprite.call(this, 32,32);
this.image = game.assets['./assets/SpriteSheet.png'];
this.x =x;
this.y =y;
this.frame = [6];
this.scaleX += 2;
this.scaleY += 2;
//battleScene.addChild(this);
}});
hero = new BattleHero(32*1,32*5);
this.addChild(hero);
/*
* Enemy Battle Class
*/
BattleNpc = Class.create(Sprite,{
initialize:function(x,y){
Sprite.call(this, 32,32);
this.image = game.assets['./assets/SpriteSheet.png'];
this.x =x;
this.y =y;
this.frame = [16];
this.scaleX += 2;
this.scaleY += 2;
}});
npc = new BattleNpc(32*8,32*5);
this.addChild(npc);
/*
* Attack
*/
var turn = Math.floor((Math.random()*2)+1);
console.log('turn equals',turn);
if(turn == 1){
console.log('player Turn',turn);
var attack = new Button("Attack");
attack.x = 32;
attack.y = 32*7.5;
attack.addEventListener(Event.TOUCH_END, function(e) {
console.log('attack pressed');
hero.tl.moveTo(32*8, 32*5, 5);//.moveTo(32*1.5, 32*5, 5);
if(hero.intersect(npc)){
console.log('melee hit');
hero.tl.moveTo(32*1.5, 32*5, 5);
//game.popScene();
turn ++;
return move = false;
console.log('turn is now',turn);
}
});
this.addChild(attack);
//Item Button
var item = new Button("Item");
item.x = 32;
item.y = 32*8.5;
item.addEventListener(Event.TOUCH_START, function(e){
turn = turn++;
});
this.addChild(item);
//Run Button
var run = new Button ("Run");
run.x = 32*4;
run.y = 32*8.5;
run.addEventListener(Event.TOUCH_END, function(e) {
game.popScene();
});
this.addChild(run);
}
//Npc Attact
else{
console.log('Enemy Turn',turn);
npc.frame = [16];
npc.tl.moveTo(32*1.5, 32*5, 5).moveTo(32*8, 32*5, 5);
if(npc.within(hero,16)){
console.log('melee hit');
npc.x = 32*8;
return move = true;
turn= turn--;
};
}
}});
Solution 1:[1]
If you extract your code into separate functions, instead of doing everything in the initialize() function, you would be able to change turns at will.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
