---
title: "Java版SLG游戏开发入门[0]--让绘制的窗口响应鼠标事件"
author: "mmdev"
date: "2008-10-15T00:46:00Z"
tags: []
slug: "java-slg-0"
draft: false
lastmod: "2012-04-14T20:09:46Z"
id: 1486242
url: "https://mmdev.iteye.com/blog/1486242"
---

什么是SLG呢？也就是Simulation Game的缩写，即模拟策略游戏。

以我这种准骨灰级玩家的视点来看（鄙人88年开始玩FC，时年6岁），早期的SLG游戏，大体只是《三国志》(Ｉ由1985年开始发售)这类发布指令扩充军备并战斗的“命令下达式游戏”，并没有什么分类上的难度。但自从《火焰纹章》(1990年开始发售）出现伊始，即策略游戏与传统RPG的分野变得模糊起来，这种具有故事情节的战棋策略游戏，同时兼具了SLG及RPG的双特性，以后的岁月中人们习惯分类其为——SRPG，火焰系列也据此被后人视作SRPG的鼻祖游戏之一。但事实上讲，此类游戏仍旧具备着传统SLG那样如同下棋般战斗并采用回合制的特点，RPG的情节部分仅仅是作为游戏内容的补充罢了，始终摆脱不掉传统策略游戏地图-〉指令-〉战斗的大框架，故此客观上依然应被划入了SLG范围。再后来，随着电脑的普及，如大众软件这些媒体杂志又把文明和模拟城市乃至美少女梦工厂这样的游戏也划分进SLG里，但按照现在的说法，足球经理、模拟人生应该是“SIM”，即单纯的Simulation，而美少女梦工厂则是TCG——不过在日式游戏划分中，这些依然都属于SLG。

就鄙人看来，强分策略类游戏类型是没有什么意义的，作为最初源泉的SLG是能够包含SRPG、RTS种种分支的。就好比有的人是博士、有的人是硕士，但我们依旧可以将其统称为“知识分子”，划到一个大圈子里面去。又比如我们平时可能常说“上海人怎样”、“北京人如何”，但当我说“中国人”时，自然能够将这些都包罗其中，无论好坏，谁都脱身不得。 而在此类游戏中，包含策略因素的这个大圈子的统一称谓，便是SLG无疑。

实际上，绝大多数英文站点也是将此类游戏统一丢到Simulation Game下的（包括模拟城市之类的纯SIM），并没有进行SRPG(Strategies Role Play Games)或RTS(Real-Time Strategy Game)乃至其余种种的细分。归根究底，因为这些游戏近似的因素太多，在大多数时候已经难以区分其本来面貌，“名无实，实无名”，只能一概而论了。而今有不少新生代玩家喜欢硬分游戏种类，窃以为愚了。

——————————————————————————————————————————————————————————

闲话说了不少，现在开始进入正题。在本系列中，我将结合实例尝试以Java实现典型战棋类SLG的主要功能，本文为第0节，也就是准备章节。

看过我以前写的RPG及ACT系列的朋友们，应该已对Java中2D图形绘制功能有了初步的认识，在本文中，我将阐述如何令绘制的窗体而非组件响应鼠标事件，及如何在窗体中自定义非标准大小的鼠标指针，作为本系列的预备知识。

首先，我们都知道，在Java中可以通过Cursor组件自定义游标样式，比如下图有一组取材自Langrisser2的光标图片。

![](http://p.blog.csdn.net/images/p_blog_csdn_net/cping1982/EntryImages/20081015/cursor.png)

在Java桌面开发中，我们可以通过分解这组图片来得到小图，以此来自定义鼠标光标。

但是有一个问题，这时无论图片原始大小如何，至多也只能是32x32大小，如果超出这个范围，则无法作为游标在窗体中完整显示。

也就是说，如上图这样46x46的大图，要么缩小显示，要么局部显示，总之46x46的状态下是无法完整的显示在窗体中的。

可我们明明见到很多游戏中的光标是不规则不成比例的，究竟如何做到呢？其实很简单，自己绘制就好了。

绝大多数不合规矩的东西，我们都可以自己把它“画出来”，只要能确定它的坐标。

**如下代码记录了键盘及鼠标状态下的图标移动：**

01. /\**
02. \*键盘事件设置
03. \*
04. \*/
05. publicvoidsetKeyset(){
06. addKeyListener(newKeyAdapter(){
07. publicvoidkeyTyped(KeyEvente){
08. }
09. publicvoidkeyReleased(KeyEvente){
10. }
11. publicvoidkeyPressed(KeyEvente){
12. if(e.getKeyCode()==KeyEvent.VK\_RIGHT){
13. currentX=currentX+move;
14. }
15. if(e.getKeyCode()==KeyEvent.VK\_LEFT){
16. currentX=currentX-move;
17. }
18. if(e.getKeyCode()==KeyEvent.VK\_UP){
19. currentY=currentY-move;
20. }
21. if(e.getKeyCode()==KeyEvent.VK\_DOWN){
22. currentY=currentY+move;
23. }
24. repaint();
25. }
26. });
27. }
28. /\**
29. \*鼠标事件设置
30. \*
31. \*/
32. publicvoidsetMouse(){
33. addMouseListener(newMouseAdapter(){
34. publicvoidmousePressed(MouseEvente){
35. }
36. publicvoidmouseReleased(MouseEvente){
37. }
38. });
39. addMouseMotionListener(newMouseMotionAdapter(){
40. publicvoidmouseMoved(MouseEventex){
41. currentX=ex.getX();
42. currentY=ex.getY();
43. repaint();
44. }
45. publicvoidmouseDragged(MouseEventex){
46. currentX=ex.getX();
47. currentY=ex.getY();
48. repaint();
49. }
50. });
51. }

此时，我们只需将光标在指定位置drawImage一下，自然就会得到想要的结果。但是有一点需要注意，那就是系统的Cursor此时还存在，如果我们不进行处理，画面上会出现两个游标的尴尬局面。但是Java并没有提供给我们直接取消光标的方法，这时该怎么办呢？很简单，我们将其“隐形”即可。

**比如这样：**

1. CursorFramef=newCursorFrame();
2. int\[]pixels=newint\[256];
3. Imageimage=Toolkit.getDefaultToolkit().createImage(
4. newMemoryImageSource(16,16,pixels,0,16));
5. CursortransparentCursor= Toolkit.getDefaultToolkit()
6. .createCustomCursor(image,newPoint(0,0),"hidden");
7. f.setCursor(transparentCursor);

我们绘制一张16x16的透明图作为游标，在使用者看来，就只能见到我们drawImage出的“伪游标”罢了。

**现在我们据此制作一个假单的仿Langrisser2开始界面，代码如下：**

001. packageorg.slg.simple;
002. importjava.awt.Color;
003. importjava.awt.Cursor;
004. importjava.awt.Graphics;
005. importjava.awt.Graphics2D;
006. importjava.awt.Image;
007. importjava.awt.Panel;
008. importjava.awt.Point;
009. importjava.awt.Toolkit;
010. importjava.awt.event.KeyAdapter;
011. importjava.awt.event.KeyEvent;
012. importjava.awt.event.MouseAdapter;
013. importjava.awt.event.MouseEvent;
014. importjava.awt.event.MouseMotionAdapter;
015. importjava.awt.image.BufferedImage;
016. importjava.awt.image.MemoryImageSource;
017. /\**
018. \*Copyright2008
019. \*
020. \*LicensedundertheApacheLicense,Version2.0(the"License");youmaynot
021. \*usethisfileexceptincompliancewiththeLicense.Youmayobtainacopyof
022. \*theLicenseat
023. \*
024. \*http://www.apache.org/licenses/LICENSE-2.0
025. \*
026. \*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
027. \*distributedundertheLicenseisdistributedonan"ASIS"BASIS,WITHOUT
028. \*WARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.Seethe
029. \*Licenseforthespecificlanguagegoverningpermissionsandlimitationsunder
030. \*theLicense.
031. \*
032. \*@projectloonframework
033. \*@authorchenpeng
034. \*@email：ceponline@yahoo.com.cn
035. \*@version0.1
036. \*/
037. publicclassExemplePanelextendsPanel{
038. /\**
039. \*
040. \*/
041. privatestaticfinallongserialVersionUID=1L;
042. finalstaticintcurrentWidth=480;
043. finalstaticintcurrentHeight=360;
044. //背景缓冲图
045. finalImage\_background;
046. //鼠标指针图形组
047. finalImage\[]\_mouses;
048. //背景图
049. finalImage\_backgroundImage;
050. Graphics\_backgroundGraphics;
051. Image\_mouse;
052. Image\_arrow;
053. //选中项，默认指向第一条
054. int\_select=1;
055. //游标x轴
056. int\_currentX=0;
057. //游标y轴
058. int\_currentY=0;
059. int\_move=5;
060. publicExemplePanel(){
061. //创建一个背景缓存用image
062. \_background=newBufferedImage(currentWidth,currentHeight,
063. BufferedImage.TYPE\_INT\_ARGB);
064. //导入开始时背景图像
065. \_backgroundImage=Utility.loadImage("image/start.gif");
066. //导入光标图系列，以列宽46读取到image数组
067. \_mouses=Utility.getImageColumns(
068. Utility.loadImage("image/cursor.png"),46);
069. //初始背景为黑色
070. setBackground(newColor(0,0,0));
071. \_arrow=Utility.loadImage("image/arrow.png");
072. \_backgroundGraphics=\_background.getGraphics();
073. //设定键盘监听
074. setKeyset();
075. //设定鼠标监听
076. setMouse();
077. //设置鼠标动画（本例只是一个简单示例，实际应根据相应事件变更游标造型）
078. ThreadmouseAnimation=newThread(){
079. publicvoidrun(){
080. intcursorMax=\_mouses.length;
081. intcursorIndex=0;
082. do{
083. if(cursorIndex&lt;cursorMax){
084. \_mouse=\_mouses\[cursorIndex];
085. try{
086. Thread.sleep(500);
087. }catch(InterruptedExceptione){
088. e.printStackTrace();
089. }
090. repaint();
091. }else{
092. cursorIndex=0;
093. }
094. cursorIndex++;
095. }while(true);
096. }
097. };
098. //开启鼠标动画
099. mouseAnimation.start();
100. }
101. publicvoidpaint(Graphicsg){
102. //绘制背景
103. \_backgroundGraphics.drawImage(\_backgroundImage,0,0,this);
104. //绘制光标
105. \_backgroundGraphics.drawImage(\_mouse,\_currentX,\_currentY,this);
106. drawTitle((Graphics2D)\_backgroundGraphics);
107. //加载缓存图
108. g.drawImage(\_background,0,0,this);
109. }
110. publicvoidupdate(Graphicsg){
111. paint(g);
112. }
113. /\**
114. \*键盘事件设置
115. \*
116. \*/
117. publicvoidsetKeyset(){
118. addKeyListener(newKeyAdapter(){
119. publicvoidkeyTyped(KeyEvente){
120. }
121. publicvoidkeyReleased(KeyEvente){
122. }
123. publicvoidkeyPressed(KeyEvente){
124. if(e.getKeyCode()==KeyEvent.VK\_RIGHT){
125. \_currentX=\_currentX+\_move;
126. }
127. if(e.getKeyCode()==KeyEvent.VK\_LEFT){
128. \_currentX=\_currentX-\_move;
129. }
130. if(e.getKeyCode()==KeyEvent.VK\_UP){
131. \_currentY=\_currentY-\_move;
132. }
133. if(e.getKeyCode()==KeyEvent.VK\_DOWN){
134. \_currentY=\_currentY+\_move;
135. }
136. repaint();
137. }
138. });
139. }
140. /\**
141. \*鼠标事件设置
142. \*
143. \*/
144. publicvoidsetMouse(){
145. int\[]pixels=newint\[256];
146. Imageimage=Toolkit.getDefaultToolkit().createImage(
147. newMemoryImageSource(16,16,pixels,0,16));
148. //制作一个透明的游标
149. CursortransparentCursor=Toolkit.getDefaultToolkit()
150. .createCustomCursor(image,newPoint(0,0),"hidden");
151. //插入透明游标，以此模拟无游标状态
152. setCursor(transparentCursor);
153. addMouseListener(newMouseAdapter(){
154. publicvoidmousePressed(MouseEvente){
155. if(e.getButton()==1){
156. State.l\_clk=true;
157. }
158. if(e.getButton()==3){
159. State.r\_clk=true;
160. }
161. }
162. publicvoidmouseReleased(MouseEvente){
163. if(e.getButton()==1){
164. State.l\_clk=false;
165. }
166. if(e.getButton()==3){
167. State.r\_clk=false;
168. }
169. }
170. });
171. addMouseMotionListener(newMouseMotionAdapter(){
172. publicvoidmouseMoved(MouseEventex){
173. \_currentX=ex.getX();
174. \_currentY=ex.getY();
175. repaint();
176. }
177. publicvoidmouseDragged(MouseEventex){
178. \_currentX=ex.getX();
179. \_currentY=ex.getY();
180. repaint();
181. }
182. });
183. }
184. /\**
185. \*绘制标题选项
186. \*
187. \*@paramg
188. \*/
189. voiddrawTitle(Graphics2Dg){
190. Utility.font(g,15,1);
191. Utility.color(g,0,0,0);
192. if(\_select!=0){
193. g.drawImage(\_arrow,168,227+\_select\*20,null);
194. }
195. //PS:如果不想在程序中绘制，也可以直接在准备好的背景图上写文字，pc版的Langrisser就是那样......
196. g.drawString("开始新游戏",195,260);
197. g.drawString("载入记录",203,280);
198. g.drawString("退出游戏",203,300);
199. for(inti=0;i&lt;3;i++){
200. if(\_currentX&gt;195&&\_currentX&lt;270&&\_currentY&gt;i\*20+235
201. &&\_currentY&lt;i\*20+275){
202. \_select=i+1;
203. }
204. }
205. repaint();
206. Utility.wait(20);
207. if(State.l\_clk&&!State.lock\_lck){
208. State.lock\_lck=true;
209. if(\_select==1){
210. System.out.println("您选择了：开始");
211. }
212. if(\_select==2){
213. System.out.println("您选择了：继续");
214. }
215. if(\_select==3){
216. System.out.println("您选择了：结束");
217. System.exit(0);
218. }
219. }
220. if(!State.l\_clk&&State.lock\_lck){
221. State.lock\_lck=false;
222. }
223. }
224. }

**运行效果如下图：**

![](http://p.blog.csdn.net/images/p_blog_csdn_net/cping1982/EntryImages/20081015/20081014_slg_02.gif)

**当您看见此行文字时，我的CSDN上传功能还无法使用……**