标签:
说了是简单版贪吃蛇。。。
就3个类+方向枚举变量(本来想写贪吃蛇斜着走的。。想象我的蛇是矩形 斜着难看就没写)
上下左右键控制移动 空格暂停
SnackClient类
package com.xynu.snaker; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; public class SnackClient extends JFrame { private static SnackClient sc; private SnackBody snackFood; //当前游戏状态 private boolean gameState = true; private MyComponent mc; //游戏 private boolean pause = false; private JMenu menu; private JMenuBar menubar; //低等级 private JMenuItem lowSpeedItem; //中等级 private JMenuItem midSpeedItem; //高等级 private JMenuItem heightSpeedItem; //重新开始 private JMenuItem restartItem; public int speed = 15; static int score = 0; private MaxScore ms; //蛇身子 ArrayList<SnackBody> snackBodys = new ArrayList<SnackBody>(); //蛇头 static SnackBody snackHead; private static final long serialVersionUID = 1L; public SnackClient() { //初始化菜单栏 initMenu(); mc = new MyComponent(); mc.setBackground(Color.BLACK); add(mc); setTitle("贪吃蛇"); setSize(800, 600); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setResizable(false); snackHead = new SnackBody(100, 100, this); for (int i = 0; i < 2; i++) { snackBodys.add(new SnackBody(-100, -100, this)); } ms = new MaxScore(); showSnackFood(); addKeyListener(new MyKeyListener()); new paintThread().start(); } private void initMenu() { // TODO Auto-generated method stub menu = new JMenu("参数设置"); lowSpeedItem = new JMenuItem("低等级"); midSpeedItem = new JMenuItem("中等级"); heightSpeedItem = new JMenuItem("高等级"); restartItem=new JMenuItem("重新开始"); lowSpeedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub speed = 15; } }); midSpeedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub speed = 17; } }); heightSpeedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub speed = 20; } }); restartItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub dispose(); sc=new SnackClient(); } }); menu.add(lowSpeedItem); menu.add(midSpeedItem); menu.add(heightSpeedItem); menu.add(restartItem); menubar = new JMenuBar(); menubar.add(menu); setJMenuBar(menubar); } public boolean isPause() { return pause; } public void setPause(boolean pause) { this.pause = pause; } public static void main(String[] args) { // TODO Auto-generated method stub sc = new SnackClient(); } public class MyComponent extends JPanel { /** * */ private static final long serialVersionUID = 1L; protected void paintComponent(Graphics g) { // TODO Auto-generated method stub super.paintComponent(g); if (!gameState) { Font font = new Font("微软雅黑", Font.BOLD, 50); g.setFont(font); g.setColor(Color.RED); g.drawString("GAME OVER!!", this.getWidth() / 2 - 150, this.getHeight() / 2); return; } // 如果蛇撞到蛇身 或 撞墙 游戏结束 if (snackHead.hitWall() || snackHead.hitSnackBody(snackBodys)) { gameState = false; } // 如果蛇头吃到食物 if (snackHead.hitSnackBody(snackFood)) { snackBodys.add(snackFood); score++; // 刷新食物 showSnackFood(); } // 画食物 snackFood.draw(g); // 画蛇身 if (gameState) { for (SnackBody sb : snackBodys) { sb.draw(g); } } // 画蛇头 if (gameState) { snackHead.draw(g); } try { g.drawString( "当前分数:" + score * 100 + " 游戏最高分:" + ms.getMaxScore(), 0, 10); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //随机出现食物 public void showSnackFood() { Random r = new Random(); boolean exit = true; while (exit) { int x = r.nextInt(mc.getWidth() - snackHead.getWidth()); int y = r.nextInt(mc.getHeight() - snackHead.getHeight()); snackFood = new SnackBody(x, y, sc); if (snackFood.hitSnackBody(snackHead) || snackFood.hitSnackBody(snackBodys)) { continue; } exit = false; } } //键盘事件 public class MyKeyListener extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub snackHead.keyPress(e); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub snackHead.keyRelease(e); } } //游戏刷新 public class paintThread extends Thread { public void run() { // TODO Auto-generated method stub while (true) { if (!pause) { repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }
封装的蛇身SnackBody类
package com.xynu.snaker; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.geom.Rectangle2D; import java.util.ArrayList; public class SnackBody { private int x; private int y; private int speed = 15; private int width = 15; private int height = 15; private boolean left, right, up, down; private Direction dir = Direction.D, curdir = Direction.D; private SnackClient sc; public SnackBody() { super(); // TODO Auto-generated constructor stub } public SnackBody(int x, int y, SnackClient sc) { super(); this.x = x; this.y = y; this.sc = sc; } 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 int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public Direction getDir() { return dir; } public void draw(Graphics g) { Graphics2D g2 = (Graphics2D) g; Rectangle2D r2 = new Rectangle2D.Double(x, y, width, height); //蛇身为黄色 g2.setColor(Color.YELLOW); //蛇头为红色 if (this == SnackClient.snackHead) g2.setColor(Color.RED); g2.fill(r2); if (this == SnackClient.snackHead) { this.speed = sc.speed; move(); } } //键盘事件 public void keyPress(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_RIGHT: right = true; break; case KeyEvent.VK_LEFT: left = true; break; case KeyEvent.VK_UP: up = true; break; case KeyEvent.VK_DOWN: down = true; break; case KeyEvent.VK_SPACE: sc.setPause(!sc.isPause()); break; } judgeDir(); } //判断方向 如果你想八个方向移动也是同理 private void judgeDir() { // TODO Auto-generated method stub if (left && !right && !up && !down) curdir = Direction.L; if (!left && right && !up && !down) curdir = Direction.R; if (!left && !right && up && !down) curdir = Direction.U; if (!left && !right && !up && down) curdir = Direction.D; } /* * 蛇体的移动根据蛇身移动 * 第一节蛇身等于蛇头移动前的位置 * 第二节蛇身等于第一节蛇身移动前的位置 * 以此类推 */ private void move() { if (dir == Direction.L && curdir == Direction.R) curdir = dir; if (dir == Direction.R && curdir == Direction.L) curdir = dir; if (dir == Direction.U && curdir == Direction.D) curdir = dir; if (dir == Direction.D && curdir == Direction.U) curdir = dir; if (dir != curdir) dir = curdir; int preX = x; int preY = y; if (dir == Direction.L) { x -= speed; preX += 1; } if (dir == Direction.R) { x += speed; preX -= 1; } if (dir == Direction.U) { y -= speed; preY += 1; } if (dir == Direction.D) { y += speed; preY -= 1; } int tempX, tempY; for (SnackBody body : sc.snackBodys) { tempX = body.getX(); tempY = body.getY(); body.setX(preX); body.setY(preY); preX = tempX; preY = tempY; } } public void keyRelease(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_RIGHT: right = false; break; case KeyEvent.VK_LEFT: left = false; break; case KeyEvent.VK_UP: up = false; break; case KeyEvent.VK_DOWN: down = false; break; } } //返回蛇身矩形 public Rectangle getRec() { return new Rectangle(x, y, width, height); } //蛇头和蛇身的碰撞事件 public boolean hitSnackBody(SnackBody sb) { if (this == sb) return false; if (this.getRec().intersects(sb.getRec())) { return true; } return false; } public boolean hitSnackBody(ArrayList<SnackBody> snackBodys) { for (SnackBody snackBody : snackBodys) { if (this != snackBody) { if (hitSnackBody(snackBody)) { return true; } } } return false; } public boolean hitWall() { if (x <= 0 || y <= 0 || x >= sc.getWidth() - width || y >= sc.getHeight() - height) { return true; } return false; } }最高分MaxScore类
package com.xynu.snaker; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class MaxScore { public int getMaxScore() throws IOException{ File file=new File("maxScore.txt"); if(!file.exists()){ file.createNewFile(); } BufferedReader br=new BufferedReader(new FileReader(file)); String s=br.readLine(); int max=0; if(!"".equals(s)&&s!=null){ max=Integer.parseInt(s); } else{ max=0; } if(SnackClient.score*100>max){ max=SnackClient.score*100; BufferedWriter bw=new BufferedWriter(new FileWriter(file)); bw.write(max+""); bw.close(); } br.close(); return max; } }运行结果
标签:
原文地址:http://blog.csdn.net/su20145104009/article/details/52132582