Skip to content

Instantly share code, notes, and snippets.

@kokdemo
Last active August 29, 2015 14:11
Show Gist options
  • Save kokdemo/77393db6f868ad8025bc to your computer and use it in GitHub Desktop.
Save kokdemo/77393db6f868ad8025bc to your computer and use it in GitHub Desktop.
code game AI
/**
* Created by kokdemo on 14/12/7.
*/
var lastPosition = null;
function turnDirection(dir,callback){
var dirs = ['up','right','down','left'];
var turnFunc = {
up: {up: false, right:'left', down:'right',left:'right'},
right:{up:'right',right: false, down:'left', left:'right'},
down: {up:'right',right:'right',down: false, left:'left'},
left: {up:'left', right:'right',down:'right',left: false}
};
//turnFunc 中是处理转向的方法,先寻找要转的方向,然后再判断要转的方法
if(me.tank.direction == dir){
//判断是否符合目的方向
callback();
}else{
//完成转向
me.turn(turnFunc[dir][me.tank.direction]);
}
}
function tankGo(step){
var dirs = ['up','right','down','left'];
if(!step){
step = 1;
}
var xpo = me.tank.position[0];
var ypo = me.tank.position[1];
var ground = {
up :[xpo,ypo-1],
right:[xpo+1,ypo],
down :[xpo,ypo+1],
left :[xpo-1,ypo]
};
if(ground[me.tank.direction] == 'x'){
//前方阻塞,必须转向
var usefulDir = {
number:0,
dirs:[]
};
for(var i=0;i<4;i++){
if(game.map[ground[dirs[i]]] !== 'x'){
//不是死路
usefulDir.number++;
usefulDir.dirs.append(dirs[i]);
}
}
var turn = usefulDir.dirs[Math.floor(Math.random() * usefulDir.number)];
me.turn(turn);
}else{
//前方通畅,前行
me.go()
}
}
function onIdle(me, enemy, game) {
if (enemy.tank) {
// 即敌方坦克不在草丛中
// 因为场上只能存在一枚己方炮弹,所以在这儿判断一下,以免白白浪费指令
if (me.tank.position[0] === enemy.tank.position[0]) {
//当横坐标相等时
if (me.tank.position[1] <= enemy.tank.position[1]) {
//我方在敌方上方
turnDirection('down',function(){
me.fire();
});
} else {
//我方在敌方下方
turnDirection('up',function(){
me.fire();
});
}
} else if (me.tank.position[1] === enemy.tank.position[1]) {
//当纵坐标相等时
if (me.tank.position[0] <= enemy.tank.position[0]) {
//我方在敌方左方
turnDirection('right',function(){
me.fire();
});
} else {
//我方在敌方左方
turnDirection('left',function(){
me.fire();
});
}
} else {
//当横纵坐标都不相等时,寻找星星
if(game.star){
//如果星星存在
if(me.tank.position[0] < game.star[0]){
//我方在星星左边
turnDirection('right',function(){
tankGo();
});
}else if (me.tank.position[0] > game.star[0]){
//我方在星星右边
turnDirection('left',function(){
tankGo();
});
}else{
//我方和星星在一条线上
if(me.tank.position[1] < game.star[1]){
//我方在星星上面
turnDirection('down',function(){
tankGo();
});
}else{
turnDirection('up',function(){
tankGo();
});
}
}
}else{
//星星不存在
tankGo();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment