Розробка ігрової програми для мобільних пристроїв з сенсорним екраном студента 4 курсу
Вид материала | Документы |
СодержаниеСписок використаних джерел Додаток: Код програми |
- Реферат роботи, 161.95kb.
- О. Л. Нечипорук „, 369.83kb.
- Методична розробка уроків та вимоги до неї, 75.68kb.
- Формат опису модуля, 51.04kb.
- Реферат метою роботи є обґрунтування та розробка ефективних технологій ведення гірничих, 201.97kb.
- Розробка програми просування товару на ринок Розробка стратегій розвитку підприємства, 24.48kb.
- Орієнтована на студента І базується на його навчальному навантажені, необхідному для, 91.14kb.
- Цей курс є одним з базових І охоплює широке коло пристроїв електронної техніки, які, 144.55kb.
- Організація самостійної роботи студентів, 563.53kb.
- Формулювання вимог до програми 7 2 Проектування програми 7 3 Кодування програми, 390.59kb.
Список використаних джерел
- Горнаков С.Г. «Програмирование мобильних телефонов на Java 2 Micro Edition» – М.: ДМК Пресс, 2004
- David Fox, Roman Verhosek «Micro Java Game Development» - Addison Wesley, 2002
- MIDP Programming with J2ME: ссылка скрыта
- Мухин И. А. Сенсорные экраны — решение проблем (10 технологий). «BROADCASTING Телевидение и радиовещение»: 1 часть — № 3(55) май 2006, с.50-52; 2 часть — № 4(56) июнь-июль 2006, с.40-41; 3 часть — № 7(59) ноябрь 2006, с.64-66.
- Офіційний сайт Java Platform, Micro Edition : ссылка скрыта
- Офіційний сайт середовища розробки NetBeans IDE : ссылка скрыта
Додаток: Код програми
// GameField.java
import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.TiledLayer;
public class GameField {
static final int GRASS = 1;
static final int ROAD = 2;
static final int HOME = 3;
int[][] field;
TiledLayer tl;
public GameField(int[][] field) {
this.field = field;
createLayer(field.length, field[0].length,100,0);
}
// генерує поле по замовчуванню
public GameField() {
int n = 10;
int m = 15;
field = new int[n][m];
for (int i=0; i
for (int j=0; j
field[i][j]=GRASS;
field[0][0] = HOME;
field[0][1] = ROAD;
field[0][2] = ROAD;
field[1][2] = ROAD;
field[2][2] = ROAD;
field[3][2] = ROAD;
field[4][2] = ROAD;
field[4][3] = ROAD;
field[1][3] = ROAD;
field[1][4] = ROAD;
field[2][4] = ROAD;
field[3][4] = ROAD;
field[4][4] = ROAD;
field[4][5] = ROAD;
field[4][6] = ROAD;
field[4][7] = ROAD;
field[5][7] = ROAD;
field[6][7] = ROAD;
field[7][7] = ROAD;
field[8][7] = ROAD;
field[8][8] = ROAD;
field[8][9] = ROAD;
field[8][10] = ROAD;
field[8][11] = ROAD;
field[8][12] = ROAD;
field[8][13] = ROAD;
field[9][13] = ROAD;
field[9][14] = ROAD;
createLayer(n, m,100,0);
}
private void createLayer(int n,int m,int x0,int y0){
try {
tl = new TiledLayer(m, n, Image.createImage("/field.png"), 36, 36);
} catch (IOException ex) {
ex.printStackTrace();
}
tl.setPosition(x0, y0);
for (int i=0; i
for (int j=0; j
tl.setCell(j, i, field[i][j]);
}
public void paint(Graphics g){
tl.paint(g);
}
public point getCellij(int x,int y){
x -= tl.getX();
y -= tl.getY();
return new point(x / tl.getCellWidth(),y /tl.getCellHeight());
}
public TrekBuilder genTrekBuilder(){
TrekBuilder tb = new TrekBuilder(36,36,tl.getX(),tl.getY());
tb.buildTreks(field, 9, 14);
return tb;
}
public point getCellXY(point p){
return new point(p.x*tl.getCellWidth()+tl.getX(), p.y*tl.getCellHeight()+tl.getY());
}
public boolean isCellAvailable(int i, int j){
return ((j >=0 && j
}
public void checkCell(point p){
p = getCellij(p.x, p.y);
String s = (field[p.x][p.y] == GRASS)?"Grass":"";
s = (field[p.x][p.y] == ROAD)?"road":s;
s = (field[p.x][p.y] == HOME)?"home":s;
System.out.println(s + " ("+p.x + " " + p.y + ")");
}
}
// Menu.java
import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class Menu {
Image bgimg,changeimg,sellimg;
TDCanvas pc;
boolean sell = false;
public Menu( TDCanvas pc) {
this.pc = pc;
try {
bgimg = Image.createImage("/menu.png");
changeimg = Image.createImage("/change.png");
sellimg = Image.createImage("/sell.png");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void changeState(boolean sell){
this.sell = sell;
}
public boolean isSell(){
return sell;
}
public void paint(Graphics g){
g.drawImage(bgimg, 0, 0, Graphics.TOP|Graphics.LEFT);
if (sell) g.drawImage(sellimg, 7, 188, Graphics.TOP|Graphics.LEFT);
else g.drawImage(changeimg, 7, 188, Graphics.TOP|Graphics.LEFT);
}
public void pressed(int x,int y){
if (x>7 && x<83 && y>188 && y<264) {
if (sell) {
pc.removeCur();
sell = false;
}
else pc.changeCurTower();
}
}
}
// MenuCanvas.java
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
public class MenuCanvas extends Canvas{
int cenX = 0;
int cenY = 0;
int selected;
String[] options = {"Campaign","Survival","Exit"};
TDGame tdg;
public MenuCanvas(TDGame tdg) {
super();
this.tdg = tdg;
setFullScreenMode(true);
cenX = getWidth()/2;
cenY = getHeight()/2;
}
public void pointerPressed (int x, int y) {
if (x > cenX)
if (y >cenY) select();
else cancel();
else
if (y >cenY) down();
else up();
}
protected void paint(Graphics g) {
g.setGrayScale (255);
g.setColor(10, 200, 100);
g.fillRect (0, 0, getWidth(), getHeight());
g.setGrayScale (0);
for (int i=0; i
if (i == selected) g.setColor(200, 20, 10);
g.drawString (options[i], cenX - cenX/2, i*15,Graphics.TOP|Graphics.LEFT);
g.setColor(0,0,0);
}
g.drawString ("ok", 5+ cenX + cenX/2, 5+ cenY + cenY/2,Graphics.TOP|Graphics.LEFT);
g.drawString ("cancel", 5+ cenX + cenX/2,cenY/2 - 5,Graphics.TOP|Graphics.LEFT);
g.drawString ("up", 2, cenY/2 - 5, Graphics.TOP|Graphics.LEFT);
g.drawString ("down", 2, 5+ cenY + cenY/2, Graphics.TOP|Graphics.LEFT);
}
protected void up(){
selected = (selected>0)?selected-1:options.length-1;
repaint();
}
protected void down(){
selected = (selected
repaint();
}
protected void select(){
switch(selected){
case 0:
Display.getDisplay(tdg).setCurrent(new TDCanvas(tdg, TDCanvas.CAMPAIGN));
break;
case 1:
Display.getDisplay(tdg).setCurrent(new TDCanvas(tdg, TDCanvas.SURVIVAL));
break;
case 2:
tdg.destroyApp(false);
tdg.notifyDestroyed();
break;
}
}
protected void cancel(){
if (tdg.canContinue()) tdg.continueGame();
}
}
// Monster.java
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;
public class Monster {
Sprite sp;
int speed;
int maxspeed;
int minspeed = 1;
int hp;
int dmg;
int gold;
Trek tr;
public Monster(int speed, int hp, int dmg, int gold, Image img) {
this.speed = speed;
this.hp = hp;
this.dmg = dmg;
this.gold = gold;
sp = new Sprite(img,36,36);
}
public void SetXY(int x,int y){
sp.setPosition(x, y);
}
public void SetXY(point p){
sp.setPosition(p.x, p.y);
}
public void paint(Graphics g){
sp.paint(g);
if (sp.getFrame() != 0) sp.setFrame(0);
else sp.setFrame(1);
}
public void setTrek(Trek tr){
this.tr = tr;
SetXY(tr.getNext());
}
public boolean move(){
Speed();
boolean res = moveWith(speed);
return res;
}
private boolean moveWith(int step){
if (tr.isEmty()) {
// видалити монстра
hp = 0;
return false;
}
else{
point pto = tr.getNext();
point cur = new point(sp.getX(),sp.getY());
if (cur.equals(pto)) {
tr.delNext();
move();
}
else{
int step1 = 0;
if (pto.x > cur.x) {
step1 = changeStep(cur.x,pto.x,step);
cur.x+=step1;
step-= step1;
}
if (pto.x < cur.x) {
step1 = changeStep(cur.x,pto.x,step);
cur.x-=step;
step-= step1;
}
if (pto.y > cur.y) {
step1 = changeStep(cur.y,pto.y,step);
cur.y+=step;
step-= step1;
}
if (pto.y < cur.y) {
step1 = changeStep(cur.y,pto.y,step);
cur.y-=step;
step-= step1;
}
SetXY(cur);
if (step !=0) moveWith(step);
}
return true;
}
}
private int changeStep(int f,int t,int step){
int dist = Math.abs(f-t);
if (dist
else return step;
}
public point getCentPosition(){
return new point(sp.getX()+sp.getWidth()/2,sp.getY()+sp.getHeight()/2);
}
public point getPosition(){
return new point(sp.getX(),sp.getY());
}
public void hit(int d){
hp -= d;
if (!isAlive()) {
tr.st.removeAllElements();
}
sp.setFrame(2);
}
public void hitSpeed(int d){
speed -= d;
if (speed < minspeed) speed = minspeed;
}
private void Speed(){
if (speed < maxspeed) speed += 1;
}
public boolean isAlive(){
return (hp>0);
}
public int getHp(){
return hp;
}
public void setHp(int hp){
this.hp = hp;
}
}
// MonsterFactory.java
public interface MonsterFactory {
public Monster genNext();
}
// Monsters.java
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
public class Monsters {
Vector mar = new Vector();
TDCanvas pc;
public Monsters(TDCanvas pc ){
this.pc = pc;
}
public void add(Monster m){
mar.addElement(m);
}
public void move(){
for (int i=0; i
Monster m = ((Monster)mar.elementAt(i));
if (m.isAlive()) m.move();
else {
mar.removeElementAt(i);
point p = m.getPosition();
if (p.x == 100 && p.y == 0) pc.hp -= m.dmg;
else pc.gold += m.gold;
}
}
}
public Monster[] getArray(){
Monster[] oar = new Monster[mar.size()];
mar.copyInto(oar);
return oar;
}
public void paint(Graphics g){
for (int i=0; i
((Monster)mar.elementAt(i)).paint(g);
}
}
}
//SimpleFactory.java
import java.util.Random;
import javax.microedition.lcdui.Image;
public class SimpleFactory implements MonsterFactory{
TrekBuilder tb;
Image img;
point start;
public SimpleFactory(TrekBuilder tb,Image img) {
this.tb = tb;
this.img = img;
}
public Monster genNext() {
Random r = new Random();
int speed = r.nextInt(8)+2;
Monster m = new Monster(speed, 30, 7, 3, img);
m.setTrek(tb.randTrek());
return m;
}
}
// SimpleTower.java
import javax.microedition.lcdui.Image;
public class SimpleTower extends Tower{
public SimpleTower(int xp, int dmg, int range, int gold, int cooldown,Image img){
super(xp, dmg,range,gold, cooldown,img,"damages\n one");
}
public boolean attack(Monster[] m){
sp.setFrame(0);
for (int i=0; i
if (isInRange(m[i])) {
m[i].hit(dmg);
sp.setFrame(1);
return true;
}
}
return false;
}
protected void upgrade() {
if (xp % 20 == 0) dmg ++;
if (xp % 30 == 0) range ++;
}
}
// SpeedTower.java
import javax.microedition.lcdui.Image;
public class SpeedTower extends Tower{
public SpeedTower(int xp, int dmg, int range, int gold, int cooldown,Image img){
super(xp, dmg,range,gold, cooldown,img,"damages\n speed");
}
public boolean attack(Monster[] m){
sp.setFrame(0);
for (int i=0; i
if (isInRange(m[i])) {
m[i].hitSpeed(dmg);
sp.setFrame(1);
return true;
}
}
return false;
}
protected void upgrade() {
if (xp % 20 == 0 && cooldown>0) cooldown--;
if (xp % 30 == 0) range++;
}
}
// SplashTower.java
import javax.microedition.lcdui.Image;
public class SplashTower extends Tower{
public SplashTower(int xp, int dmg, int range, int gold, int cooldown,Image img){
super(xp, dmg,range,gold, cooldown,img,"splash\n damage");
}
public boolean attack(Monster[] m){
boolean hit = false;
sp.setFrame(0);
for (int i=0; i
if (isInRange(m[i])) {
m[i].hit(dmg);
sp.setFrame(1);
hit = true;
}
}
return hit;
}
protected void upgrade() {
if (xp % 20 == 0 && cooldown>0) cooldown--;
if (xp % 30 == 0) dmg++;
}
}
// TDGame.java
import java.util.Random;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.GameCanvas;
public class TDGame extends MIDlet
{
private Display display;
public void startApp(){
display = Display.getDisplay(this);
display.setCurrent (new MenuCanvas(this));
}
public void pauseApp(){}
public void destroyApp (boolean forced){}
private TDCanvas PausedGame = null;
public void setToPause(TDCanvas tdc){
PausedGame = tdc;
}
public boolean canContinue(){
return (PausedGame != null);
}
public void continueGame(){
Display.getDisplay(this).setCurrent(PausedGame);
PausedGame.continueGame();
PausedGame = null;
}
}
class TDCanvas extends GameCanvas implements Runnable{
Image img, im1,im2,im3,mimg;
Thread t;
GameField gf = new GameField();
TrekBuilder tb;
Towers tws;
MonsterFactory mf;
Monsters ms;
public static int hp = 100;
TDGame pe;
Menu m = new Menu(this);
long startTime = System.currentTimeMillis();
int gold = 100;
public static final int SURVIVAL = 0;
public static final int CAMPAIGN = 1;
public TDCanvas(TDGame pe, int mode){
super(true);
setFullScreenMode(true);
this.pe = pe;
try {
img = Image.createImage("/monstr_fastt.png");
im1 = Image.createImage("/tower_simple.png");
im2 = Image.createImage("/tower_speed.png");
im3 = Image.createImage("/tower_splash.png");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
tb = gf.genTrekBuilder();
mf = new SimpleFactory(tb, img);
tws = new Towers();
ms = new Monsters(this);
ms.add(mf.genNext());
t = new Thread(this);
t.start();
}
int curTower = -1;
public void removeCur(){
gold += tws.remove(curTower);
}
public void pointerPressed (int x, int y) {
if (x>100) {
curTower = tws.check(new point(x,y));
if (curTower == -1) {
tws.moveNew(x, y);
m.changeState(false);
tws.changeState(false);
}
else {
m.changeState(true);
tws.changeState(true);
}
}
else {
if (y<90) {
pause = true;
pe.setToPause(this);
Display.getDisplay(pe).setCurrent(new MenuCanvas(pe));
}
m.pressed(x, y);
}
}
int simple = 0;
public void changeCurTower(){
simple ++;
if (simple > 2) simple =0;
setCurTower(simple);
}
public void setCurTower(int simple){
if (simple == 0) tws.tryNew(new SimpleTower(0, 7, 36, 10, 5, im1));
else if (simple == 1) tws.tryNew(new SpeedTower(0, 2, 36, 20, 5, im2));
else tws.tryNew(new SplashTower(0, 4, 36, 15, 10, im3));
}
public void pointerReleased (int x, int y) {
if (!m.isSell()) {
int res = tws.put(gf,gold);
if (res!=-1){
gold = res;
setCurTower(simple);
}
}
}
public void pointerDragged (int x, int y) {
tws.moveNew(x, y);
}
public void painting(Graphics g){
g.setGrayScale (255);
g.fillRect (0, 0, getWidth(), getHeight());
g.setGrayScale (0);
g.drawRect (0, 0, getWidth(), getHeight());
gf.paint(g);
ms.paint(g);
m.paint(g);
tws.paint(g);
if (m.isSell()) tws.paintInfo(g, 7,101, curTower);
int c = g.getColor();
g.setColor(0, 230, 25);
g.drawString (" hp:"+ hp, 6, 10,Graphics.TOP|Graphics.LEFT);
g.setColor(255, 245, 48);
g.drawString ("Gold:"+ gold, 6, 25,Graphics.TOP|Graphics.LEFT);
g.setColor(255, 10, 10);
g.drawString ("Mons:"+ 25, 6, 40,Graphics.TOP|Graphics.LEFT);
g.setColor(10, 10, 210);
int tm = (int) ((System.currentTimeMillis()-startTime)/1000);
int min = (tm/60)%60;
int sec = tm%60;
g.drawString ("Time:"+ min+":"+sec, 5, 55,Graphics.TOP|Graphics.LEFT);
g.setColor(c);
flushGraphics();
}
public void continueGame(){
pause = false;
}
private boolean pause = false;
public void run() {
int k = 0;
Graphics g = getGraphics();
int addgoldtime = 0;
while (true){
if (!pause){
int add = (int)(System.currentTimeMillis()/1000);
if (add%2 == 0 && add!= addgoldtime){
addgoldtime = add;
gold ++;
Monster[] mar = ms.getArray();
tws.act(mar);
ms.move();
k++;
Random r = new Random();
if (k % (r.nextInt(5)+5) == 0){
k = 0;
ms.add(mf.genNext());
}
painting(g);
}
}
try {
Thread.sleep(80);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
if (hp <= 0) break;
}
g.setColor(255, 0, 120);
g.drawString ("G A M E O V E R", 30, 30,Graphics.TOP|Graphics.LEFT);
flushGraphics();
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
pe.destroyApp(false);
pe.notifyDestroyed();
}
}
83>