Beginner in Java GUI programming. So I am playing a Snake game to practice what I learned.
For an object-oriented programming language such as Java, you must analyze the corresponding objects and methods before writing the program.
This little game contains the following objects: Snake, food, game controller, and game panel.
Next we will analyze the attributes and methods contained in these objects.
First, analyze the object of the snake:
The attributes of a snake are: the snake's body, the color of the snake's body, the length of the snake's body, the snake's life, and the direction of the snake's movements.
In a snake-Greedy game, a snake seeks food and increases its body through its movements in all directions to ensure the normal operation of the game.
At this time, there will be several methods in the object of the snake: the method of moving the snake, the method of eating the snake
Then analyze the food object:
Food has two attributes: Color and location, and the way to generate food.
The preliminary code plan looks like this:
// Snake. javapackage Org. sysit. game. snake; import Java. AWT. color; import Java. AWT. point; import Java. util. arraylist; import Java. util. list; public class snake {private int length; private color; private list <point> body = new arraylist (); Private Boolean life = true; /*** snake movement direction ** @ author zhangbing **/Enum dir {up, right, down, left}; private dir snkedir; /*** initialize the snake ** @ Param length the length of the snake body */Public snake (INT length) {} public void move () {}/*** determine whether a snake eats food * @ Param head * @ return */Public Boolean issnkeeatfood (point head) {return true ;}}
// Food. javapackage Org. sysit. game. snake; import Java. AWT. color; import Java. AWT. point; public class food {private color; private point location;/*** generate the food location * @ Param snake * @ return returns point */Public point setlocation (Snake snake) {return NULL ;}}
The following code is added to each method:
In the object "snake", we should first complete the initialization code of the Snake. Here, I save each section of the snake body to the list of the snake body in the form of points.
/*** Initialize the Snake ** @ param length the length of the Snake body */public Snake (int length) {this. length = length; this. color = Color. YELLOW; for (int I = length; I> 0; I --) {body. add (new Point (0, I-1);} snkedir = dir. RIGHT ;}
The core of the next step should be the snake movement method. A large part of my code still needs to be improved. My method is to merge multiple operations into one method, make changes by yourself
Public void move () {Point head = new Point (body. get (0 ). x, body. get (0 ). y); switch (snail Kedir) {case UP: head. x --; break; case DOWN: head. x ++; break; case LEFT: head. y --; break; case RIGHT: head. y ++; break;} int canvas_width = SysConfig. CANVAS_WIDTH/SysConfig. STONE_WIDTH-2; int canvas_height = SysConfig. CANVAS_HEIGHT/SysConfig. STONE_HEIGHT-2; if (head. x <0 | head. canvas_height-1 | head. y <0 | head. y > Canvas_width-1) {life = false; // snake dieJOptionPane. showMessageDialog (null, "end of game"); return;} else {body. add (0, head); if (issnkeeatfood (head) {// No food body has been eaten. remove (body. size ()-1);} else {getFood (). setLocation (this); setScore (getScore () + 10);} for (int I = 1; I <= body. size ()-1; I ++) {Point point = body. get (I); if (point. x = head. x & point. y = head. y) {life = false; JOptionPane. showMessageDialog (null, "hit Yourself ~ Game ended "); // System. exit (0); return ;}}}}
/*** Determine whether a snake eats food * @ param head * @ return */public boolean issnkeeatfood (Point head) {if (this. food. getLocation (). x = head. x & this. food. getLocation (). y = head. y) return false; return true ;}
Then, in the food object, we need to implement only the methods for claiming food:
/*** Location of the generated food * @ param snake * @ return returns Point */public Point setLocation (Snake snake) {location = new Point (); int canvas_width = SysConfig. CANVAS_WIDTH/SysConfig. STONE_WIDTH-2; int canvas_height = SysConfig. CANVAS_HEIGHT/SysConfig. STONE_HEIGHT-2; int temp = (int) (Math. random () * 1000); int rand = temp % (canvas_width * canvas_height-snake. getBody (). size () + 1; // int rand = temp % 50 + 1; boolean flag; for (int I = 0; I <canvas_height; I ++) {for (int j = 0; j <canvas_width; j ++) {flag = true; for (Point point: snake. getBody () {// System. out. println ("point: (" + point. x + "," + point. y + ")"); if (I = point. x & j = point. y) {flag = false; break;} if (flag) {rand --; if (rand = 0) {location. x = I; location. y = j; return location ;}}} return null ;}
Other remaining operations are code that associates snakes with food:
// GameController. javapackage org. sysit. game. snake; import java. awt. event. actionEvent; import java. awt. event. actionListener; import javax. swing. JTextField; import javax. swing. timer; public class GameController {private Ground ground; private Snake snake; private Food food; private Timer timer; private boolean pause = false; private int score = 0; private JTextField txtScore; public JTextField getTxtScore () {r Eturn txtScore;} public void setTxtScore (JTextField txtScore) implements this.txt Score = txtScore;} public GameController (final Snake, Food food, final Ground) {this. snake = snake; this. food = food; this. ground = ground; timer = new Timer (200, new ActionListener () {public void actionreceivmed (ActionEvent e) {if (snake. isLife () {snake. move (); if (snake. isLife () {score = snake. getScore (); getTxtScore (). se TText (score + ""); ground. repaint ();} else {timer. stop () ;}}});}/*** game initialization */public void init () {getTxtScore (). setText ("0");}/*** start game */public void startGame () {init (); timer. start (); ground. requestFocus ();}/*** pause the game */public void pauseGame () {if (! Pause) {timer. stop (); pause = true;} ground. requestFocus ();}/*** continue game */public void resumeGame () {if (pause) {timer. restart (); pause = false;} ground. requestFocus ();} public boolean isPause () {return pause;} public void setPause (boolean pause) {this. pause = pause ;}}
// Ground. javapackage org. sysit. game. snake; import java. awt. canvas; import java. awt. color; import java. awt. graphics; import java. awt. image; import java. awt. point; import java. awt. event. keyAdapter; import java. awt. event. keyEvent; import java. util. list; import org. sysit. game. snake. snake. dir; public class Ground extends Canvas {private Snake snake; private Food food; private Image iBuffer; public Ground () {setBound S (0, 0, SysConfig. CANVAS_WIDTH, SysConfig. CANVAS_HEIGHT); setBackground (Color. BLACK); addKeyListener (new KeyAdapter () {@ Overridepublic void keyPressed (KeyEvent e) {int keyCode = e. getKeyCode (); switch (keyCode) {case KeyEvent. VK_UP: snake. setsnkedir (dir. UP); break; case KeyEvent. VK_DOWN: snake. setsnkedir (dir. DOWN); break; case KeyEvent. VK_LEFT: snake. setsnkedir (dir. LEFT); break; case KeyEvent. VK_RIGHT: snake. Setsnkedir (dir. RIGHT); break ;}}});} public Snake getSnake () {return snake;} public void setSnake (Snake snake) {this. snake = snake;} public Food getFood () {return food;} public void setFood (Food food) {this. food = food;}/*** dual Buffer technology solves the problem of screen flickering */@ Overridepublic void update (Graphics g) {if (iBuffer = null) {iBuffer = createImage (this. getSize (). width, this. getSize (). height);} // if (gBuffer = null) {Graphics gBu Ffer = iBuffer. getGraphics (); //} gBuffer. setColor (getBackground (); gBuffer. fillRect (0, 0, this. getSize (). width, this. getSize (). height); paint (gBuffer); gBuffer. dispose (); g. drawImage (iBuffer, 0, 0, this);}/*** draw wall */public void drawWall (Graphics g) {g. setColor (Color. GRAY); int canvas_width = SysConfig. CANVAS_WIDTH/SysConfig. STONE_WIDTH; int canvas_height = SysConfig. CANVAS_HEIGHT/SysConfig. STONE_WID TH; for (int I = 0; I <canvas_width; I ++) {g. fill3DRect (I * SysConfig. STONE_WIDTH, 0, SysConfig. STONE_WIDTH, SysConfig. STONE_HEIGHT, true) ;}for (int I = 0; I <canvas_width; I ++) {g. fill3DRect (I * SysConfig. STONE_WIDTH, SysConfig. CANVAS_HEIGHT-SysConfig. STONE_HEIGHT, SysConfig. STONE_WIDTH, SysConfig. STONE_HEIGHT, true) ;}for (int I = 0; I <canvas_height; I ++) {g. fill3DRect (0, I * SysConfig. STONE _ WIDTH, SysConfig. STONE_WIDTH, SysConfig. STONE_HEIGHT, true) ;}for (int I = 0; I <canvas_height; I ++) {g. fill3DRect (SysConfig. CANVAS_WIDTH-SysConfig. STONE_WIDTH, I * SysConfig. STONE_WIDTH, SysConfig. STONE_WIDTH, SysConfig. STONE_HEIGHT, true) ;}/ *** lawn painting */public void drawGrass (Graphics g) {g. setColor (Color. DARK_GRAY); for (int I = 1; I <SysConfig. CANVAS_WIDTH/SysConfig. STONE_WIDTH-1; I ++) {(Int j = 1; j <SysConfig. CANVAS_HEIGHT/SysConfig. STONE_HEIGHT-1; j ++) {g. fill3DRect (I * SysConfig. STONE_WIDTH, j * SysConfig. STONE_HEIGHT, SysConfig. STONE_WIDTH, SysConfig. STONE_HEIGHT, true) ;}}/ *** draw food */public void drawFood (Graphics g) {Point point = getFood (). getLocation (); // System. out. println ("location: (" + point. x + "," + point. y + ")"); g. setColor (getFood (). getColor (); g. fill3DRect (poi Nt. y + 1) * SysConfig. STONE_WIDTH, (point. x + 1) * SysConfig. STONE_HEIGHT, SysConfig. STONE_WIDTH, SysConfig. STONE_HEIGHT, true);}/*** draw snake */public void drawSnake (Graphics g) {g. setColor (getSnake (). getColor (); List <Point> body = getSnake (). getBody (); for (Point point: body) {g. fill3DRect (point. y + 1) * SysConfig. STONE_WIDTH, (point. x + 1) * SysConfig. STONE_HEIGHT, SysConfig. STONE_WIDTH, SysConfig. STO NE_HEIGHT, true) ;}@overridepublic void paint (java. awt. graphics g) {drawWall (g); drawGrass (g); // snake. move (); if (snake! = Null) {drawSnake (g);} if (food! = Null) {drawFood (g );}};}
// MainFrame. javapackage org. sysit. game. snake; import java. awt. borderLayout; public class MainFrame extends JFrame {private JButton start; private JButton pause; private JPanel showScore; private JLabel lblNewLabel; private JTextField txtScore; public MainFrame () {super ("snake"); getContentPane (). setLayout (new BorderLayout (); setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); Ground ground = new Ground (); // controller. setGround (ground); Snake snake = new Snake (3); ground. setSnake (snake); Food food = new Food (); ground. setFood (food); snake. setFood (food); food. setLocation (snake); final GameController controller = new GameController (snake, food, ground); JPanel control = new JPanel (); start = new JButton ("start"); start. addActionListener (new ActionListener () {@ Overridepublic void actionreceivmed (ActionEvent e) {controller. startGame (); pause. setEnabled (true) ;}}); start. setSize (100, 50); pause = new JButton ("Suspend"); pause. addActionListener (new ActionListener () {@ Overridepublic void actionreceivmed (ActionEvent e) {if (controller. isPause () {pause. setText ("paused"); controller. resumeGame ();} else {pause. setText ("continue"); controller. pauseGame () ;}}); pause. setEnabled (false); pause. setSize (100, 50); control. add (start); control. add (pause); add (ground, BorderLayout. CENTER); add (control, BorderLayout. SOUTH); pack (); panel = new JPanel (); control. add (panel); panel. setLayout (null); showScore = new JPanel (); getContentPane (). add (showScore, BorderLayout. NORTH); showScore. setLayout (new FlowLayout (FlowLayout. CENTER, 5, 5); lblNewLabel = new JLabel ("\ u5206 \ u6570:"); showScore. add (lblNewLabel); txtScore = new JTextField (); showScore. add (txtScore); txtScore. setColumns (10); txtScore. setEditable (false); controller. setTxtScore (txtScore); Toolkit tool = Toolkit. getdefatooltoolkit (); Dimension dime = tool. getScreenSize (); int screenWidth = dime. width; int screenHeight = dime. height; int frameWidth = SysConfig. CANVAS_WIDTH + 6; int frameHeight = SysConfig. CANVAS_HEIGHT + 94; setBounds (screenWidth-frameWidth)/2, (screenHeight-frameHeight)/2, frameWidth, frameHeight); setResizable (false); setVisible (true );} public static void main (String [] args) {new MainFrame ();}}
Full: http://download.csdn.net/detail/zhang__bing/4377159