将对象尽量的抽象,能够有效减小代码量,好比此例中的Star类java
package com.test084_087_solar; import java.awt.Graphics; import java.awt.Image; import com.test084_087_util.GameUtil; public class Star { Image img; double x,y; public void draw(Graphics g){ g.drawImage(img,(int)x,(int)y,null); } public Star(Image img,double x,double y){ this.img = img; this.x = x; this.y = y; } public Star(String imgpath,double x,double y){ this.img = GameUtil.getImage(imgpath); this.x = x; this.y = y; } }
构建常量类的好处相似CSS,改一个地方,其它地方都改了,例如此例中的Constant.GAME_WIDTH。this
package com.test084_087_util; /** * @author wangtao * 游戏项目中用到的常量 */ public class Constant { public static final int GAME_WIDTH = 800; public static final int GAME_HEIGHT = 600; }
paint会在对象加载时自动调用。code
package com.test084_087_solar; import java.awt.Graphics; import java.awt.Image; import com.test084_087_util.Constant; import com.test084_087_util.GameUtil; import com.test084_087_util.MyFrame; public class SolarFrame extends MyFrame { Image bg = GameUtil.getImage("images/bg.jpg"); Star sun = new Star("images/sun.jpg",Constant.GAME_WIDTH/2,Constant.GAME_HEIGHT/2); public void paint(Graphics g){ g.drawImage(bg,0,0,null); sun.draw(g); } public static void main(String[] args){ new SolarFrame().launchFrame(); } }