Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

1 .

SNAKE GAME USING JAVA

In our childhood, nearly all of us enjoyed playing classic snake games. Now
we will try to enhance it with the help of Java concepts. The concept
appears to be easy but it is not that effortless to implement.

One ought to comprehend the OOPs concept in detail to execute this


effectively. Furthermore, ideas from Java Swing are used to create this
application. The application should comprise the following functionalities:

 The Snake will have the ability to move in all four directions.
 The snake’s length grows as it eats food.
 When the snake crosses itself or strikes the perimeter of the box, the
game is marked over.
 Food is always given at different positions.
src/com/zetcode/Board.java

package com.zetcode;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Board extends JPanel implements ActionListener {

private final int B_WIDTH = 300;


private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;

private final int x[] = new int[ALL_DOTS];


private final int y[] = new int[ALL_DOTS];

private int dots;


private int apple_x;
private int apple_y;

private boolean leftDirection = false;


private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;

private Timer timer;


private Image ball;
private Image apple;
private Image head;

public Board() {

initBoard();
}

private void initBoard() {

addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);

setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));


loadImages();
initGame();
}

private void loadImages() {

ImageIcon iid = new ImageIcon("src/resources/dot.png");


ball = iid.getImage();

ImageIcon iia = new ImageIcon("src/resources/apple.png");


apple = iia.getImage();

ImageIcon iih = new ImageIcon("src/resources/head.png");


head = iih.getImage();
}

private void initGame() {

dots = 3;

for (int z = 0; z < dots; z++) {


x[z] = 50 - z * 10;
y[z] = 50;
}

locateApple();

timer = new Timer(DELAY, this);


timer.start();
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

doDrawing(g);
}

private void doDrawing(Graphics g) {

if (inGame) {

g.drawImage(apple, apple_x, apple_y, this);

for (int z = 0; z < dots; z++) {


if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}

Toolkit.getDefaultToolkit().sync();

} else {

gameOver(g);
}
}

private void gameOver(Graphics g) {

String msg = "Game Over";


Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);

g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}

private void checkApple() {

if ((x[0] == apple_x) && (y[0] == apple_y)) {

dots++;
locateApple();
}
}

private void move() {

for (int z = dots; z > 0; z--) {


x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}

if (leftDirection) {
x[0] -= DOT_SIZE;
}

if (rightDirection) {
x[0] += DOT_SIZE;
}

if (upDirection) {
y[0] -= DOT_SIZE;
}

if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {

for (int z = dots; z > 0; z--) {

if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {


inGame = false;
}
}

if (y[0] >= B_HEIGHT) {


inGame = false;
}

if (y[0] < 0) {
inGame = false;
}

if (x[0] >= B_WIDTH) {


inGame = false;
}

if (x[0] < 0) {
inGame = false;
}

if (!inGame) {
timer.stop();
}
}

private void locateApple() {

int r = (int) (Math.random() * RAND_POS);


apple_x = ((r * DOT_SIZE));

r = (int) (Math.random() * RAND_POS);


apple_y = ((r * DOT_SIZE));
}

@Override
public void actionPerformed(ActionEvent e) {

if (inGame) {

checkApple();
checkCollision();
move();
}

repaint();
}

private class TAdapter extends KeyAdapter {


@Override
public void keyPressed(KeyEvent e) {

int key = e.getKeyCode();

if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {


leftDirection = true;
upDirection = false;
downDirection = false;
}

if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {


rightDirection = true;
upDirection = false;
downDirection = false;
}

if ((key == KeyEvent.VK_UP) && (!downDirection)) {


upDirection = true;
rightDirection = false;
leftDirection = false;
}

if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {


downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}

src/com/zetcode/Snake.java
package com.zetcode;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class Snake extends JFrame {

public Snake() {

initUI();
}

private void initUI() {

add(new Board());

setResizable(false);
pack();

setTitle("Snake");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

EventQueue.invokeLater(() -> {
JFrame ex = new Snake();
ex.setVisible(true);
});
}
}
2.PASSWORD GENERATOR USING JAVA

With the growing trend of hacking attacks, everyone should create


different and complex passwords for their diverse accounts to keep them
secure. Remembering every password is not humanly possible and noting it
down somewhere is not a wise idea. Hence, people take the help of
Password generators to create strong and complex passwords for their
accounts. To generate such functionality all by yourself, you can take
advantage of the function that java offers. Whenever a user is developing an
account on a new website, you can use that program to develop a password.
To take the safety of the password a notch above, you can enforce such
functionality so that it saves passwords in encrypted form. To incorporate
this, you need to study the fundamentals of Cryptography and Java
Cryptography Architecture.

Password Generator/src/Alphabet.java

public class Alphabet {

public static final String UPPERCASE_LETTERS =


"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
public static final String NUMBERS = "1234567890";
public static final String SYMBOLS = "!@#$%^&*()-_=+\\/~?";

private final StringBuilder pool;

public Alphabet(boolean uppercaseIncluded, boolean lowercaseIncluded, boolean


numbersIncluded, boolean specialCharactersIncluded) {
pool = new StringBuilder();

if (uppercaseIncluded) pool.append(UPPERCASE_LETTERS);

if (lowercaseIncluded) pool.append(LOWERCASE_LETTERS);

if (numbersIncluded) pool.append(NUMBERS);

if (specialCharactersIncluded) pool.append(SYMBOLS);

public String getAlphabet() {


return pool.toString();
}
}

Password Generator/src/Generator.java
import java.util.Objects;
import java.util.Scanner;

public class Generator {


Alphabet alphabet;
public static Scanner keyboard;

public Generator(Scanner scanner) {


keyboard = scanner;
}

public Generator(boolean IncludeUpper, boolean IncludeLower, boolean IncludeNum,


boolean IncludeSym) {
alphabet = new Alphabet(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);
}

public void mainLoop() {


System.out.println("Welcome to Ziz Password Services :)");
printMenu();

String userOption = "-1";

while (!userOption.equals("4")) {

userOption = keyboard.next();

switch (userOption) {
case "1" -> {
requestPassword();
printMenu();
}
case "2" -> {
checkPassword();
printMenu();
}
case "3" -> {
printUsefulInfo();
printMenu();
}
case "4" -> printQuitMessage();
default -> {
System.out.println();
System.out.println("Kindly select one of the available commands");
printMenu();
}
}
}
}

private Password GeneratePassword(int length) {


final StringBuilder pass = new StringBuilder("");

final int alphabetLength = alphabet.getAlphabet().length();

int max = alphabetLength - 1;


int min = 0;
int range = max - min + 1;

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


int index = (int) (Math.random() * range) + min;
pass.append(alphabet.getAlphabet().charAt(index));
}

return new Password(pass.toString());


}

private void printUsefulInfo() {


System.out.println();
System.out.println("Use a minimum password length of 8 or more characters if
permitted");
System.out.println("Include lowercase and uppercase alphabetic characters,
numbers and symbols if permitted");
System.out.println("Generate passwords randomly where feasible");
System.out.println("Avoid using the same password twice (e.g., across multiple user
accounts and/or software systems)");
System.out.println("Avoid character repetition, keyboard patterns, dictionary
words, letter or number sequences," +
"\nusernames, relative or pet names, romantic links (current or past) " +
"and biographical information (e.g., ID numbers, ancestors' names or dates).");
System.out.println("Avoid using information that the user's colleagues and/or " +
"acquaintances might know to be associated with the user");
System.out.println("Do not use passwords which consist wholly of any simple
combination of the aforementioned weak components");
}

private void requestPassword() {


boolean IncludeUpper = false;
boolean IncludeLower = false;
boolean IncludeNum = false;
boolean IncludeSym = false;

boolean correctParams;

System.out.println();
System.out.println("Hello, welcome to the Password Generator :) answer"
+ " the following questions by Yes or No \n");

do {
String input;
correctParams = false;

do {
System.out.println("Do you want Lowercase letters \"abcd...\" to be used? ");
input = keyboard.next();
PasswordRequestError(input);
} while (!input.equalsIgnoreCase("yes") && !input.equalsIgnoreCase("no"));

if (isInclude(input)) IncludeLower = true;

do {
System.out.println("Do you want Uppercase letters \"ABCD...\" to be used? ");
input = keyboard.next();
PasswordRequestError(input);
} while (!input.equalsIgnoreCase("yes") && !input.equalsIgnoreCase("no"));

if (isInclude(input)) IncludeUpper = true;

do {
System.out.println("Do you want Numbers \"1234...\" to be used? ");
input = keyboard.next();
PasswordRequestError(input);
} while (!input.equalsIgnoreCase("yes") && !input.equalsIgnoreCase("no"));

if (isInclude(input)) IncludeNum = true;

do {
System.out.println("Do you want Symbols \"!@#$...\" to be used? ");
input = keyboard.next();
PasswordRequestError(input);
} while (!input.equalsIgnoreCase("yes") && !input.equalsIgnoreCase("no"));

if (isInclude(input)) IncludeSym = true;

//No Pool Selected


if (!IncludeUpper && !IncludeLower && !IncludeNum && !IncludeSym) {
System.out.println("You have selected no characters to generate your " +
"password, at least one of your answers should be Yes\n");
correctParams = true;
}

} while (correctParams);

System.out.println("Great! Now enter the length of the password");


int length = keyboard.nextInt();

final Generator generator = new Generator(IncludeUpper, IncludeLower,


IncludeNum, IncludeSym);
final Password password = generator.GeneratePassword(length);

System.err.println("Your generated password -> " + password);


}

private boolean isInclude(String Input) {


if (Input.equalsIgnoreCase("yes")) {
return true;
}
else {
return false;
}
}

private void PasswordRequestError(String i) {


if (!i.equalsIgnoreCase("yes") && !i.equalsIgnoreCase("no")) {
System.out.println("You have entered something incorrect let's go over it again \
n");
}
}

private void checkPassword() {


String input;

System.out.print("\nEnter your password:");


input = keyboard.next();

final Password p = new Password(input);

System.out.println(p.calculateScore());
}

private void printMenu() {


System.out.println();
System.out.println("Enter 1 - Password Generator");
System.out.println("Enter 2 - Password Strength Check");
System.out.println("Enter 3 - Useful Information");
System.out.println("Enter 4 - Quit");
System.out.print("Choice:");
}

private void printQuitMessage() {


System.out.println("Closing the program bye bye!");
}
}
Password Generator/src/GeneratorTest.java
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class GeneratorTest {

private final Password password= new Password("Secret");


private final Alphabet firstAlphabet = new Alphabet(true,false,false,false);
private final Alphabet secondAlphabet = new Alphabet(false,true,true,true);
private final Generator generator = new Generator(true,false,false,false);
// private final Password generatedPassword = generator.GeneratePassword(4);

@Test
void test1() {
assertEquals("Secret", password.toString());
}

@Test
void test2() {
assertEquals(firstAlphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);
}

@Test
void test3() {
assertEquals(secondAlphabet.getAlphabet(),
Alphabet.LOWERCASE_LETTERS + Alphabet.NUMBERS + Alphabet.SYMBOLS);
}

@Test
void test4() {
assertEquals(generator.alphabet.getAlphabet(),
Alphabet.UPPERCASE_LETTERS);
}

@Test
void test5() {
assertEquals(generator.alphabet.getAlphabet().length(), 26);
}

Password Generator/src/Main.java
import java.util.Scanner;

public class Main {

public static final Scanner keyboard = new Scanner(System.in);

public static void main(String[] args) {


Generator generator = new Generator(keyboard);
generator.mainLoop();
keyboard.close();
}
}

Password Generator/src/Password.java

public class Password {


String Value;
int Length;

public Password(String s) {
Value = s;
Length = s.length();
}

public int CharType(char C) {


int val;

// Char is Uppercase Letter


if ((int) C >= 65 && (int) C <= 90)
val = 1;

// Char is Lowercase Letter


else if ((int) C >= 97 && (int) C <= 122) {
val = 2;
}

// Char is Digit
else if ((int) C >= 60 && (int) C <= 71) {
val = 3;
}

// Char is Symbol
else {
val = 4;
}

return val;
}

public int PasswordStrength() {


String s = this.Value;
boolean UsedUpper = false;
boolean UsedLower = false;
boolean UsedNum = false;
boolean UsedSym = false;
int type;
int Score = 0;

for (int i = 0; i < s.length(); i++) {


char c = s.charAt(i);
type = CharType(c);

if (type == 1) UsedUpper = true;


if (type == 2) UsedLower = true;
if (type == 3) UsedNum = true;
if (type == 4) UsedSym = true;
}

if (UsedUpper) Score += 1;
if (UsedLower) Score += 1;
if (UsedNum) Score += 1;
if (UsedSym) Score += 1;

if (s.length() >= 8) Score += 1;


if (s.length() >= 16) Score += 1;

return Score;
}

public String calculateScore() {


int Score = this.PasswordStrength();

if (Score == 6) {
return "This is a very good password :D check the Useful Information section to
make sure it satisfies the guidelines";
} else if (Score >= 4) {
return "This is a good password :) but you can still do better";
} else if (Score >= 3) {
return "This is a medium password :/ try making it better";
} else {
return "This is a weak password :( definitely find a new one";
}
}

@Override
public String toString() {
return Value;
}
}

You might also like