坦克游戏教程二:实现坦克移动以及方向控制

今天实现了可以通过键盘的游戏键控制坦克的移动,以及可以控制其方向位置改变。同时可以绘制多辆敌方坦克。

代码如下:

/*
 * Function: TankGame 1.0
 * Draw Tank
*/
package com.test1;

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.*;

public class MyTankGame1 extends JFrame {
	
	MyPanel mp = null;
	
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		MyTankGame1 myTankGame1 = new MyTankGame1();

	}
	
	public MyTankGame1(){
		mp = new MyPanel();
		this.add(mp);
		this.addKeyListener(mp);
		this.setSize(400, 300);
		this.setVisible(true);
	}

}

//My Planel
class MyPanel extends JPanel implements KeyListener{
	//Define a Tank
	Hero  hero = null;
	
	// define enemy tank group
	Vector ets = new Vector();
	
	int ensize = 3;
	
	
	public MyPanel(){
		hero = new Hero(100, 100);
		
		for(int i = 0; i < ensize; i++){
			EnemyTank et = new EnemyTank(i * 50,  0);
			et.setColor(0);
			et.setDirect(2);
			ets.add(et);
		}
	}
	
	public void paint(Graphics g){
		super.paint(g);
		// Draw my tank. And then encapsulate them into functions.
		g.fillRect(0, 0, 400, 300);
		this.drawTank(hero.getX(), hero.getY(), g, hero.getDirect(), 0);
		
		for(int i = 0; i 

package com.test1;

public class Members {

}


//Tank Class
class Tank{
	
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	int x = 0;
	int y = 0;
	public int getDirect() {
		return direct;
	}

	public void setDirect(int direct) {
		this.direct = direct;
	}

	int direct = 0;
	int speed = 2;
	int color;
	
	// 0:up 
	// 1:down
	// 2:right
	// 3:left
	
	public int getColor() {
		return color;
	}

	public void setColor(int color) {
		this.color = color;
	}

	public int getSpeed() {
		return speed;
	}

	public void setSpeed(int speed) {
		this.speed = speed;
	}

	public Tank(int x, int y){
		this.x = x ;
		this.y = y ;
	}
}

class EnemyTank extends Tank {

	public EnemyTank(int x, int y) {
		super(x, y);
		// TODO 自动生成的构造函数存根
	}
	
}

class Hero extends Tank{
	public Hero(int x, int y){
		super(x, y);
	}
	
	//tank move to direction up
	public void moveUp(){
		this.y -= speed;
	}
	public void moveDown(){
		this.y += speed;
	}
	
	public void moveLeft(){
		this.x -= speed;
	}
	
	public void moveRight(){
		this.x += speed;
	}
}

运行效果图:

坦克游戏教程二:实现坦克移动以及方向控制_第1张图片坦克游戏教程二:实现坦克移动以及方向控制_第2张图片

你可能感兴趣的:(Java)