Computer Science, asked by lindassam2006, 9 months ago

Can someone give me a simple code for coding a snake game in Java

Answers

Answered by 09zishan
1

Explanation:

private final int x[] = new int[ALL_DOTS]; private final int y[] = new int[ALL_DOTS]; These two arrays store the x and y coordinates of all joints of a snake. In the loadImages() method we get the images for the game. The ImageIcon class is used for displaying PNG images.

Answered by pavithranatarajan855
0

Answer:

import java.awt.*;

import javax.swing.*;

import java.awt.event.*; // needed for event handling

public class Snake {

  static final int SCREEN_SIZE_X=40;         // In units of snake sections.

 static final int SCREEN_SIZE_Y=30;

 final int MAX_SNAKE_LENGTH = 1000;

  int snakeLength = 5;                      // Start snakes with length 5.

 SnakeSection [] snakeSecs = new SnakeSection[MAX_SNAKE_LENGTH];

 int dirX=-1;

 int dirY=0;

 

 Color color;               // Holds the color of the snake.

 

 public Snake(SnakeSection startPos,int dx,int dy,Color color) {

   for (int i=0; i<MAX_SNAKE_LENGTH; i++)  

     snakeSecs[i]=new SnakeSection(0,0);  

   for (int i=0; i<snakeLength; i++)  

     snakeSecs[i]=new SnakeSection(startPos.x+i*dx,startPos.y+i*dy);

 }

 public boolean contains(int x,int y) {  

   SnakeSection s=new SnakeSection(x,y);

   return s.match(snakeSecs[0]) || checkBodyPositions(s);

 }

 public boolean checkBodyPositions(SnakeSection s) {

   boolean collision=false;

   for (int i=1; i<snakeLength; i++) {

     if (s.match(snakeSecs[i]))

       collision=true;

   }

   return collision;

 }

 public void move() {

   for (int i=snakeLength-1; i>0; i--)

     snakeSecs[i]=snakeSecs[i-1];

   

   int newX=(snakeSecs[1].x + dirX + SCREEN_SIZE_X) % SCREEN_SIZE_X;

   int newY=(snakeSecs[1].y + dirY + SCREEN_SIZE_Y) % SCREEN_SIZE_Y;

   snakeSecs[0]=new SnakeSection(newX,newY);

 }

   public void paint(Graphics g) {  

   g.setColor(color);

   for (int i=0; i<snakeLength; i++) {

     g.setColor(new Color((float) Math.random(), (float) Math.random(), (float) Math.random()));

     g.drawRect(snakeSecs[i].x*20,snakeSecs[i].y*20,20,20);

   }

 }

}

Explanation:

Similar questions