자바 탐식 사

이 게임 을 디자인 할 때 먼저 메 인 화면 인 SnakeUI 류 를 만 듭 니 다.이 유형 에서 메 인 화면 에 대한 수식,뱀의 초기 화,음식의 초기 화,키보드 의 감청 사건 을 만들어 야 합 니 다.
1,SnakeUI 클래스
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class SnakeUI extends JFrame implements KeyListener {
	private BufferedImage uiImg = new BufferedImage(Constant.JFRAME_WIDTH,
			Constant.JFRAME_HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
	private Rectangle rec;
	private SNode food;
	private Snake snake; //      
	private static int SPEED = Constant.SNAKE_NORMAL;

	public SnakeUI() {
		this.rec = Constant.rec;
		this.food = new SNode(Color.BLUE);
		this.snake = new Snake(this);//       
		this.launchFrame();
	}

	//          
	public SNode getFood() {
		return food;
	}

	private void launchFrame() {
		this.setTitle("   V0.1");
		this.setBounds(200, 100, Constant.JFRAME_WIDTH, Constant.JFRAME_HEIGHT);
		this.setVisible(true);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		new Thread(new UIUpdate()).start(); //       
		this.addKeyListener(this); //       
	}

	public void paint(Graphics g) {
		// 1.      。g.drawRect      [   ]

		// 2.          ,       Frame ,      
		//        ,    uiImg  ,           
		Graphics2D g2d = (Graphics2D) uiImg.getGraphics();
		//           
		g2d.setColor(Color.WHITE);
		g2d.fillRect(0, 0, this.getWidth(), this.getHeight());

		//       
		g2d.setColor(Color.BLACK);
		g2d.drawRect((int) this.rec.getX(), (int) this.rec.getY(),
				(int) this.rec.getWidth(), (int) this.rec.getHeight());

		//       
		g2d.setColor(Color.CYAN);
		int startx = (int) this.rec.getX();
		int starty = (int) this.rec.getY();
		for (int i = 0; i < 35; i++) {
			for (int j = 0; j < 50; j++) {
				g2d.drawRect(startx + j * Constant.FOOD_WIDTH, starty + i
						* Constant.FOOD_HEIGHT, Constant.FOOD_WIDTH,
						Constant.FOOD_HEIGHT);
			}
		}

		//       
		g2d.setColor(Color.RED);
		g2d.setFont(new Font("  ", Font.ITALIC, 16));//     
		g2d.drawString("       2019", 580, 530);

		//    ,  paint   SNode   , UI    paint     
		this.food.paint(g2d);

		//   
		this.snake.paint(g2d);

		//       :       ,                ,           
		if (this.snake.eat(this.food)) {
			this.food = new SNode(Color.BLUE);
			while (this.snake.hit(this.food)) {
				this.food = new SNode(Color.BLUE);
			}
		}
		g.drawImage(uiImg, 0, 0, null); //      
	}

	public static void main(String[] args) {
		new SnakeUI();
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	//                
	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
		switch (key) {
		case KeyEvent.VK_LEFT:
			snake.setDir(Constant.L);
			System.out.println("dddl");
			break;
		case KeyEvent.VK_RIGHT:
			snake.setDir(Constant.R);
			System.out.println("dddr");
			break;
		case KeyEvent.VK_UP:
			snake.setDir(Constant.U);
			System.out.println("dddu");
			break;
		case KeyEvent.VK_DOWN:
			snake.setDir(Constant.D);
			break;
		case KeyEvent.VK_W:
			SPEED = Constant.SNAKE_ADD;
			break;
		case KeyEvent.VK_D:
			SPEED = Constant.SNAKE_NORMAL;
			break;
		case KeyEvent.VK_S:
			SPEED = Constant.SNAKE_SUB;
			break;
		case KeyEvent.VK_T:
			SPEED = Constant.SNAKE_SUPER;
			break;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		SPEED = Constant.SNAKE_NORMAL; 
	}

	//          
	class UIUpdate implements Runnable { 
		@Override
		public void run() {
			while (SnakeUI.this.snake.isLive()) {
				System.out.println("..............thread....");
				SnakeUI.this.repaint();
				//          ,           1 。
				try {
					Thread.sleep(SPEED);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			JOptionPane.showMessageDialog(SnakeUI.this, "    ,game over.");			
		}
	}
}

2,뱀 뱀
실례 화 뱀 이라는 종 류 는 list 집합 을 사용 하여 뱀의 각 부분 을 저장 하고 표시 하 는 것 이다.
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

public class Snake {
	private SNode snakeHead; //     
	private int startx, starty; //      
	private List nodes = new ArrayList(); //    , SNode    :
														//    List
	private int dir; //   
	private boolean isLive = true; //        
	
	//        ,      3   
	private int speed = 3;

	// getter.setter    
	public int getDir() {
		return dir;
	}

	public void setDir(int dir) {
		this.dir = dir;
	}

	//         ,             
	public Snake(SnakeUI ui) {
		this.dir = Constant.U;
		this.noOverride(ui.getFood());
	}

	//                
	public void noOverride(SNode food) {
		this.generateSnake();
		while (this.hit(food)) { //       
			this.generateSnake();
		}
	}

	private void generateSnake() {
		int x = SNode.generate(50); // [0,49)
		int y = SNode.generate(35);
		if (x == 0) {
			x += 1;
		} else if (x == 49) {
			x -= 1;
		}
		if (y == 0) {
			y += 1;
		} else if (y == 34) {
			y -= 1;
		}
		this.startx = ((int) Constant.rec.getX() + x * Constant.FOOD_WIDTH);
		this.starty = ((int) Constant.rec.getY() + y * Constant.FOOD_HEIGHT);
		this.snakeHead = new SNode(this.startx, this.starty, Color.GREEN);
		nodes.add(snakeHead);
		this.addNode(); //    2   ,    1   
	}

	//             :true:   ,false:   
	public boolean hit(SNode food) {
		boolean result = false;
		for (SNode snode : nodes) {
			boolean res = snode.getRec().intersects(food.getRec());
			if (res) {
				result = true;
				break;
			}
		}
		return result;
	}

	//    
	public boolean eat(SNode food) {
		boolean result = false;
		for (SNode snode : nodes) {
			boolean res = snode.getRec().intersects(food.getRec());
			if (res) {
				result = true;
				if (nodes.size() >= 2) { // 1.    ,2.      
					this.addNode(); //       1
				}
				break;
			}
		}
		return result;
	}

	//            ,      
	private void addNode() {
		int size = nodes.size();
		switch (dir) {
		case Constant.L: //    ,      2   ,     
			if (size == 1) { //    ,           
				int x = this.startx + Constant.FOOD_WIDTH;
				int y = this.starty;
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(snode); //        
			} else {
				int x = this.startx - Constant.FOOD_WIDTH;
				int y = this.starty;				
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(0, snode);
				this.snakeHead = snode;
				this.startx = x;
				this.starty = y;
				//        
				if (this.startx < Constant.rec.getX()) {
					this.isLive = false;
				}
			}
			break;
		case Constant.R:
			if (size == 1) { //    ,           
				int x = this.startx - Constant.FOOD_WIDTH;
				int y = this.starty;
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(snode); //        
			} else {
				int x = this.startx + Constant.FOOD_WIDTH;
				int y = this.starty;
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(0, snode);
				this.snakeHead = snode;
				this.startx = x;
				this.starty = y;
				//       
				if (this.startx > Constant.GAME_WIDTH) { 
					this.isLive = false;
				}
			}
			break;
		case Constant.U:
			if (size == 1) { //    ,           
				int x = this.startx;
				int y = this.starty + Constant.FOOD_HEIGHT;
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(snode); //        
			} else {
				int x = this.startx;
				int y = this.starty - Constant.FOOD_HEIGHT;
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(0, snode);
				this.snakeHead = snode;
				this.startx = x;
				this.starty = y;
				//        
				if (this.starty < Constant.rec.getY()) {
					this.isLive = false;
				}
			}
			break;
		case Constant.D:
			if (size == 1) { //    ,           
				int x = this.startx;
				int y = this.starty - Constant.FOOD_HEIGHT;						
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(snode); //        
			} else {
				int x = this.startx;
				int y = this.starty + Constant.FOOD_HEIGHT;	
//				int y = this.starty + this.speed;
				SNode snode = new SNode(x, y, Color.GREEN);
				nodes.add(0, snode);
				this.snakeHead = snode;
				this.startx = x;
				this.starty = y;
				//       
				if (this.starty > ((int)Constant.rec.getY()+ Constant.GAME_HEIGHT-Constant.FOOD_HEIGHT)) {
					this.isLive = false;
				}
			}
			break;
		}

	}

	public boolean isLive() {
		return isLive;
	}

	//     ,      ,    
	private void move() {
		this.addNode(); //         ,      
		int len = nodes.size();
		nodes.remove(len - 1);
	}

	//        
	public void paint(Graphics2D g2d) {
		//  nodes      
		g2d.setColor(this.snakeHead.getColor());

		//          
		for (SNode snode : nodes) {
			g2d.fillRect(snode.getX(), snode.getY(), Constant.FOOD_WIDTH,
					Constant.FOOD_HEIGHT);
		}
		this.move();
	}
}

3,SNode 음식 류
음식 류 를 설계 하 는 것 도 뱀 류 에 대한 간소화 라 고 할 수 있다.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

//      :
public class SNode {
	private int x,y;     //       ,         
	private Color color; //     
	private Rectangle rec; //       
	
	public Color getColor() {
		return color;
	}

	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;
	}

	public Rectangle getRec() {
		return rec;
	}

	public void setRec(Rectangle rec) {
		this.rec = rec;
	}

	//           
	public SNode(Color color) {
		this.x = (int)Constant.rec.getX()+this.generate(50)*Constant.FOOD_WIDTH;
		this.y = (int)Constant.rec.getY()+this.generate(35)*Constant.FOOD_HEIGHT;
		this.rec = new Rectangle(this.x, this.y, Constant.FOOD_WIDTH, Constant.FOOD_HEIGHT);
		this.color = color; 
	}
	
	//         ,      
	public SNode(int x,int y,Color color) {
		this.x = x;
		this.y = y;
		this.color = color;
		this.rec = new Rectangle(this.x, this.y, Constant.FOOD_WIDTH, Constant.FOOD_HEIGHT);
	}
	
	//      
	public static int generate(int number) { //[0,numbder)
		int x = 0;
		x = (int)(Math.random()*number);
		return x;
	}
	
	//        :        Graphics2D
	public void paint(Graphics2D g2d) {
		g2d.setColor(this.color);
        g2d.fillRect(this.x, this.y, Constant.FOOD_WIDTH, Constant.FOOD_HEIGHT);
	}
	
	public static void main(String[] args) {
		
	}

}


4,Constant 상수 류
사용 해 야 할 상수 에 저장 하여 전체 인터페이스 에 대한 수정 을 편리 하 게 합 니 다.
import java.awt.Rectangle;


public class Constant {
	public static final int FOOD_WIDTH = 15; //         

	public static final int FOOD_HEIGHT = 15;
	
	public static final int GAME_WIDTH = FOOD_WIDTH*50;
	
	public static final int GAME_HEIGHT = FOOD_HEIGHT*35;
	
	public static final int JFRAME_WIDTH = FOOD_WIDTH*52;
	
	public static final int JFRAME_HEIGHT = FOOD_HEIGHT*38+6;
	
	public static final int L=1,R=2,U=3,D=4;
	
	public static final int SNAKE_NORMAL = 500;
	
	public static final int SNAKE_ADD = 180;
	
	public static final int SNAKE_SUPER = 50;
	
	public static final int SNAKE_SUB = 850;
	
	//      
	public static final Rectangle rec = new Rectangle(FOOD_WIDTH, FOOD_HEIGHT*2+6, GAME_WIDTH, GAME_HEIGHT);

}

좋은 웹페이지 즐겨찾기