📄 gamehandle.java
字号:
package org.loon.chair.example6;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
/**
*
* @author chenpeng
* @email ceponline@yahoo.com.cn
*
* Loon Framework in Game
*
*/
public class GameHandle implements Common{
// 用于获得加载图像的实例
private Image image;
//角色坐标
private int x, y;
//增加计步器
private int count;
//新增变量,用以确认角色所对方向,对应按键触发
private int direction;
//用于处理角色动画的线程
private Thread threadAnime;
//游戏地图
private GameMap map;
//面板
private MyPanel panel;
/**
* 构造函数,拼合所需素材
* @param x
* @param y
* @param filename
* @param map
* @param panel
*/
public GameHandle(int x, int y, String filename, GameMap map, MyPanel panel) {
this.x = x;
this.y = y;
direction = DOWN;
count = 0;
this.map = map;
this.panel = panel;
//加指定图像
loadImage(filename);
//实例化内部线程AnimationThread
threadAnime = new Thread(new AnimationThread());
threadAnime.start();
}
//自Example6开始,为了实现背景的移动,所有算法都要加入偏移值
public void draw(Graphics g, int offsetX, int offsetY) {
//以count作为图像的偏移数值,并于Example4中添加direction以获取所处图像块位置
g.drawImage(image, x * CS + offsetX, y * CS + offsetY, x * CS + offsetX + CS, y * CS + offsetY + CS,
count * CS, direction * CS, CS + count * CS, direction * CS + CS, panel);
}
/**
* 判断移动事件,关联isAllow()函数
* 在Example4中,添加了对于移动方向的整型记录变量direction
* @param event
*/
public void move(int event) {
//以转换器判断相关事件,仅执行符合[规范]的操作。
switch (event) {
case LEFT:
//依次判定事件
if (map.isAllow(x-1, y)) x--;
direction = LEFT;
break;
case RIGHT:
if (map.isAllow(x+1, y)) x++;
direction = RIGHT;
break;
case UP:
if (map.isAllow(x, y-1)) y--;
direction = UP;
break;
case DOWN:
if (map.isAllow(x, y+1)) y++;
direction = DOWN;
break;
default:
break;
}
}
private void loadImage(String filename) {
ImageIcon icon = new ImageIcon(getClass().getResource(filename));
image = icon.getImage();
}
// 内部类,用于处理计步动作。
private class AnimationThread extends Thread {
public void run() {
while (true) {
// count计步
if (count == 0) {
count = 1;
} else if (count == 1) {
count = 0;
}
// 重绘画面。
panel.repaint();
// 每300毫秒改变一次动作。
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -