Java版战棋(SLG)游戏AI及寻径处理入门

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

 代码下载地址:http://download.csdn.net/source/1047937


 SLG或者说战棋游戏,在大多数英文站点是归类到SimulationGame的(包括模拟城市之类的纯SIM),并没有进行SRPG(Strategies Role PlayGames)、RTS(Real-Time Strategy Game)乃至RSLG(Role play SimulationGame)种种的细分。归结原因,想必还是因为近似因素太多,在大多数时候已经难以区分其本来面貌,只能一概而论,所以本文也可以理解为SRPG或RSLG开发的入门示例。

 

前言:

 这是一篇孤立的博文,精简了示例代码效果及行数,仅保留最基础功能,与以前写过的[Java版SLG游戏开发入门]没有直接联系,但可以互相参看。

 

关于AI:

 AI(Artificial Intelligence),即人工智能,有时也称作机器智能或人工脑,是指那些由人类制造出来的系统,在面对具体事务时,所表现出的类人反应。通常情况下人工智能多指以人类思维模式为准绳,通过计算机模拟实现的智能。

 人工智能的定义可以分为两部分,即“人工”和“智能”。“人工”比较好理解,争议性也不大。有时我们会要考虑什么是人力所能及制造的,或著人自身的智能程度有没有高到可以创造人工智能的地步,等等。但总的来说,“人工系统”就是通常意义下的人工系统。

 举凡涉及到什么是“智能”的话题,就问题多多……人唯一了解的智能是人本身的智能,这是普遍认同的观点。但我们对自身智能的理解也都非常有限,对构成人的智能的必要元素也知之甚少,所以很难真正定义什么是“人工”制造的“智能”。


 据此,我同样很怕写涉及到AI题材的博文,首先AI处理本就是个有待研究的领域,因为甚至连[智能]究竟是什么都是个很难解释的问题,这其中还涉及到其它诸如意识(consciousness)、自我(self)、心灵(mind)(包括无意识的精神(unconscious_mind)等等,存在相当大程度的争议。

 而评判AI的标准也不尽相同,抛开还很遥远的人工生命(“强人工智能”或“弱人工智能”),似乎要成为标准的“机器人三定律”,图灵测试等等不说,单从游戏AI引擎的设计角度讲,这已经是个很严肃的话题,并非一两行代码就能构建完成的,负责任的说,如果要严谨的写出一个中等规模战棋游戏的AI处理代码,并配合图文解释且标注上参考文献,加上关键字摘要等等,差不多就是篇硕士论文|||,总之水很深。考虑到篇幅及鄙人水平因素,故此文中并没有深入探究,仅仅给出一个“入门示例”,供看客参考而已。

 

正文:

 事实上我们之所以喜欢游戏,很大程度上是基于“与天斗,与地斗,与人斗,其乐无穷”的理由,相信极少有玩家会喜欢战场上的敌人永远一动不动任你蹂躏,更不会有人喜欢仅仅出现You win again字样的游戏。应该说,游戏中的AI很大程度上讲是体现在电脑与玩家的对抗中,一款好的游戏AI应该能足够刺激玩家,“蹂躏”玩家,吸引玩家参与对抗。
 
 不妨这样讲,制作游戏的目的相较于体现玩家的“聪明”,倒不如说是更希望看见他们的“愚蠢”,看见他们被游戏玩弄得惊慌失措,叫苦连天,还乐此不疲的“憨佬”形象,这才是我们作为游戏开发者的最大快乐(^^)~

 根据具体事件的不同,游戏AI可具体体现在以下两个方面:

 一、单元活动AI(Unit Behavioral AI)

  游戏AI并不总是标准含义上的AI。而单元(也可理解为角色或者基本对象,以下同)游戏AI正是为设计出具有提供某种挑战或某种真实体现的生命特征的一次真正的尝试。

  譬如在玩家与游戏的互动中,只站在一处、从不移动的警卫会显得非常不真实。不过,如果你创建一个例行程序(routine),使他不时的朝四周张望,或变换他的姿势,他会看起来更具活力。通过创建一个在预设的路径上行走的警卫偶然停在站岗的警卫前,并好像与他谈话这样的情景,真实的体现能被极大地提高。单元活动AI,正是出于这种目的制作的“拟人性”而非“拟人”AI。

  在单元AI中,动作模式可分为被动式(Passive)与自发式(Spontaneous)两大类。
 
  1、被动式:现实生活中,如果有人打了你的左脸,要不然就伸出右脸让他再打,要不然就伸出右手还他一巴掌,总之,你会有相应的“反应”。而被动式AI,正是这种情况的体现。

  在被动模式下,单元(角色)随时会对自身环境中的变化做出响应。如果一个敌人发现了你,开始向你跑来,并朝你射击,那么他们已经做出了看到你的反应。
 
  2、自发式:在自发模式下,单元做出行动时并不依赖于自身环境中的任何变化。一个单元决定从其所站立的岗哨移向基地周围的某个游动岗哨,则这个单元已经做出了一次自发性的行动。

   通过在你的游戏中加入不同的单元活动元素,就能够制造出单元的“聪明”假象,令玩家产生对手如同真人的错觉。

 二、单元行动AI(Unit Actions AI)
  

   好比人类的智商是体现在行为及对世情的准确判断上,真正让一个游戏单元看起来聪明或者愚蠢的,同样是他们的行动。

   简单的说,如果游戏单元依照玩家认为可行的方式移动,或者在玩家认知范围合理的情景下做如闪避这样的动作,那么单元看起来会很聪明,相反则会给人愚蠢的印象。但是,实际开发中这种现象都并非真实存在,而是看起来聪明或愚蠢的假象,因为程序仅仅与玩家面对的基本情景相关联,而并非游戏中角色真的聪明抑或愚蠢。

   如果你处理恰当,且这一应用包含的范围广泛,你的玩家就会相信你的单元足够“聪明”。为了实现这一目的,你需要把自己放在你所构建单元的位置上思考,如果把你丢到游戏中,在他们的情景下你会怎么做?你将怎样回应各种各样的攻击或遭遇敌人?如果什么事都根本没发生,你又将会做些什么?

   如果你回答了这些问题,并针对你的单元将遇到的每种情景正确的实施了它们,你拥有“看似聪明”单元的机会就会最大化,这也是创建一个优秀的、稳健的游戏AI的第一步。

 

谈过了单元行为,我们再来说说单元运行中的事件分类。

 根据处理事件采取的不同技术,游戏AI又可分为确定性(deterministic)AI与非确定性(Non-deterministic)AI两大类别:

  1、确定性AI:

  确定性AI的单元(角色)行为或者说表现是特定的,可预测,没有任何不确定因素。其具体实现如同我在博文[Java伪寻径追踪实现]中展示的单元追逐演算,一个非玩家单元紧随玩家单元X,Y坐标前进,直至与玩家单元或目标点重叠为止。


  2、非确定性AI:

  与确定性AI相反,非确定性AI在行为模式上存在着很大程度上的不可预测性,理论上讲甚至能够令单元(角色)做出很多超出程序员构想的突现行为。简单实现可见随本博文发布的程序示例(单元随机动作),但其复杂实现则需要应用到神经网路、贝斯叶概率模式、乃至基因演算法等相关知识支撑。故此鄙人对严谨意义上的非确定性AI也不敢置喙太多,深入研究有待看客自行探索。

  3、[隐藏类别] AI处理结果欺诈(流氓手段、作弊、赖招,随便叫(-_-|||)):

  这种方式事实上是程序员心智肚明,却又讳莫如深的一种编程技巧,我读书时老师戏称其为“流氓手段”。还记得在当时课堂上,老师曾举过这样一个例子,让我们写出一段能够得到1-100相累加结果的最简代码,同学们发言很踊跃,但是却没人有正确答案。而当我们质疑老师的评判标准时,老师却给出了绝对最简的答案——直接显示5050。

  应该说,在处理绝对可知结果时,这种方式确实非常有效,对于频繁运算来讲更能体现其价值所在;而对于游戏中某些运算复杂,但结果却单一的事件,确实可以采用“流氓手段”进行编程,即可提高效率,又减少了代码量,但却决不能轻易被用户知道,尤其是在网游的转轮盘、精炼等结果中……


 总结:


  就我目前所知的游戏AI实现中,确定性AI可谓绝对主流,因为它的结果固定有穷,所以相对于非确定AI占用程序资源更小,效率更高,实现也更简单。但有利必有弊,对一个聪明的玩家而言,找出一个确定性AI的规律是再简单不过的事情,有限的行动模式,也必然决定游戏可玩性同样有限。

 而非确定性AI,则毫无疑问是块雷区,无论对我这种业余玩票性质抑或专业游戏开发者尽都如此,它已经无限延伸入“人工生命”这块“神之领域”,并非短时间就能够学习甚至使用的技术。但如果能在程序中成功利用,则无疑会极大增强游戏可玩性。

 至于我提到的“流氓手段”,则只能意会,不可言传,大家心照不宣。

 总体来讲,游戏AI无论是确定性或非确定性,单元(角色)都难免如同巴浦洛夫狗流哈喇子中的dog那样,仅仅会对特定事件做出“条件反射”,依据制作者设定好的行为模式而并非角色的自主思维运作,行为可能性是“有穷”的,并没有如人类般拥有“无限可能性”,故此可以看作一种“伪智能”,而非严格意义上的“人工智能”。当然,我相信随着技术的发展,这种“伪智能”技术最终将进化为真正意义上的“人工智能”。

 

对于具体处理流程,则可作如下分类:
  
 1、有限状态机(Finite State Machin,FSM):

 最廉价、同时也是最实用的技术。在游戏实现(非游戏实现有出入)中的基本运作方式是采用穷举方式,罗列出单元所有可能的动作或状态,再利用switch、if等方式判定各种事件关系及满足条件,据此变更单元的动作或状态,由于我们所能做的仅是编辑从一状态到另一状态的转换,完成这系列一行为的算法,就可归属于分层有限状态机。

 2、模糊状态机(Fuzzy State Machine,FuSM):

 当利用随机数等方式触发模糊逻辑(fuzzy logic)时,会令单元的动作较难预计,产生大量新的分支判断,这时处理多个有限状态机情况的技术实现,就是模糊状态机,它以看“不精准”的响应来进行不确定性结果的处理。

 3、分层有限状态机(Hierarchical Finite State Machines,HFSM)及扩展分层有限状态机(Extended Hierarchical Finite State Machines,EHFSM):

 这两项技术可视同有限状态机与模糊状态机的融合体,他们尝试以一种树状结构分别处理有限及模糊状态,是一系列由同一个支点扩展开的行为模式树,不同的是扩展分层有限状态机有更为严密的控制流及数据流,当然代价是对于游戏系统的资源损耗也更多。

 以上是AI引擎开发中常用的一些基础概念,如果想深入了解相关细节,还需看客自行深入研究。

 

关于单元(角色)寻径:

  如果单元拥有AI,那么他理所应当的能够自主行动。但是,我们都知道游戏中角色是不存在或者说很难实现真正意义上AI的,所以与AI处理同样,寻径同样是我们这些程序员的一种“欺诈手段”,用以“蒙蔽”用户,让他们产生单元拥有自主思维的错觉。

  关于常见的几种寻径方式,可见参本人博文[Java中的A*(A star)寻径实现]以及[Java伪寻径追踪实现],不再赘述。

  简单的说,平面图是由x、y两点构成的,而所谓寻径就是在网格化的地图上连接出点到点间的路线交集;如果我们以二维数组mapList表示地图数据,moveList表示地图上可移动点的话,那么复合mapList地图数据及moveList上可移动点所构成的交集,就是寻径后得到的单元行走路线,即寻径结果。

  相较于AI部分,寻径可以看作AI实现中的一项分支技术,个人认为没有太过深入探究理论的必要,唯一需要关心的,仅在于多对象寻径时的效率或准确性取舍问题,同样请参考相关技术文献,否则本文随时超出文章最大字数……

 

具体到游戏实现流程:

 

SLG离不开战场及角色与各种事件判断,而具体到其构建过程,大多遵循如下顺序:

1、地图(背景战场图)构建


2、获得对应地图基本单元的对象集合(2D游戏中多为二维数组)


3、获得可移动点的对象集合


4、创建地图上角色(针对于地图基本单元放置)


5、激活键盘或者鼠标事件(处理如光标移动等)


6、根据选择的不同在地图单元上绘制相光事件触发物(菜单等),以供事件触发


7、当选择事件时,事件处理开始,各单元(角色)根据预先设定响应事件反馈给玩家(比如移动、攻击等事件)


8、当我方全部行动结束或者选择结束后,敌军开始由AI自行处理事件


9、判定是否满足战斗结束条件


10、如果未满足步骤9,则循环回步骤1,同时回合数+1,游戏继续

 在这一过程中,还可以加入如兵种、物品、特殊人物加成等影响性数据,但基本流程不受影响。 

 

具体到演示代码:

 

  本博文附带的演示代码有核心基本类如下,具体请参见代码注释:

 

  Role.java(角色处理,包含敌我双方)

 

[java] view plain copy print ?
  1. package org.loon.simple.slg.ai;  
  2. import java.awt.Image;  
  3. /** 
  4.  * Copyright 2008 - 2009 
  5.  *  
  6.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
  7.  * use this file except in compliance with the License. You may obtain a copy of 
  8.  * the License at 
  9.  *  
  10.  * http://www.apache.org/licenses/LICENSE-2.0 
  11.  *  
  12.  * Unless required by applicable law or agreed to in writing, software 
  13.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
  14.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
  15.  * License for the specific language governing permissions and limitations under 
  16.  * the License. 
  17.  *  
  18.  * @project loonframework 
  19.  * @author chenpeng 
  20.  * @email:[email protected] 
  21.  * @version 0.1 
  22.  */  
  23. public class Role {  
  24.     //名称  
  25.     String name;  
  26.     //分队(0:我军 1:敌军)  
  27.     int team;   
  28.     //hp  
  29.     int hp;  
  30.     //角色图像  
  31.     Image image;   
  32.     //移动力  
  33.     int move;  
  34.     //行动状态(0:未行动 1:已行动)  
  35.     int action;   
  36.     //x坐标  
  37.     int x;   
  38.     //y坐标  
  39.     int y;   
  40.     //是否已进行攻击  
  41.     boolean isAttack = false;  
  42.     /** 
  43.      * 设定角色参数 
  44.      *  
  45.      * @param name 
  46.      * @param team 
  47.      * @param image 
  48.      * @param move 
  49.      * @param x 
  50.      * @param y 
  51.      */  
  52.     public Role(String name, int team, Image image, int move, int x, int y) {  
  53.         this.name = name;  
  54.         this.team = team;  
  55.         this.hp = 10;  
  56.         this.image = image;  
  57.         this.move = move;  
  58.         this.x = x;  
  59.         this.y = y;  
  60.     }  
  61.     public int getAction() {  
  62.         return action;  
  63.     }  
  64.     public void setAction(int action) {  
  65.         this.action = action;  
  66.     }  
  67.     public int getHp() {  
  68.         return hp;  
  69.     }  
  70.     public void setHp(int hp) {  
  71.         this.hp = hp;  
  72.     }  
  73.     public Image getImage() {  
  74.         return image;  
  75.     }  
  76.     public void setImage(Image image) {  
  77.         this.image = image;  
  78.     }  
  79.     public int getMove() {  
  80.         return move;  
  81.     }  
  82.     public void setMove(int move) {  
  83.         this.move = move;  
  84.     }  
  85.     public String getName() {  
  86.         return name;  
  87.     }  
  88.     public void setName(String name) {  
  89.         this.name = name;  
  90.     }  
  91.     public int getTeam() {  
  92.         return team;  
  93.     }  
  94.     public void setTeam(int team) {  
  95.         this.team = team;  
  96.     }  
  97.     public int getX() {  
  98.         return x;  
  99.     }  
  100.     public void setX(int x) {  
  101.         this.x = x;  
  102.     }  
  103.     public int getY() {  
  104.         return y;  
  105.     }  
  106.     public void setY(int y) {  
  107.         this.y = y;  
  108.     }  
  109.     public boolean isAttack() {  
  110.         return isAttack;  
  111.     }  
  112.     public void setAttack(boolean isAttack) {  
  113.         this.isAttack = isAttack;  
  114.     }  
  115. }  
package org.loon.simple.slg.ai;import java.awt.Image;/** * Copyright 2008 - 2009 *  * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at *  * http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. *  * @project loonframework * @author chenpeng * @email:[email protected] * @version 0.1 */public class Role { //名称 String name;    //分队(0:我军 1:敌军) int team;     //hp int hp;    //角色图像 Image image;     //移动力 int move; //行动状态(0:未行动 1:已行动) int action;  //x坐标 int x;  //y坐标 int y;  //是否已进行攻击 boolean isAttack = false; /**  * 设定角色参数  *   * @param name  * @param team  * @param image  * @param move  * @param x  * @param y  */ public Role(String name, int team, Image image, int move, int x, int y) {  this.name = name;  this.team = team;  this.hp = 10;  this.image = image;  this.move = move;  this.x = x;  this.y = y; } public int getAction() {  return action; } public void setAction(int action) {  this.action = action; } public int getHp() {  return hp; } public void setHp(int hp) {  this.hp = hp; } public Image getImage() {  return image; } public void setImage(Image image) {  this.image = image; } public int getMove() {  return move; } public void setMove(int move) {  this.move = move; } public String getName() {  return name; } public void setName(String name) {  this.name = name; } public int getTeam() {  return team; } public void setTeam(int team) {  this.team = team; } public int getX() {  return x; } public void setX(int x) {  this.x = x; } public int getY() {  return y; } public void setY(int y) {  this.y = y; } public boolean isAttack() {  return isAttack; } public void setAttack(boolean isAttack) {  this.isAttack = isAttack; }}

 

  Map.java(地图处理)

 

[java] view plain copy print ?
  1. package org.loon.simple.slg.ai;  
  2. import java.awt.Graphics;  
  3. import java.awt.Image;  
  4. import java.io.BufferedReader;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9. /** 
  10.  * Copyright 2008 - 2009 
  11.  *  
  12.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
  13.  * use this file except in compliance with the License. You may obtain a copy of 
  14.  * the License at 
  15.  *  
  16.  * http://www.apache.org/licenses/LICENSE-2.0 
  17.  *  
  18.  * Unless required by applicable law or agreed to in writing, software 
  19.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
  20.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
  21.  * License for the specific language governing permissions and limitations under 
  22.  * the License. 
  23.  *  
  24.  * @project loonframework 
  25.  * @author chenpeng 
  26.  * @email:[email protected] 
  27.  * @version 0.1 
  28.  */  
  29. public class Map {  
  30.     private int[][] mapArray = null;  
  31.     private int size = 0;  
  32.     private int maxX = 0;  
  33.     private int maxY = 0;  
  34.     private int tile = 32;  
  35.     private Image[] mapImages;  
  36.     /** 
  37.      * 加载指定地图文件为list 
  38.      *  
  39.      * @param fileName 
  40.      * @return 
  41.      * @throws IOException 
  42.      */  
  43.     private static List loadList(final String fileName) throws IOException {  
  44.         BufferedReader reader = new BufferedReader(new InputStreamReader(  
  45.                 Utility.getResource(fileName)));  
  46.         List records = new ArrayList(10);  
  47.         String result = null;  
  48.         try {  
  49.             // 分解地图设定点  
  50.             while ((result = reader.readLine()) != null) {  
  51.                 char[] charArray = result.toCharArray();  
  52.                 int size = charArray.length;  
  53.                 int[] intArray = new int[size];  
  54.                 for (int i = 0; i < size; i++) {  
  55.                     intArray[i] = Character.getNumericValue(charArray[i]);  
  56.                 }  
  57.                 records.add(intArray);  
  58.             }  
  59.         } finally {  
  60.             if (reader != null) {  
  61.                 try {  
  62.                     reader.close();  
  63.                 } catch (IOException e) {  
  64.                 }  
  65.             }  
  66.         }  
  67.         return records;  
  68.     }  
  69.     /** 
  70.      * 加载地图文件为整型二维数组 
  71.      *  
  72.      * @param fileName 
  73.      * @return 
  74.      * @throws IOException 
  75.      */  
  76.     public static int[][] loadArray(final String fileName) throws IOException {  
  77.         // 取得地图二维数组(此时row,col颠倒)  
  78.         List list = loadList(fileName);  
  79.         int row = list.size();  
  80.         int[][] mapArray = new int[row][];  
  81.         for (int i = 0; i < row; i++) {  
  82.             mapArray[i] = (int[]) list.get(i);  
  83.         }  
  84.         int col = (((int[]) mapArray[row > 0 ? row - 1 : 0]).length);  
  85.         // 颠倒二维数组row,col  
  86.         int[][] result = new int[col][row];  
  87.         for (int j = 0; j < col; j++) {  
  88.             for (int i = 0; i < row; i++) {  
  89.                 result[i][j] = mapArray[j][i];  
  90.             }  
  91.         }  
  92.         return result;  
  93.     }  
  94.     /** 
  95.      * 构造地图 
  96.      *  
  97.      * @param size 
  98.      * @param fileName 
  99.      */  
  100.     public Map(final String fileName, final int tile) {  
  101.         try {  
  102.             this.mapArray = Map.loadArray(fileName);  
  103.         } catch (IOException e) {  
  104.             throw new RuntimeException(e);  
  105.         }  
  106.         this.size = this.mapArray.length;  
  107.         this.tile = tile;  
  108.         this.maxX = this.size;  
  109.         this.maxY = (((int[]) this.mapArray[this.maxX > 0 ? this.maxX - 1 : 0]).length);  
  110.         this.mapImages = Utility.getSplitImages("image/map.png", tile, tile);  
  111.     }  
  112.     /** 
  113.      * 获得地图图像 
  114.      *  
  115.      * @return 
  116.      */  
  117.     public Image getMapImage() {  
  118.         Image image = Utility.createImage(maxX * tile, maxY * tile, true);  
  119.         Graphics graphics = image.getGraphics();  
  120.         for (int y = 0; y <= maxY - 1; y++) {  
  121.             for (int x = 0; x <= maxX - 1; x++) {  
  122.                 int type = getMapType(x, y);  
  123.                 graphics.drawImage(mapImages[type], x * tile, y * tile, null);  
  124.             }  
  125.         }  
  126.         graphics.dispose();  
  127.         return image;  
  128.     }  
  129.     public int[][] getMaps() {  
  130.         return mapArray;  
  131.     }  
  132.     public int getMaxX() {  
  133.         return maxX;  
  134.     }  
  135.     public int getMaxY() {  
  136.         return maxY;  
  137.     }  
  138.     /** 
  139.      * 获得地图指定坐标点对象 
  140.      *  
  141.      * @param x 
  142.      * @param y 
  143.      * @return 
  144.      */  
  145.     public int getMapType(int x, int y) {  
  146.         /*if (x < 0) { 
  147.             x = 0; 
  148.         } 
  149.         if (y < 0) { 
  150.             y = 0; 
  151.         } 
  152.         if (x > maxX - 1) { 
  153.             x = maxX - 1; 
  154.         } 
  155.         if (y > maxY - 1) { 
  156.             y = maxY - 1; 
  157.         }*/  
  158.         return mapArray[x][y];  
  159.     }  
  160.     /** 
  161.      * 返回指定坐标地形 
  162.      *  
  163.      * @param x 
  164.      * @param y 
  165.      * @return 
  166.      */  
  167.     public int getMapCost(int x, int y) {  
  168.         int type = getMapType(x, y);  
  169.         switch (type) {  
  170.         case 0:  
  171.             type = 1// 草  
  172.             break;  
  173.         case 1:  
  174.             type = 2// 树  
  175.             break;  
  176.         case 2:  
  177.             type = 3// 山地  
  178.             break;  
  179.         case 3:  
  180.             type = -1// 湖泽(不能进入)  
  181.             break;  
  182.         }  
  183.         return type;  
  184.     }  
  185. }   
package org.loon.simple.slg.ai;import java.awt.Graphics;import java.awt.Image;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;/** * Copyright 2008 - 2009 *  * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at *  * http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. *  * @project loonframework * @author chenpeng * @email:[email protected] * @version 0.1 */public class Map { private int[][] mapArray = null; private int size = 0; private int maxX = 0; private int maxY = 0; private int tile = 32; private Image[] mapImages; /**  * 加载指定地图文件为list  *   * @param fileName  * @return  * @throws IOException  */ private static List loadList(final String fileName) throws IOException {  BufferedReader reader = new BufferedReader(new InputStreamReader(    Utility.getResource(fileName)));  List records = new ArrayList(10);  String result = null;  try {   // 分解地图设定点   while ((result = reader.readLine()) != null) {    char[] charArray = result.toCharArray();    int size = charArray.length;    int[] intArray = new int[size];    for (int i = 0; i < size; i++) {     intArray[i] = Character.getNumericValue(charArray[i]);    }    records.add(intArray);   }  } finally {   if (reader != null) {    try {     reader.close();    } catch (IOException e) {    }   }  }  return records; } /**  * 加载地图文件为整型二维数组  *   * @param fileName  * @return  * @throws IOException  */ public static int[][] loadArray(final String fileName) throws IOException {  // 取得地图二维数组(此时row,col颠倒)  List list = loadList(fileName);  int row = list.size();  int[][] mapArray = new int[row][];  for (int i = 0; i < row; i++) {   mapArray[i] = (int[]) list.get(i);  }  int col = (((int[]) mapArray[row > 0 ? row - 1 : 0]).length);  // 颠倒二维数组row,col  int[][] result = new int[col][row];  for (int j = 0; j < col; j++) {   for (int i = 0; i < row; i++) {    result[i][j] = mapArray[j][i];   }  }  return result; } /**  * 构造地图  *   * @param size  * @param fileName  */ public Map(final String fileName, final int tile) {  try {   this.mapArray = Map.loadArray(fileName);  } catch (IOException e) {   throw new RuntimeException(e);  }  this.size = this.mapArray.length;  this.tile = tile;  this.maxX = this.size;  this.maxY = (((int[]) this.mapArray[this.maxX > 0 ? this.maxX - 1 : 0]).length);  this.mapImages = Utility.getSplitImages("image/map.png", tile, tile); } /**  * 获得地图图像  *   * @return  */ public Image getMapImage() {  Image image = Utility.createImage(maxX * tile, maxY * tile, true);  Graphics graphics = image.getGraphics();  for (int y = 0; y <= maxY - 1; y++) {   for (int x = 0; x <= maxX - 1; x++) {    int type = getMapType(x, y);    graphics.drawImage(mapImages[type], x * tile, y * tile, null);   }  }  graphics.dispose();  return image; } public int[][] getMaps() {  return mapArray; } public int getMaxX() {  return maxX; } public int getMaxY() {  return maxY; } /**  * 获得地图指定坐标点对象  *   * @param x  * @param y  * @return  */ public int getMapType(int x, int y) {  /*if (x < 0) {   x = 0;  }  if (y < 0) {   y = 0;  }  if (x > maxX - 1) {   x = maxX - 1;  }  if (y > maxY - 1) {   y = maxY - 1;  }*/  return mapArray[x][y]; } /**  * 返回指定坐标地形  *   * @param x  * @param y  * @return  */ public int getMapCost(int x, int y) {  int type = getMapType(x, y);  switch (type) {  case 0:   type = 1; // 草   break;  case 1:   type = 2; // 树   break;  case 2:   type = 3; // 山地   break;  case 3:   type = -1; // 湖泽(不能进入)   break;  }  return type; }} 

 

  GameCanvas.java(战场绘制及各种事件处理)

 

[java] view plain copy print ?
  1. package org.loon.simple.slg.ai;  
  2. import java.awt.Canvas;  
  3. import java.awt.Color;  
  4. import java.awt.Dimension;  
  5. import java.awt.Graphics;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.Image;  
  8. import java.awt.event.KeyEvent;  
  9. import java.awt.event.KeyListener;  
  10. import java.util.ArrayList;  
  11. import java.util.Collections;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.util.Random;  
  15. /** 
  16.  * Copyright 2008 - 2009 
  17.  *  
  18.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
  19.  * use this file except in compliance with the License. You may obtain a copy of 
  20.  * the License at 
  21.  *  
  22.  * http://www.apache.org/licenses/LICENSE-2.0 
  23.  *  
  24.  * Unless required by applicable law or agreed to in writing, software 
  25.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
  26.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
  27.  * License for the specific language governing permissions and limitations under 
  28.  * the License. 
  29.  *  
  30.  * @project loonframework 
  31.  * @author chenpeng 
  32.  * @email:[email protected] 
  33.  * @version 0.1 
  34.  */  
  35. public class GameCanvas extends Canvas implements Runnable, KeyListener {  
  36.     /** 
  37.      *  
  38.      */  
  39.     private static final long serialVersionUID = 1L;  
  40.     // 地图  
  41.     private Map map = null;  
  42.     // 菜单  
  43.     private Menu menu = null;  
  44.     // 背景窗体  
  45.     private Image screen;  
  46.     // 地图图片  
  47.     private Image mapImage;  
  48.     private Graphics2D graphics;  
  49.     private String state;  
  50.     private int lastX;  
  51.     private int lastY;  
  52.     private int curX;  
  53.     private int curY;  
  54.     private int turn = 1;  
  55.     private int actionUnit = -1;  
  56.     private int moveCount = 0;  
  57.     private int[][] moveList;  
  58.     private int[][] movingList;  
  59.     private int[][] attackList;  
  60.     private int maxX;  
  61.     private int maxY;  
  62.     private List unitList = Collections.synchronizedList(new ArrayList(10));  
  63.     // 战斗个体图  
  64.     private Image[] unitImages = Utility.getSplitImages("image/unit.png", tile,  
  65.             tile);  
  66.     private Image[] iconImages = Utility.getSplitImages("image/icon.png", tile,  
  67.             tile);  
  68.     private Image[] listImages = Utility.getSplitImages("image/list.png", tile,  
  69.             tile);  
  70.     private Thread gameLoop;  
  71.     private int eventCode = -1;  
  72.     final static int tile = 32;  
  73.     public GameCanvas() {  
  74.         actionUnit = -1;  
  75.         state = "战斗开始";  
  76.         turn = 1;  
  77.         this.setBackground(Color.BLACK);  
  78.         this.map = new Map("map.txt", tile);  
  79.         // 地图  
  80.         this.mapImage = this.map.getMapImage();  
  81.         this.maxX = map.getMaxX();  
  82.         this.maxY = map.getMaxY();  
  83.         this.moveList = new int[maxX][maxY];  
  84.         this.movingList = new int[maxX][maxY];  
  85.         this.attackList = new int[maxX][maxY];  
  86.         int width = maxX * tile;  
  87.         int height = maxY * tile;  
  88.         // 菜单  
  89.         this.menu = new Menu(maxX - 1);  
  90.         // 创建角色:name=空罐少女,team=0(我军),imageindex=3,x=7,y=1,以下雷同  
  91.         createRole("空罐少女"00371);  
  92.         createRole("猫猫1"01612);  
  93.         createRole("猫猫2"00326);  
  94.         // 创建角色:name=躲猫兵团1,team=1(敌军),imageindex=6,x=4,y=5,以下雷同  
  95.         createRole("躲猫兵团1"12445);  
  96.         createRole("躲猫兵团2"12485);  
  97.         createRole("躲猫兵团3"12457);  
  98.         createRole("躲猫兵团4"12472);  
  99.         this.screen = Utility.createImage(width, height, true);  
  100.         this.graphics = (Graphics2D) screen.getGraphics();  
  101.         // 初始化  
  102.         this.initRange();  
  103.         // 绘制图像  
  104.         this.drawBattle();  
  105.         this.setPreferredSize(new Dimension(width - 2, height - 2));  
  106.         this.setFocusable(true);  
  107.         this.addKeyListener(this);  
  108.         // 开始构建游戏  
  109.         this.mainLoop();  
  110.     }  
  111.     public void mainLoop() {  
  112.         gameLoop = new Thread(this);  
  113.         gameLoop.start();  
  114.     }  
  115.     public void run() {  
  116.         for (;;) {  
  117.             long start = System.currentTimeMillis();  
  118.             long end = System.currentTimeMillis();  
  119.             long time = end - start;  
  120.             long sleepTime = 20L - time;  
  121.             if (sleepTime < 0L) {  
  122.                 sleepTime = 0L;  
  123.             }  
  124.             this.eventClick();  
  125.             try {  
  126.                 Thread.sleep(sleepTime);  
  127.             } catch (InterruptedException e) {  
  128.             }  
  129.         }  
  130.     }  
  131.     /** 
  132.      * 事件触发 
  133.      *  
  134.      */  
  135.     public synchronized void eventClick() {  
  136.         switch (eventCode) {  
  137.         // 按下Enter,开始触发游戏事件  
  138.         case KeyEvent.VK_ENTER:  
  139.             int index = 0;  
  140.             // 当游戏状态为[状态显示]下  
  141.             if (state.equalsIgnoreCase("状态显示")) {  
  142.                 // 光标指向我方未行动角色  
  143.                 index = getRoleIdx(0, curX, curY);  
  144.                 if ((index > -1) && (getRole(index).action == 0)) {  
  145.                     state = "角色移动";  
  146.                     actionUnit = getRoleIdx(0, curX, curY);  
  147.                     // 绘制移动范围  
  148.                     setMoveRange();  
  149.                     movingList[curX][curY] = moveCount;  
  150.                     drawBattle();  
  151.                     // 光标指向敌方未行动角色  
  152.                 } else if (getRoleIdx(1, curX, curY) > -1) {  
  153.                     state = "移动范围";  
  154.                     actionUnit = getRoleIdx(1, curX, curY);  
  155.                     setMoveRange();  
  156.                     drawBattle();  
  157.                     // 查看角色情报  
  158.                 } else {  
  159.                     state = "情报查看";  
  160.                     openMenu(0);  
  161.                     drawBattle();  
  162.                 }  
  163.             }  
  164.             // 选择移动  
  165.             else if (state.equalsIgnoreCase("角色移动")) {  
  166.                 // 无法移动的区域  
  167.                 if (moveList[curX][curY] < 0) {  
  168.                     return;  
  169.                 }  
  170.                 // 监测移动地点  
  171.                 if ((getRoleIdx(0, curX, curY) == -1)  
  172.                         || (moveList[curX][curY] == 0)) {  
  173.                     lastX = getRole(actionUnit).x;  
  174.                     lastY = getRole(actionUnit).y;  
  175.                     moveRole();  
  176.                     state = "行动菜单";  
  177.                     // 绘制攻击范围  
  178.                     setAttackRange(true);  
  179.                     // 判定菜单项  
  180.                     if (isAttackCheck()) {  
  181.                         openMenu(2);  
  182.                     } else {  
  183.                         openMenu(1);  
  184.                     }  
  185.                     drawBattle();  
  186.                 }  
  187.             }  
  188.             // 当角色移动后  
  189.             else if (state.equalsIgnoreCase("行动菜单")) {  
  190.                 if (menu.getMenuItem(menu.cur).equalsIgnoreCase("攻击")) {  
  191.                     state = "进行攻击";  
  192.                     closeMenu();  
  193.                     drawBattle();  
  194.                 } else if (menu.getMenuItem(menu.cur).equalsIgnoreCase("待机")) {  
  195.                     state = "状态显示";  
  196.                     closeMenu();  
  197.                     getRole(actionUnit).action = 1;  
  198.                     actionUnit = -1;  
  199.                     initRange();  
  200.                     drawBattle();  
  201.                 }  
  202.             }  
  203.      &nb

    给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

    Java版战棋(SLG)游戏AI及寻径处理入门_第1张图片

你可能感兴趣的:(Java版战棋(SLG)游戏AI及寻径处理入门)