?? 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 + -