Java and java code

Source: Internet
Author: User

Java and java code


Idea: It mainly simulates the movements of snakes. You only need to perform operations on the snake head, and then copy the first position of the previous State to the second part of the current snake body, copy the second part of the previous snake to the third part of the current snake ...... and so on, to simulate the snake movement.


Glutonoussnake. java

Package xjj; // graphical interface import java. awt. flowLayout; import java. awt. gridLayout; import java. awt. event. actionEvent; import java. awt. event. actionListener; import java. util. observable; import java. util. observer; import javax. swing. imageIcon; import javax. swing. JButton; import javax. swing. JFrame; import javax. swing. JLabel; import javax. swing. JMenu; import javax. swing. JMenuBar; import javax. swing. JMenuItem; import javax. swing. JOptionPane; import javax. swing. JPanel; import javax. swing. JTextField; import javax. swing. border. titledBorder; import javax. swing. event. caretEvent; import javax. swing. event. caretListener; import javax. swing. event. changeEvent; import javax. swing. event. changeListener; public class glutonoussnake extends JFrame implements ActionListener {private JButton upButton, downButton, leftButton, rightButton; // control direction button private JTextField score; // score private SnakeCanvas snake; // Snake Model public fig () {super ("snake"); // set the title this. setSize (725,515); // set the size of this. setdefaclocloseoperation (EXIT_ON_CLOSE); // set the exit button this. setLocationRelativeTo (null); // set the center of the window JPanel p = new JPanel (); // control button and display score panel p. setBorder (new TitledBorder ("control and display area"); // set the title of this panel this. getContentPane (). add (p, "East"); // set the position of this panel p. setLayout (new GridLayout (4, 1); // set the layout mode of the Panel. For the grid layout mode, JPanel p2 = new JPanel (); // Add the Panel p2.setLayout (new FlowLayout () for displaying scores in this panel; // set it to the stream Layout mode p2.add (new JLabel ("score :")); score = new JTextField ("0"); score. setEditable (false); p2.add (score); p. add (p2); // add button with image and add event listening upButton = new JButton ("", new ImageIcon ("up.png"); upButton. setActionCommand ("up"); upButton. addActionListener (this); downButton = new JButton ("", new ImageIcon ("down.png"); downButton. setActionCommand ("down"); downButton. addActionListener (this); leftButton = new JButton ("", new ImageIcon ("left.png"); leftButton. setActionCommand ("left"); leftButton. addActionListener (this); rightButton = new JButton ("", new ImageIcon ("right.png"); rightButton. setActionCommand ("right"); rightButton. addActionListener (this); p. add (upButton); JPanel p1 = new JPanel (); p1.setLayout (new GridLayout (1, 2); p1.add (leftButton); p1.add (rightButton); p. add (p1); p. add (downButton); addMenu (); // add menu start (); this. setResizable (false); this. setVisible (true);} private void start () {snake = new SnakeCanvas (); this. getContentPane (). add (snake);} private void addMenu () {JMenuBar menubar = new JMenuBar (); this. setJMenuBar (menubar); JMenu game = new JMenu ("game"); JMenu help = new JMenu ("help"); JMenuItem jitemNew = new JMenuItem ("new game "); jitemNew. setActionCommand ("new"); jitemNew. addActionListener (this); JMenuItem jitemPause = new JMenuItem ("paused"); jitemPause. setActionCommand ("pause"); jitemPause. addActionListener (this); JMenuItem jitemExit = new JMenuItem ("exit"); jitemExit. setActionCommand ("exit"); jitemExit. addActionListener (this); game. add (jitemNew); game. add (jitemPause); game. addSeparator (); // set the separation line game in the menu. add (jitemExit); menubar. add (game); menubar. add (help);} public static void main (String [] args) {new glutonoussnake ();} public void actionreceivmed (ActionEvent e) {if (e. getActionCommand (). equalsIgnoreCase ("exit") {System. exit (EXIT_ON_CLOSE);} if (e. getSource () instanceof JButton) {if (e. getActionCommand (). equalsIgnoreCase ("up") {// responds to the above button and presses the event snake. setDirect (1); // sets the direction of snake head movement to snake. repaint (); // re-paint snake on the snake model. timer. start (); // The timer starts return;} if (e. getActionCommand (). equalsIgnoreCase ("down") {snake. setDirect (2); snake. repaint (); snake. timer. start (); return;} if (e. getActionCommand (). inclusignorecase ("left") {snake. setDirect (3); snake. repaint (); snake. timer. start (); return;} if (e. getActionCommand (). equalsIgnoreCase ("right") {snake. setDirect (4); snake. repaint (); snake. timer. start (); return ;}} if (e. getSource () instanceof JMenuItem) {if (e. getActionCommand (). equalsIgnoreCase ("new") {// this. getContentPane (). remove (snake); snake. init (); snake. repaint (); snake. timer. start ();} if (e. getActionCommand (). equalsIgnoreCase ("pause") {snake. timer. stop (); JOptionPane. showMessageDialog (this, "continue to press" OK "); snake. timer. start ();}}}}


MapCanvas. java

Package xjj; import java. awt. canvas; import java. awt. color; import java. awt. graphics; // public class MapCanvas extends Canvas {public void paint (Graphics g) {g. setColor (Color. red); for (int I = 30; I <= 450; I + = 30) {g. drawLine (0, I, 450, I) ;}for (int I = 30; I <= 450; I + = 30) {g. drawLine (I, 0, I, 450);} g. drawLine (0, 0,450, 0); g. drawLine (0,450,450,450); g. drawLine (0, 0, 0,450); g. drawLine (450, 0,450,450 );}}

SnakeCanvas. java

Package xjj; import java. awt. color; import java. awt. graphics; import java. awt. event. actionEvent; import java. awt. event. actionListener; import java. util. random; import javax. swing. JOptionPane; import javax. swing. timer; // Snake Model public class snkecanvas extends MapCanvas implements ActionListener {private int number = 5; // The initial length of the snake Body public Timer timer; // Timer private Body [] bodys; // private Body food; // public int SC Ore = 0; // score private int speed = 250; // timer delay event int direct = 3; // private int [] [] mapflag = new int [455] [455]; // map tag // initialize public void init () {this. direct = 3; this. number = 5; this. bodys = new Body [this. number]; mapflag = new int [455] [455]; for (int I = 0, x = 300; I <this. number; I ++, x + = 30) {bodys [I] = new Body (x, 180); mapflag [bodys [I]. x] [bodys [I]. y] = 2; // If the snake is marked as 2} food = creatFood (); // create food} public Sn AkeCanvas () {init (); timer = new Timer (speed, this); // create a timer object timer. start (); // timer start} private class Body {// snake header member int x, y; Body (int x, int y) {this. x = x; this. y = y ;}} public void paint (Graphics g) {// drawing super. paint (g); if (bodys = null) {return;} for (int I = 0; I <this. number; I ++) {if (I = 0) {// set different colors for the snake header g. setColor (Color. blue);} else {g. setColor (Color. black);} mapflag [bodys [I]. x] [bodys [I]. y] = 2; g. fillOval (bodys [I]. x, bodys [I]. y, 30, 30); // draw a snake} g. setColor (Color. red); g. fillOval (food. x, food. y, 30, 30); // draw food} public Body creatFood () {int x = 0, y = 0; do {// randomly generate the food location Random r = new Random (); // create a Random number object x = r. nextInt (450); // randomly generates a pseudo-random number from 0 to the given number. y = r. nextInt (450); // System. out. println (mapflag [x] [y] + "! ");} While (x % 30! = 0 | y % 30! = 0 | mapflag [x] [y] = 2); // ensure that the position is not the part of the snake and that it is neat. // System. out. println (x + "" + y); mapflag [x] [y] = 1; // mark the food as 1, next we can identify whether to eat food or ourselves by marking different operations, and then perform different operations return new Body (x, y);} public void actionreceivmed (ActionEvent e) {if (bodys = null) {return;} if (! IsMove () {// if the movement fails, the Game ends. JOptionPane. showMessageDialog (this, "Game Over! "); Bodys = null; timer. stop (); return;} repaint ();} // snake movement. Principle: you only need to operate the snake header, then assign the value of the position before the Snake Head to the second part of the current snake body, // Let the second part copy the third part of the current .... Similarly, simulate the snake Movement (this is the key) public void move (int x, int y) {Body [] B = new Body [bodys. length]; for (int I = 0; I <this. number; I ++) {B [I] = new Body (bodys [I]. x, bodys [I]. y);} this. bodys [0]. x = x; this. bodys [0]. y = y; for (int I = 1; I <this. number; I ++) {this. bodys [I] = B [I-1];} setMapflag ();} private void setMapflag () {// refresh mapflag for map flag = new int [455] [455]; mapflag [food. x] [food. y] = 1; for (int I = 0; I <this. number; I ++) {mapflag [bodys [I]. x] [bodys [I]. y] = 2 ;}/// determines whether the object is successfully moved. public boolean isMove () {if (bodys = null) {return false;} int x = bodys [0]. x; int y = bodys [0]. y; switch (this. direct) {// perform different operations on the snake headers in different directions. Example 1: y-= 30; break; case 2: y + = 30; break; case 3: x-= 30; break; case 4: x + = 30; break ;} if (x <0 | y> = 450 | x> = 450 | y <0) {// cross-border problem return false ;} if (mapflag [x] [y] = 1) {// if it is marked as 1, it is the snake head. Add the length of the snake body this. number ++; addSnake (x, y); // Add a snake length // System. out. println ("*"); return true;} else if (mapflag [x] [y] = 2) {// if it is marked as 2, it is a snake, that is, eat yourself and the game ends. // System. out. println ("^"); return false;} else {// System. out. println ("%"); move (x, y); return true ;}// Add a snake body, similar to move (); private void addSnake (int x, int y) {this. score ++; Body [] B = new Body [bodys. length]; for (int I = 0; I <this. number-1; I ++) {B [I] = new Body (bodys [I]. x, bodys [I]. y);} bodys = new Body [this. number]; this. bodys [0] = new Body (x, y); for (int I = 1; I <this. number; I ++) {this. bodys [I] = B [I-1];} setMapflag (); food = creatFood ();} public void setDirect (int I) {// set the direction of the snake header this. direct = I ;}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.