GK SCIENTIST

General Knowledge One Stop Source
Menu
  • Home
  • Social Science
    • History
    • Political Science
    • Geography
  • Science
    • Physics
    • Chemistry
    • Biology
  • Chemistry Notes
  • Mathematics
  • Computer
  • Tutorial MySQL
  • Tutorial Python
  • Java Tutorial
  • English Grammar
  • English Essay
  • Indian Anthropology
  • Philosophy
  • Solved Paper
  • UPSC
  • Current Content
    • Current Affairs
    • RSTV News
    • Yojana and Kurukshetra Gist
  • Donate
  • Contact Us

If you are interested in advertising to our audience, submit the advertising enquiry form.

Advertising Enquiry
Computer

Create Snake Game in Java

Gk Scientist January 20, 2023 No Comments
Tweet WhatsApp Telegram

Create Snake Game in Java:

We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it.

Snake Game in Java Sample Code:

snake game java code 1 - Create Snake Game in Java
snake game java code 3 - Create Snake Game in Java
snake game java code 4 - Create Snake Game in Java
snake game java code 5 - Create Snake Game in Java
snake game java code 6 - Create Snake Game in Java
snake game java code 7 - Create Snake Game in Java

Output:

snake game java output - Create Snake Game in Java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

import javax.swing.JFrame;


public class SnakeGame extends JFrame{
	
	SnakeGame(){
		
		this.add(new GamePanel());
		this.setTitle("Snake");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(false);
		this.pack();
		this.setVisible(true);
		this.setLocationRelativeTo(null);
		
	}
	
	public class GamePanel extends JPanel implements ActionListener{

		static final int SCREEN_WIDTH = 1300;
		static final int SCREEN_HEIGHT = 750;
		static final int UNIT_SIZE = 50;
		static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
		static final int DELAY = 175;
		final int x[] = new int[GAME_UNITS];
		final int y[] = new int[GAME_UNITS];
		int bodyParts = 6;
		int applesEaten;
		int appleX;
		int appleY;
		char direction = 'R';
		boolean running = false;
		Timer timer;
		Random random;
		
		GamePanel(){
			random = new Random();
			this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
			this.setBackground(Color.black);
			this.setFocusable(true);
			this.addKeyListener(new MyKeyAdapter());
			startGame();
		}
		public void startGame() {
			newApple();
			running = true;
			timer = new Timer(DELAY,this);
			timer.start();
		}
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			draw(g);
		}
		public void draw(Graphics g) {
			
			if(running) {
				
				g.setColor(Color.red);
				g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
			
				for(int i = 0; i< bodyParts;i++) {
					if(i == 0) {
						g.setColor(Color.green);
						g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
					}
					else {
						g.setColor(new Color(45,180,0));
						//g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
						g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
					}			
				}
				g.setColor(Color.red);
				g.setFont( new Font("ROBOTO",Font.BOLD, 40));
				FontMetrics metrics = getFontMetrics(g.getFont());
				g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
			}
			else {
				gameOver(g);
			}
			
		}
		public void newApple(){
			appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
			appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
		}
		public void move(){
			for(int i = bodyParts;i>0;i--) {
				x[i] = x[i-1];
				y[i] = y[i-1];
			}
			
			switch(direction) {
			case 'U':
				y[0] = y[0] - UNIT_SIZE;
				break;
			case 'D':
				y[0] = y[0] + UNIT_SIZE;
				break;
			case 'L':
				x[0] = x[0] - UNIT_SIZE;
				break;
			case 'R':
				x[0] = x[0] + UNIT_SIZE;
				break;
			}
			
		}
		public void checkApple() {
			if((x[0] == appleX) && (y[0] == appleY)) {
				bodyParts++;
				applesEaten++;
				newApple();
			}
		}
		public void checkCollisions() {
			//checks if head collides with body
			for(int i = bodyParts;i>0;i--) {
				if((x[0] == x[i])&& (y[0] == y[i])) {
					running = false;
				}
			}
			//check if head touches left border
			if(x[0] < 0) {
				running = false;
			}
			//check if head touches right border
			if(x[0] > SCREEN_WIDTH) {
				running = false;
			}
			//check if head touches top border
			if(y[0] < 0) {
				running = false;
			}
			//check if head touches bottom border
			if(y[0] > SCREEN_HEIGHT) {
				running = false;
			}
			
			if(!running) {
				timer.stop();
			}
		}
		public void gameOver(Graphics g) {
			//Score
			g.setColor(Color.red);
			g.setFont( new Font("Ink Free",Font.BOLD, 40));
			FontMetrics metrics1 = getFontMetrics(g.getFont());
			g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
			//Game Over text
			g.setColor(Color.red);
			g.setFont( new Font("Ink Free",Font.BOLD, 75));
			FontMetrics metrics2 = getFontMetrics(g.getFont());
			g.drawString("Game Over", (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2);
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			
			if(running) {
				move();
				checkApple();
				checkCollisions();
			}
			repaint();
		}
		
		public class MyKeyAdapter extends KeyAdapter{
			@Override
			public void keyPressed(KeyEvent e) {
				switch(e.getKeyCode()) {
				case KeyEvent.VK_LEFT:
					if(direction != 'R') {
						direction = 'L';
					}
					break;
				case KeyEvent.VK_RIGHT:
					if(direction != 'L') {
						direction = 'R';
					}
					break;
				case KeyEvent.VK_UP:
					if(direction != 'D') {
						direction = 'U';
					}
					break;
				case KeyEvent.VK_DOWN:
					if(direction != 'U') {
						direction = 'D';
					}
					break;
				}
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		 new SnakeGame();

	
	
	}

}

Tutorial MySQL
Tutorial Python
Tokens in C++
Database Management System (DBMS)
Applications of Computer
Basic Components of Computer System
Java (programming language)– Wikipedia
Prev Article
Next Article

Related Articles

String Concatenation in Python
String Concatenation in Python: We can use the PyCharm code …
Gk Scientist November 21, 2022 Computer

String Concatenation in Python

User Input and Type Casting in Python
User Input and Type Casting in Python: We can use …
Gk Scientist November 23, 2022 Computer

User Input and Type Casting in Python

World Wide Web (WWW)
World Wide Web: From the late 1960s to the early …
Gk Scientist September 16, 2022 Computer

World Wide Web (WWW)

MySQL Logical Operators
MySQL Logical Operators: (1) AND Operator- MySQL logical AND operator …
Gk Scientist November 12, 2022 Computer

MySQL Logical Operators

Structured Programming- Advantages and Disadvantages
Structured Programming: In structured programming design, programs are broken into …
Gk Scientist August 9, 2022 Computer

Structured Programming- Advantages and Disadvantages

Constructors in Java
Constructors in Java: We can use the Eclipse IDE for …
Gk Scientist January 7, 2023 Computer

Constructors in Java

MySQL Primary Key and Foreign Key
MySQL Primary Key and Foreign Key: The Primary Key is …
Gk Scientist November 16, 2022 Computer

MySQL Primary Key and Foreign Key

Rock Paper Scissors Game in Python (Using Random Module)
Rock Paper Scissors Game in Python: We can use the …
Gk Scientist December 3, 2022 Computer

Rock Paper Scissors Game in Python (Using Random Module)

Leave a Reply Cancel Reply

Search




  • Popular
  • Recent




GK SCIENTIST

General Knowledge One Stop Source

Information

  • About Us
  • Terms and Condition, Disclaimer
  • Contact Us

Android Apps

  • IAS App For English Medium Students
  • IAS Basics App For English Medium Students
  • IAS Hindi App For Hindi Medium Students
DMCA.com Protection Status

Popular Tags

Biology (33) Biology Questions (88) Chemistry (57) Computer (213) Current Affairs (4) Current Content (0) Economy (10) English Essay (172) English Grammar (75) English Literature (10) Geography (83) History (259) Indian Anthropology (11) Indian Polity (14) JKAS Mains Question Papers (17) Mathematics (68) Moral Science (7) NCERT & Other Boards Books (25) Philosophy (114) Physics (89) Political Science (132) RS TV News (33) Science (553) Social Anthropology (7) Social Science (17) Solved Paper (47) UPSC (7) UPSC Mains Question Papers (26)

Downloads

  • NCERT Books
  • Old NCERT Books
  • NIOS Books For IAS, SSC, and State PSC Exam
  • Tamil Nadu Board Books: Important For UPSC, SSC, and State PSC Exam
  • Modern Indian and World History Notes For IAS Exam
  • UPSC Topper 2013 Gaurav Agrawal Notes For IAS Preparation
  • UPSC IAS Prelims General Studies – Previous Year Papers
  • UPSC Mains Question Papers

Copyright © 2023 GK SCIENTIST
Theme by MyThemeShop.com& Hosted On Cloudways

Ad Blocker Detected

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Refresh
 

Loading Comments...