This tutorial explains step by step writing a simple guessing game where the player guess the number selected by the computer and the goal is to introduce the power and usage of RANDOM as well as the how to benefit CURRENTTIMEMILLIS method of the System class in order to check how much it took the player guessing the correct number.
a mini project in computer grafics using c and linkedlisted on a small game that name is snake game. we play this on mobile but this can be played on pc
Snake game powerpoint presentation by rohit malavRohit malav
snake game
Snake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle.Snake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of versions (some of which have the word snake or worm in the title) for many platforms. After a variant was preloaded on Nokia mobile phones in 1998, there was a resurgence of interest in the snake concept as it found a larger audience. There are over 300 Snake-like games for iOS aloneSnake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of versions (some of which have the word snake or worm in the title) for many platforms. After a variant was preloaded on Nokia mobile phones in 1998, there was a resurgence of interest in the snake concept as it found a larger audience. There are over 300 Snake-like games for iOS alone.
The project that we have undertaken aims to develop a 2D Adventures game. The
project “Game Development (Platformer Game Development)” includes the following
functionalities:
Realistic Experience
2D view
Good Graphics
Faster performance
Offline Game
No need for the Internet
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
A Virtual Keyboard is considered to be a component to use on computers without a real keyboard e.g. Touch Screen Computers and Smart Phones; where a mouse can utilize the keyboard functionalities and features.
In addition, Virtual Keyboard used for the following subjects: Foreign Character Sets, Touchscreen, Bypass Key Loggers, etc.
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
These PHP basic and fundamental questions and answers with detail explanation help students and learners to think comprehensive, and to seek more to understand the concept and the root of each topic concretely.
a mini project in computer grafics using c and linkedlisted on a small game that name is snake game. we play this on mobile but this can be played on pc
Snake game powerpoint presentation by rohit malavRohit malav
snake game
Snake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle.Snake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of versions (some of which have the word snake or worm in the title) for many platforms. After a variant was preloaded on Nokia mobile phones in 1998, there was a resurgence of interest in the snake concept as it found a larger audience. There are over 300 Snake-like games for iOS aloneSnake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of versions (some of which have the word snake or worm in the title) for many platforms. After a variant was preloaded on Nokia mobile phones in 1998, there was a resurgence of interest in the snake concept as it found a larger audience. There are over 300 Snake-like games for iOS alone.
The project that we have undertaken aims to develop a 2D Adventures game. The
project “Game Development (Platformer Game Development)” includes the following
functionalities:
Realistic Experience
2D view
Good Graphics
Faster performance
Offline Game
No need for the Internet
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
A Virtual Keyboard is considered to be a component to use on computers without a real keyboard e.g. Touch Screen Computers and Smart Phones; where a mouse can utilize the keyboard functionalities and features.
In addition, Virtual Keyboard used for the following subjects: Foreign Character Sets, Touchscreen, Bypass Key Loggers, etc.
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
These PHP basic and fundamental questions and answers with detail explanation help students and learners to think comprehensive, and to seek more to understand the concept and the root of each topic concretely.
This presentation explores and discusses the practical and useful of Regular Expressions covering username validation, complex and strong password validation, password strength checker, email validation, and finally image file extension validation.
Object Oriented Programming (OOP) makes it easier for programmers to structure and form software programs; since individual objects can be modified without touching other aspects of the program.
With this presentation we are covering most OOP features (Class, Object, Inheritance, Polymorphism, Encapsulation, etc.) with real life examples.
This presentation introduces Java Applet and Java Graphics in detail with examples and finally using the concept of both applet and graphics code the analog clock project to depict how to use them in real life challenges and applications.
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaOXUS 20
This presentation explains step by step how to develop and code Fal-e Hafez (Omens of Hafez) Cards in Persian Using JAVA. There are several applications which are coded by different programming languages i.e. Java languages for Desktops and Mobiles, HTML and CSS and PHP for Web Pages, etc. and this shows the importance of Omens of Hafez among the Persian people.
With Unicode you can program and accomplish many funny, cool and useful programs and tools as for instance, Abjad Calculator calculating the numerical value of letters derived from the Arabic alphabet through the use of the Abjad writing system, Bubble Text Generator to write letters in circle, Flip Text Generator to write letters upside down, Google Transliteration to convert English names to Persian/Arabic, etc.
Regular Expressions (Regex) is powerful and convenient to use for string manipulation i.e. matching and validation, extracting and capturing, modifying and substitution, etc. This presentation covers Regular Expression with real world examples and demos.
Object Oriented Concept Static vs. Non StaticOXUS 20
Static is not the true intend of Object Oriented Design and Concept.
For instance, we turn a LAMP "off" it does not suppose to turn the LAMPS of the entire world goes "off".
To review computer basics, programs, and operating systems
To explore the relationship between Java and the World Wide Web
To distinguish the terms API, IDE, and JDK
To write a simple Java program
To display output on the console
To explain the basic syntax of a Java program
To create, compile, and run Java programs
(GUI) To display output using the JOptionPane output dialog boxes
Create Splash Screen with Java Step by StepOXUS 20
This presentation guide you how to make a custom Splash Screen step by step using Java Programming. In addition, you will learn the concept and usage of Java Timer, Java Progress Bar and Window ...
Web Design and Development Life Cycle and TechnologiesOXUS 20
This presentation is an introduction to the design, creation, and maintenance of web design and development life cycle and web technologies. With it, you will learn about the web technologies, the life cycle of developing an efficient website and web application and finally some web essentials questions will be provided and reviewed.
Everything about Database JOINS and RelationshipsOXUS 20
Today, we continue our journey into the world of RDBMS (relational database management systems) and SQL (Structured Query Language).
In this presentation, you will understand about some key definitions and then you will learn how to work with multiple tables that have relationships with each other.
First, we will go covering some core concepts and key definitions, and then will begin working with JOINs queries in SQL.
With Unicode you can program and accomplish many funny, cool and useful programs and tools as for instance, Abjad Calculator, Bubble Text Generator to write letters in circle, Flip Text Generator to write letters upside down, Google Transliteration to convert English names to Persian/Arabic, etc...
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesAbdul Rahman Sherzad
A Virtual Keyboard is considered to be a component to use on computers without a real keyboard e.g. Touch Screen Computers and Smart Phones; where a mouse can utilize the keyboard functionalities and features.
In addition, Virtual Keyboard used for the following subjects: Foreign Character Sets, Touchscreen, Bypass Key Loggers, etc.
Jdbc Complete Notes by Java Training Center (Som Sir)Som Prakash Rai
This Jdbc (Java Database Connectivity) notes contains the complete indepth Explanation of JDBC by Som Prakash Rai Sir. This is the Running notes of java Training center ,(J.T.C Noida), www.jtcindia.org
I am Fabian H. I am a Computer Science Assignment Help Expert at programminghomeworkhelp.com. I hold a Masters in Programming, Deakin University, Australia. I have been helping students with their homework for the past 8 years. I solve assignments related to Computer Science.
Visit programminghomeworkhelp.com or email support@programminghomeworkhelp.com.You can also call on +1 678 648 4277 for any assistance with Computer Science assignments.
Are you worried about your Python Homework? Are you afraid of your deadline lurking near? Leave your tensions and worries behind. Just Contact www.pythonhomeworkhelp.com Experts. With more than 90% of success rate, they are one of the reliable Python homework Help Experts. You can’t ignore them if you want good grades for your homework. You can also contact the anytime as they are available 24 x 7 in live chat.
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
You will write a multi-interface version of the well-known concentration game: 1. The game
displays a grid of upper-case letters, with each letter appearing twice. 2. A player has a few
seconds to memorize the letters before they disappear. 3. The player then has to remember where
each pair was located.
line, then MultiConcentration starts with the text interface.
First the new game display will show the user the pairs he/she must guess, in a format similar to
the following example for size = 6
D H B C M I
H G K K A R
C N R E O E
Q O A Q L F
L F J P B G
P D N M I J
Memorize the above grid!
Note that the new game display uses pairs of distinct single uppercase capital letters distributed
at random on a square grid, starting at A and continuing until the grid is full.
This new game display shows for 10 seconds, after which it scrolls out of view. (To scroll it just
write about 25 newlines.) Then the standard game display appears.
The standard game display will look like the following example for size = 6
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
21 32 33 34 35 36
Enter a pair of numbers, or \"R\" to reset, or \"Q\" to quit:
reset, or \"Q\" to quit:
If the player makes an invalid entry (e.g. numbers out of range, number already guessed, no
blank separator, etc.) then a \"please reenter\" message is printed and the same display is shown
again.
If the player makes a bad guess, then a \"Sorry...\" message is printed and the same display is
shown again.
If the player enters an \"R\" for reset, then we start over, that is, the computer calculates a new
set of pairs and shows the new game display again.
If the player enters a \"Q\" for quit, then the game prints a \"Game Over\" message and ends.
3.4 Graphic Game Interface
If the player used the \"-g\" flag on the startup command line then MultiConcentration starts up
with the graphic interface.
You may design the graphic interface as you choose, as long as you use Swing and preserve the
steps in the game as described in the previous section.
One possible graphic interface is shown in Figure 1. In this design the new game display and the
standard game display have been replaced by a grid of buttons. Instead of entering pairs of
numbers, the player clicks on two of the buttons. The \"reset\" and \"quit\" commands are given
using a menu. Letters that have been correctly guessed are shown with a pink background color.
Messages to the player are shown in a text area under the grid.
4 GENERAL REQUIREMENTS
4.1 Design Requirements
Design your program with GUI classes, a main class, and Application Logic / Data classes as
described in my overheads on Design for Testability.
Do not use a package statement; name the main class MultiConcentration. (Otherwise the
startup command given in 3.1 would not work.)
You should have at least 5 classes, and not one of them should have more than 40% of the code.
Solution
import java.io.OutputStream;
import java.io.PrintStream;
public cl.
Most asked JAVA Interview Questions & Answers.Questpond
Java Interview Q&A video - https://youtu.be/WM351yrdlpk
In this slide we have answered definitely asked questions in JAVA interviews about Snake & Ladder game and Connection Pooling in JAVA with complete code example.
For more Basic and Advanced JAVA training videos visit this link - https://www.questpond.com/java/javaj2eedesignpattern.html
For more details contact questpond@questpond.com OR call +919967590707- 9619842789 - 9769000232.
OverviewThis hands-on lab allows you to follow and experiment w.docxgerardkortney
Overview:
This hands-on lab allows you to follow and experiment with the critical steps of developing a program including the program description, Analysis, , Design(program design, pseudocode), Test Plan, and implementation with C code. The example provided uses sequential, repetition statements and nested repetition statements.
Program Description:
This program will calculate the average of 10 positive integers. The program will ask the user to 10 integers. If any of the values entered is negative, a message will be displayed asking the user to enter a value greater than 0. The program will use a loop to input the data.
Analysis:
I will use sequential, selection and repetition programming statements.
The program will loop for 10 positive numbers, prompting the user to enter a number.
I will define three integer variables: count, value and sum. count will store how many times values greater than 0 are entered. value will store the input. Sum will store the sum of all 10 integers.
I will define one double number: avg. avg will store the average of the ten positive integers input.
The sum will be calculated by this formula: sum = sum + value For example, if the first value entered was 4 and second was 10: sum = sum + value = 0 + 4
sum = 4 + 10 = 14
Values and sum can be input and calculated within a repetition loop: while count <10
Input value
sum = sum + value End while
Avg can be calculated by: avg = value/count
A selection statement can be used inside the loop to make sure the input value is positive.
If value >= 0 then count = count + 1 sum = sum + value
Else
input value End If
(
7
)
Program Design:
Main
// This program will calculate the average of 10 integer numbers
// Declare variables
// Initialize variables
// Loop through 10 numbers
// Prompt for positive integer
// Get input
// test input value for gt 0 if (value > 0)
//Increment counter
//Accumulate sum Else
// display msg to enter a positive integer
// Prompt for positive integer
// Get input Endif
// End loop
//Calculate average
//Print the results (average)
End
Test Plan:
To verify this program is working properly the input values could be used for testing:
Test Case
Input
Expected Output
1
1 1 1 0 1
2 0 1 3 2
Average = 1.2
2
100 100 100 100 -100
Input a positive value
100 200 -200 200 200
Input a positive value
200 200
average is 120.0
NOTE: test #2 has 12 input numbers because there are two negative numbers.
Pseudocode: Main
// This program will calculate the average of 10 positive integers.
// Declare variables
Declare count, value, sum as Integer Declare avg as double
//Initialize values
Set count=0 Set sum = 0 Set avg = 0.0;
// Loop through 10 integers While count < 10
Input value
If (value >=0)
sum = sum + value count=count+1
Else
Pr *** Value must be positive *** Input value
End if End While
// Calculate average avg = sum/count
// Print results
End //End of Main
C Code
The following is the C Code that will compile in execute in the online.
An introduction to JavaScript that includes side-by-side comparisons with Python -- for journalism students. Based on the free JavaScript exercises/lessons at Codecademy: http://www.codecademy.com/tracks/javascript (Students in this course spent 4 weeks learning Python before they were introduced to JavaScript.)
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
In this lesson you will learn how to use basic syntax, conditions, if-else statements and loops (for-loop, while-loop and do-while-loop) in Java and how to use the debugger.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-basic-syntax-conditions-and-loops
See the blog post here: http://www.pubnub.com/blog/trackpad-destroyer-whos-got-the-fastest-fingers/
Ever wondered how many pixels you can scroll in 30 seconds? Ever had a friend tell you to scroll faster? Looking for a simple yet extremely addicting multiplayer game?
Introducing TrackPad Destroyer. The game is simple. Two players scroll their trackpads as fast as possible before the timer counts down to zero. Whoever scrolls more pixels wins.
Built at PubNub's Hackathon, Rongchao Fan walks you through how to make one of your own. Happy scrolling!
Similar to Java Guessing Game Number Tutorial (20)
Array Basics
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
(Optional) Variable-Length Argument Lists
The Arrays Class
Two-Dimensional Arrays
(Optional) Multidimensional Arrays
Fundamentals of Database Systems Questions and AnswersOXUS 20
Fundamentals of Database Systems questions and answers with explanation for fresher's and experienced for interview, competitive examination and entrance test.
Java GUI PART III is the continues of JAVA GUI PART I and II covering and discussing the GUI components with events and events handling as for instance Action Event, Mouse Event, Key Event, etc...
Java GUI PART II is the continues of JAVA GUI PART I covering and discussing the GUI components as well as the different available Layout Managers which is available in JAVA and you can find dedicated example for each Layout Managers …
A Graphical User Interface (GUI) is a user interface based on graphics i.e. icons, pictures, menus, etc. instead of just plain text, it uses a mouse as well as a keyboard as an input device.
GUI applications enable the users (especially naive ones) to interact with a system easily and friendly. This presentation is meant for the individual who has little or no experience in Java GUI programming.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...NelTorrente
In this research, it concludes that while the readiness of teachers in Caloocan City to implement the MATATAG Curriculum is generally positive, targeted efforts in professional development, resource distribution, support networks, and comprehensive preparation can address the existing gaps and ensure successful curriculum implementation.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
2. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
TABLE OF CONTENTS
Introduction ....................................................... 3
Problem statement .................................................. 3
Plan and Algorithm Solution ........................................ 4
Code Break Down Step By Step ....................................... 6
Variables Declaration and Initialization ......................... 6
Outer Loop and Inner Loop ........................................ 7
Outer Loop ...................................................... 7
Inner Loop ...................................................... 8
Conclusion ......................................................... 9
2
3. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
INTRODUCTION
In this program we are supposed to make a simple guessing game where the user / player
guess the number selected by the computer and the goal is to introduce the power and
usage of random as well as the how to benefit currentTimeMillis() method of the System
class in order to check how much it took the player guessing the number.
PROBLEM STATEMENT
It is worth having idea and knowledge how the guessing game works before jumping to the
code. When the player runs the program the computer will choose a random number
between 1 and 1000 and in the meanwhile the player will be prompted to guess a number
between 1 and 1000 until he / she guesses the correct number; for every guess, the
computer will either print "Your guess is too high", "Your guess is too low" or "your guess is
correct" . Finally at the end of the game, the guessed number will be shown along with the
number of guesses it took to get the correct number. See followings screenshots as demo:
3
4. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
PLAN AND ALGORITHM SOLUTION
Before jumping in the code it is worth planning and having a clear understanding of the
steps required building the program. Both plan and code is needed; but plan first and then
code.
Following steps will act as a map and guide-line enabling the programmer to write the code
easily and efficiently:
Create a new class including main() method
Create a constant MAX_NUMBER = 1000 indicating the highest guessing number
Generate random numbers between 1 and MAX_NUMBER which has the value of
1000 in our current case and scenario
Ask the computer choosing a number randomly and store it in a variable for later
use and comparison against the player guess.
Ask the player to guess and input a number between 1 and MAX_NUMBER
Keep track of number of guesses the player played and input
Check whether the player guess is either correct, too high or too low comparing
with the initial random selected number
Repeat the game until the player guess the correct number
Prompt the player the correct number and the total number of tries and how much
time it took the player
Next page demonstrates the complete source code of the Guessing Game Number and then
we will explain the source code piece by piece …
4
5. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
import java.util.Random;
import javax.swing.JOptionPane;
public class GuessingGameNumber {
public static void main(String[] args) {
// declare and initialize the required variables
final int MAX_NUMBER = 1000;
Random rand = new Random();
int guessed = 0;
int choice = 1;
String input = "";
// these calculate and display the execution time
long start, end, duration;
// outer loop ask whether you want to continue the game(YES/NO)
do {
int selected = rand.nextInt(MAX_NUMBER) + 1;
int count = 0;
start = System.currentTimeMillis();
// inner loop prompt you if your guess is high, low or correct
do {
input = JOptionPane.showInputDialog("Let's play the guessing game.n"
+ "Guess a number between 1 AND " + MAX_NUMBER);
guessed = Integer.parseInt(input);
count++;
if (guessed > selected) {
JOptionPane.showMessageDialog(null, "You guessed ""
+ guessed + "". Your guess is high!");
} else if (guessed < selected) {
JOptionPane.showMessageDialog(null, "You guessed ""
+ guessed + "". Your guess is low!");
} else if (guessed == selected) {
JOptionPane.showMessageDialog(null, "WOW! You guessed ""
+ guessed + "". Your guess is correct");
}
} while (selected != guessed);
end = System.currentTimeMillis();
duration = end - start;
JOptionPane
.showMessageDialog(null,
"You guessed correctly. nThe correct guess was ""
+ selected + "".nYou tried " + count
+ " times, and " + (duration / 1000d)
+ " seconds.");
choice = JOptionPane.showConfirmDialog(null,
"Do you want to play again?", "Confirmation",
JOptionPane.YES_NO_OPTION);
} while (choice != JOptionPane.NO_OPTION);
JOptionPane.showMessageDialog(null, "Thanks for playing");
}
}
5
6. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
CODE BREAK DOWN STEP BY STEP
First and foremost
we will start the program by creating a new class named
"GuessingGameNumber.java" including the main method as follow:
public class GuessingGameNumber {
public static void main(String[] args) {
}
}
VARIABLES DECLARATION AND INITIALIZATION
Next step is to declare the required variables and initialize them to their default value in
case it is needed as follow:
// declare and initialize the required variables
final int MAX_NUMBER = 1000;
Random rand = new Random();
int guessed = 0;
int choice = 1;
String input = "";
// these calculate and display the execution time
long start, end, duration;
NOTE:
Please notice you will get an error message when you try to use the Random class
complaining that either you create the class or import it from the java class library.
Therefore, you need to import the class using the Jave import statement at the very top of
the program as follow:
import java.util.Random;
Please note that The same case is true while using the classes which are out of the
java.lang.* packages for example the JOptionPane class which resides under the javax.swing
package.
6
7. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
OUTER LOOP AND INNER LOOP
do {
do {
} while (selected != guessed);
} while (choice != JOptionPane.NO_OPTION);
OUTER LOOP
When the program ends the Outer Loop is responsible giving option to the player if he / she
still would to continue playing as well as resets the all the options i.e. the initial random
selection, reset the start time and initial counter, etc.
do {
int selected = rand.nextInt(MAX_NUMBER) + 1;
int count = 0;
start = System.currentTimeMillis();
// inner loop prompt you if your guess is high, low or correct
} while (choice != JOptionPane.NO_OPTION);
The variable selected store the initial guess of the program by the computer which
is a number between range of 1 and 1000.
The variable count is initialized with values of zero which keeps track of the number
of times it took the user to guess the correct number.
The variable start keeps track the game start time in order to calculates how much
time it took the user to guess the correct number.
Finally the while with condition executes when the player guess the number
correctly and give the player the option of playing again and/or stop the game.
7
8. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
INNER LOOP
On the other hand the Inner Loop responsible comparing the player guess against the
computer guess and then provides input option each time the user guess is incorrect.
// Outer Loop Begin
do {
input = JOptionPane.showInputDialog("Let's play the guessing game.n"
+ "Guess a number between 1 AND " + MAX_NUMBER);
guessed = Integer.parseInt(input);
count++;
if (guessed > selected) {
JOptionPane.showMessageDialog(null, "You guessed ""
+ guessed + "". Your guess is high!");
} else if (guessed < selected) {
JOptionPane.showMessageDialog(null, "You guessed ""
+ guessed + "". Your guess is low!");
} else if (guessed == selected) {
JOptionPane.showMessageDialog(null, "WOW! You guessed ""
+ guessed + "". Your guess is correct");
}
} while (selected != guessed);
end = System.currentTimeMillis();
duration = end - start;
JOptionPane.showMessageDialog(null, "You guessed correctly. nThe correct guess
was "" + selected + "".nYou tried " + count + " times, and " + (duration /
1000d) + " seconds.");
choice = JOptionPane.showConfirmDialog(null,
"Confirmation", JOptionPane.YES_NO_OPTION);
"Do
you
want
to
play
again?",
// Outer Loop End
As it was mentioned the Inner Loop is responsible to provide entry option to the player
using JOptionPane.showMessageDialog() method. It is worth mentioning everything reads
from the keyboard is String and needs to be converted to int using the Integer.parseIn()
method. Finally compare it against the computer guess as follow:
if (guessed > selected) {} // if player guess is higher than computer guess
if (guessed < selected) {} // if player guess is lower than computer guess
if (guessed == selected) {} // if player guess is equal computer guess
When the guess is correct then the time will be recorded and the start time subtracted to
calculate the amount of time it took the player and finally prompt the user with details.
8
9. Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
CONCLUSION
You have noticed we have used Random class in this application to generate random
numbers of integers in a specific range. Random class has many other useful
methods where gives the power to generate random floating point numbers, etc.
Using random concept inside the program has much usages in many application
programs and areas for instance Lottery Applications, Random Advertisement,
Random Security Images, Random Questions with Random Options, etc.
In addition, we have used currentTimeMillis() method in this application to calculate
how much time it took the player to guess the correct guessed number. This method
is so usable in many other environments and cases such as optimization and
measurement of algorithm, killing the execution process if the execution process
took longer abnormal time, etc.
9