ACN Micro Project

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

SANJIVANI K.B.

P POLYTECHNIC, KOPARGAON

Sub- Advanced Java Programming (22517)


(2024-2025)

A PROJECT ON

“Number Guessing Game”

DIPLOMA COMPUTER TECHNOLOGY

Submitted By - Miss. Thombare Sakshi Santosh

Under the Guidance Of - Prof. S.B.Jadhav


.

Project Guide HOD


Prof.S.B.Jadhav Dr.G.N.Jorvekar

1
Department Of Computer Technology S.K.B.P.
Polytechnic Kopargaon

CERTIFICATE

This is to certify that project entitle

“Number Guessing Game”


SUBMITTED BY

Miss. Thombare Sakshi Santosh

This is a bonafide work carried out by above student under the


supervision of Prof.S.B.Jadhav and it is submitted towards the partial
fulfillment of the requirement of MSBTE, Mumbai for the award of
Diploma in Computer Technology.
Project Guide HOD
Prof. S.B. Jadhav Dr. G.N. Jorvekar

2
Introduction

The Number Guessing Game is a simple yet engaging project designed to


demonstrate fundamental programming concepts such as user input,
conditionals, loops, and random number generation. This project is
suitable for beginners and can be implemented in various programming
languages, including Python, JavaScript, and Java.
This project is designed to engage users in a fun and interactive way while
enhancing programming skills. The objective of the game is simple:
players must guess a randomly generated number within a specified range
in as few attempts as possible.

Project Overview

In this game, the computer will select a random number, and players will
input their guesses. After each guess, the program will provide feedback,
indicating whether the guess is too high, too low, or correct. This not only
makes the game challenging but also encourages strategic thinking as
players refine their guesses based on the feedback received.

3
Source Code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class NumberGuessingGame extends JFrame {


private JTextField guessInput; private JButton
guessButton, restartButton; private JLabel messageLabel,
attemptsLabel, scoreLabel; private int randomNumber,
attempts, maxAttempts, score; private Random random;

public NumberGuessingGame() {
// Set up JFrame
setTitle("Number Guessing Game");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

4
// Initialize components
guessInput = new JTextField(10);
guessButton = new JButton("Guess");
restartButton = new JButton("Restart");
messageLabel = new JLabel("Guess a number between 1
and 100");
attemptsLabel = new JLabel("Attempts left: 7");
scoreLabel = new JLabel("Score: 0");

add(messageLabel);
add(guessInput);
add(guessButton);
add(restartButton);
add(attemptsLabel);
add(scoreLabel);

// Set difficulty
maxAttempts = 7;
random = new Random();
resetGame();

5
// Guess button action
guessButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
makeGuess();
}
});

// Restart button action


restartButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetGame();
}
});
}

6
private void makeGuess() {
if (attempts > 0) { try
{
int guess = Integer.parseInt(guessInput.getText());

if (guess < 1 || guess > 100) {


messageLabel.setText("Enter a number between 1 and 100.");
return;
}
attempts--
;
attemptsLabel.setText("Attempts left: " + attempts);

if (guess == randomNumber) {
messageLabel.setText("You guessed it right!");
score += (maxAttempts - attempts) * 10;
scoreLabel.setText("Score: " + score);
guessButton.setEnabled(false); } else if (guess <
randomNumber) { messageLabel.setText("Too
low! Try again.");
} else {

7
messageLabel.setText("Too high! Try again.");
}

if (attempts == 0 && guess != randomNumber) {


messageLabel.setText("Game over! The number was
" + randomNumber);
guessButton.setEnabled(false);
}
} catch (NumberFormatException ex) {
messageLabel.setText("Invalid input. Enter a number.");
}
}
}

private void resetGame() {


randomNumber = random.nextInt(100) + 1;
attempts = maxAttempts;
messageLabel.setText("Guess a number between 1 and
100");

8
attemptsLabel.setText("Attempts left: " + attempts);
guessInput.setText("");
guessButton.setEnabled(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> { new
NumberGuessingGame().setVisible(true);
});
}

9
Output

10
Conclusion

The Number Guessing Game microproject successfully


illustrates key programming concepts while providing an
enjoyable and interactive experience. Through this project,
participants have had the opportunity to apply their knowledge in
several areas:
1. Programming Fundamentals: By implementing the game,
participants have strengthened their understanding of
variables, data types, loops, and conditionals.
2. User Interaction: The project emphasizes the importance of
user input and feedback, showcasing how to create engaging
and responsive applications.
3. Problem Solving: Participants have encountered challenges
in game design, such as input validation and random number
generation, which enhance critical thinking and debugging
skills.
4. Code Structure: Organizing the game into functions or
classes promotes better coding practices and prepares
participants for larger projects.

11
Swing Components

JFrame: The main window for the application.

JTextField: Allows the user to input their guess.

JButton: Two buttons for making a guess and restarting the game.

JLabel: Displays messages, attempts left, and score.

Classes

NumberGuessingGame: This is the main class that extends


JFrame, meaning it represents a window in a Swing application.

Constructor

NumberGuessingGame():

12
o This is the constructor for the NumberGuessingGame
class. It initializes the JFrame, sets its title, size, and
default close operation, and arranges the layout. o It
initializes the various GUI components (text fields,
buttons, and labels).
o The game starts by setting the maximum number of
attempts and generating a random number for the user
to guess. o Action listeners for the guess and restart
buttons are added to handle user interactions.

Methods

1. makeGuess():
o This method is called when the user clicks the
"Guess" button. o It checks if the user has remaining
attempts and processes their input. o The input is
validated to ensure it’s a number between 1 and 100. o If
the guess is correct, it updates the message and score. If
the guess is incorrect, it provides feedback on whether
the guess is too low or too high. o If attempts run out
without a correct guess, it informs the user that the
game is over.

13
2. resetGame():
o This method resets the game state for a new round. o
It generates a new random number and resets the
number of attempts. o The message and attempt labels
are updated, and the input field is cleared.
3. main(String[] args):
o The main method serves as the entry point for the
program. o It uses SwingUtilities.invokeLater() to
ensure that the
GUI updates happen on the Event Dispatch Thread,
which is the correct way to manage Swing
components.

GUI Components

• JTextField guessInput: A text field where the user enters


their guess.
• JButton guessButton: A button to submit the guess.
• JButton restartButton: A button to restart the game.
• JLabel messageLabel: Displays messages to the user, such
as instructions and feedback.
• JLabel attemptsLabel: Shows the number of attempts left.

14
• JLabel scoreLabel: Displays the current score.

Other Variables

• int randomNumber: The number that the user needs to


guess.
• int attempts: The number of attempts left for the current
game.
• int maxAttempts: The maximum number of attempts
allowed (set to 7).
• int score: The user's score based on the number of attempts
used

15
Algorithm:

1.Generate a random number between 1 and 100 (inclusive).


2. Ask the user to guess the number.
3. Compare the user's guess with the generated number.
4. If the guess is:
- Higher than the generated number, display "Too high!"
- Lower than the generated number, display "Too low!"

16
Reference

www.tutorialpoint.com www.javatpoint.com

17

You might also like