0% found this document useful (0 votes)
0 views

Java+Game

The document provides a comprehensive overview of Java programming concepts, including conditional statements, loops, branching statements, classes, objects, strings, arrays, and HashSets. It includes code examples to illustrate each concept and discusses the syntax and usage of various Java features. Additionally, it outlines the structure of a simple Tic Tac Toe game implementation in Java.

Uploaded by

Smridh Sud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Java+Game

The document provides a comprehensive overview of Java programming concepts, including conditional statements, loops, branching statements, classes, objects, strings, arrays, and HashSets. It includes code examples to illustrate each concept and discusses the syntax and usage of various Java features. Additionally, it outlines the structure of a simple Tic Tac Toe game implementation in Java.

Uploaded by

Smridh Sud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Java Game in 45 minutes

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Table of Content

● Conditional Statements
● Loops
● Branching Statements
● Object and Class
● Strings
● Arrays
● HashSet

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Conditional Statement : if else

● consist of 2 keywords, if and else

● This is a way where there are 2 paths possible


depending upon a condition

● if condition manipulates to true then if gets executed


otherwise code is else will execute

● you can multiple else if followed by else if there are


more possible paths.

● Also nested if and else are possible

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Output:
Output:
public class IfElseDemo {
num
numare
are equal
public static void main (String[] args) {
equal
int val1=5,val2=6;
if(val1 + val2 ==11)
System.out.println("num are
equal");
else
System.out.println("num are
not equal");
}
}

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Conditional Statement : switch
● It is an elegant way to replace multiple else-if
● Syntax:
switch(expression)
{
case val: ... ;
break;
case val: ... ;
break;
default: ...;
}
● Here depending upon the answer evaluated by the condition, case code gets executed.
● every case must be followed by break unless it is required not to as per logic. Otherwise,
all cases will start executing from the matched case till either break is encountered or all
cases gets exhausted
● default is optional and holds the code which should be executed if no catches gets
matched.
● val can be integer, char or String in java.
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
public class SwitchDemo {
public static void main (String[] args) { Output:
String day="sun"; Today is sunday
switch(day)
{
case "mon": System.out.println("Today is monday");
break;
case "tues": System.out.println("Today is tuesday");
break;
case "wed": System.out.println("Today is wednesday");
break;
case "thurs": System.out.println("Today is thursday");
break;
case "fri": System.out.println("Today is friday");
break;
case "sat": System.out.println("Today is saturday");
break;
case "sun": System.out.println("Today is sunday");
break;
default : System.out.println("day is invalid!");
}
} Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Loops - for
● It is best to use when we know the specified number of times the code should
execute.
● Syntax:
for( initialization; termination; updation){
}

○ initialization - is used to initialize the variable, which is being used for


iteration.
○ termination - comprises conditions which determine till when iteration will
continue.
○ updation - how our variable will get updated.

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
public class ForLoopDemo {
public static void main (String[] args) {
for(int itr=0;itr<5;itr++)
System.out.println("cur iteration : "+itr);
}
}

Output:
cur iteration : 0
cur iteration : 1
cur iteration : 2
cur iteration : 3
cur iteration : 4
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Loops - while
● It is optimal when we know the specified expression whose value dictates
the times the code should execute.
● Syntax:
while( expression ){ }
expression- is used to dictate the condition who is responsible for loop
continuation.

● Example:
public class WhileForDemo {
public static void main (String[] args) { Output:
int count=0; cur iteration : 0
while(count<5){ cur iteration : 1
cur iteration : 2
System.out.println("cur iteration : "+count);
count++; cur iteration : 3
} cur iteration : 4
}
} Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Branching statement - break
● It is a keyword that basically terminate the current loop and moves execution out of
the loop
● Syntax:
for(.........){
break;
} ==>execution comes here when break is encountered
● Example:
public class BreakDemo {
public static void main (String[] args) { Output:
int itr=0; cur iteration : 0
while(itr<5){ cur iteration : 1
System.out.println("cur iteration : "+itr); cur iteration : 2
itr++; Out of loop!
if(itr==3) break;
}
System.out.println("Out of loop!");
} Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Branching statement - return
● It returns from its block of code i.e, if it is inside a function then it will exit
from it.
● Syntax
main(.........){
return;
}
==>exists from the program
Example:
public class ReturnDemo {
public static void main (String[] args) { Output:
for(int count=0;count<5;count++){ cur iteration : 0
if(count==3) return; cur iteration : 1
System.out.println("cur iteration : "+count); cur iteration : 2
}
System.out.println("Out of loop!");
}
} Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Class
● It is a blueprint of a real life entity
● It consists of the data members and methods.
● Basically it is the implementation of Encapsulation which is one of the OOPs pillars.
● Keyword class is used to declare the class in java
● As per naming convention, classname follows that the first letter of every word
should be in uppercase.
● In java, all code must be in some class and single document can have multiple
classes but only 1 public class

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Class Demo

class Container{ void setPrice(int p){


price=p;
//data members }
int weight; void print(){
String color;
double price; System.out.println(weight+"
"+color+" "+price);
//methods }
void setWeight(int w){ }
weight=w;
}
void setColor(int c){
color=c;
}
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Object
● It is basically a physical entity of class.
● It is a class's instance
● new keyword is used to create objects and allocate memory in Heap.
● When we create an object, it calls for the constructor of class.
● Example:
Container c1=new Container();

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
String
● String is basically a sequence of characters.
● It's a class in java
● There are 2 ways to create a string
○ String str = "hello";
○ String str = new String("hello");

● We have special memory termed as string constant pool inside heap and,
○ In the first way, a copy is created in heap and in SCP too if it was not
already there.
○ In the second way, copy is created in heap only.

● String can also be create using char array


char[] ch={'h','e','l','l','o'};
String str=new String(ch);
● String is immutable that means once created it cannot be manipulated.
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Strings Comparison
To compare Strings, there are 3 ways:
● == : checks for same reference
● .equals() : checks for same content
● .compareTo() : compares content lexicographically
○ return +ve num : str1>str2
○ return -ve num : str1<str2
○ return 0 : str1==str2

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
public class StringDemo {
public static void main (String[] args) {
String s1=new String("cat");
String s2="cat"; Output:
String s3="cat"; false
System.out.println(s1==s2); true
System.out.println(s2==s3); false
System.out.println(s1==s3); true
System.out.println(s1.equals(s3)); 0
System.out.println(s1.compareTo(s2));
}
}

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
String Methods
public class StringDemo { Output:
public static void main (String[] args) { 16
String str="Today is monday."; today is monday.
System.out.println(str.length()); TODAY IS MONDAY
System.out.println(str.toLowerCase()); true
System.out.println(str.toUpperCase()); 9
System.out.println(str.contains("is monday")); y is
System.out.println(str.indexOf("monday")); Today is tuesday.
System.out.println(str.substring(4,8));
System.out.println(str.replace("monday","tuesday"));
}
}

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Arrays
● Linear Data Structure
● Elements are stored in contiguous memory locations
● Can access elements randomly using index
● Stores homogeneous elements i.e, similar elements
● 1D Array Syntax:
Array declaration
datatype varname []=new datatype[size];
datatype[] varname=new datatype[size];
● 2D Array Syntax:
Array declaration
datatype varname [][]=new datatype[size][size];
datatype[][] varname=new datatype[size][size];
● Can also do declaration and initialization at once

○ Datatype varname [] = {ele1, ele2, ele3, ele4};

○ Datatype varname [][] = {{ele1, ele2}, {ele3, ele4}};

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Advantages
● Random access
● Easy sorting and iteration
● Replacement of multiple variables

Disadvantages
● Size is fixed
● Difficult to insert and delete
● If capacity is more and occupancy less, most of the array gets wasted
● Needs contiguous memory to get allocated

Applications
● For storing information in linear fashion
● Suitable for applications that requires frequent searching

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
import java.util.*;

class JavaDemo { Output:


public static void main (String[] args) { 123456
int[][] priceOfPen= new int[3][2]; Batch nos:
int[] batch= new int[3]; 234 567 890
Scanner in=new Scanner(System.in);
for(int i=0;i<priceOfPen.length;i++)
for(int j=0;j<priceOfPen[0].length;j++)
priceOfPen[i][j]=in.nextInt();
for(int i=0;i<batch.length;i++)
batch[i]=in.nextInt();

for(int i=0;i<priceOfPen.length;i++)
for(int j=0;j<priceOfPen[0].length;j++)

System.out.print(priceOfPen[i][j]+" ");
System.out.println("\nBatch
nos:");
for(int i=0;i<batch.length;i++)
System.out.print(batch[i]+" ");
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
HashSet
● HashSet store the elements as per the hash function.
● Here insertion order is not maintained.
● It helps in fetching the elements in O(1) time.
● It’s in java.util package.
● Constructor

○ HashSet<Type> hs = new HashSet<>();


● Some methods

○ public int size(); //to find the size of hashset

○ public boolean isEmpty(); //to check if hashset is empty

○ public boolean contains(java.lang.Object); //to check if hashset contains object

○ public boolean add(java.lang.Object); //to add element if hashset

○ public boolean remove(java.lang.Object); //to remove element from hashset

○ public void clear(); //to clear hashset


Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
import java.util.*; Output:
[3, 5, 12]
class Main { false
public static void main (String[] args) { [3, 5]
HashSet<Integer> hs=new HashSet<>(); false
hs.add(5); []
hs.add(12);
hs.add(3);
System.out.println(hs);
System.out.println(hs.isEmpty());
hs.remove(12);
System.out.println(hs);
System.out.println(hs.contains(12));
hs.clear();
System.out.println(hs);

}
}
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Let’s Create & Print Our GameBoard
import java.io.*;
static void print_board(char [][]g_board)
import java.util.*;
{
class TicTacToe {
for(int i=0;i<g_board.length;i++)
public static void main (String[]
{
args)
for(int j=0;j<g_board[0].length;j++)
{
{
SOP(g_board[i][j]);
char[][] g_board ={
}
System.out.println();
}
{ ' ','|',' ','|',' '},
}
{ '-','-','-','-','-','-'},
{ ' ','|',' ','|',' '},
{ '-','-','-','-','-','-'},
{ ' ','|',' ','|',' '}
};
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
print_board(g_board);
Filling O(zeros) and X(cross)

static void place_holder(char [][]g_board,int switch(position_in_board)


position_in_board,String user) {
{ case 1:
char syb='X'; g_board[0][0]=syb;
if(user.equals("You")) break;
{ case 9:
syb = 'X'; g_board[4][4]=syb;
break;
ur_set.add(position_in_board);
} default:
System.out.println("Invalid
else if (user.equals("Comp")) Input");
{ }
syb = 'O'; System.out.println();

comp_set.add(position_in_board); print_board(g_board);
} }
else
System.out.println("Invalid
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Main Method

For the user:


Scanner in = new Scanner(System.in);

while(true) // Repeated until Result

System.out.print("Enter any number from 1 - 9:");


int user_pos = in.nextInt();
while(ur_set.contains(user_pos)|| comp_set.contains(user_pos))
{
System.out.println("Postion is already taken.TryAgain");
System.out.print("Enter any number from 1 - 9:");
user_pos = in.nextInt();
}

place_holder(g_board,user_pos,"You");

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Main Method
For the cpu:

int com_pos = gen_random();


while(ur_set.contains(com_pos)|| comp_set.contains(com_pos))
{
com_pos = gen_random();
}
place_holder(g_board,com_pos,"Comp");

static int gen_random()


{
int max=9;
int min=1;
int range = max-min+1;

int res = (int) (Math.random() * range)+ min;

return res;
}
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Global Sets of Player1 and Player2 :

static HashSet<Integer> ur_set = new HashSet<Integer>();


static HashSet<Integer> comp_set = new HashSet<Integer>();

Checking the winning conditions for both players:

String res = checking_winner(); //Winner String


if(res.length()>0)
{
System.out.println(res);
break;
}

Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
static String checking_winner(){
HashSet<Integer> r1=new HashSet<Integer>(); for(HashSet l : check) {
r1.add(1);r1.add(2);r1.add(3);
HashSet<Integer> r2=new HashSet<Integer>(); if(ur_set.containsAll(l))
r2.add(4);r2.add(5);r2.add(6); return "YOU WON";
HashSet<Integer> r3=new HashSet<Integer>();
r3.add(7); r3.add(8);r3.add(9); else if (comp_set.containsAll(l))
HashSet<Integer> c1=new HashSet<Integer>(); return "YOU LOSE";
c1.add(1);c1.add(4);c1.add(7); }
HashSet<Integer> c2=new HashSet<Integer>();
c2.add(2);c2.add(5);c2.add(8); if (ur_set.size()+comp_set.size()==9)
HashSet<Integer> c3=new HashSet<Integer>(); return "ITS A
c3.add(3);c3.add(6);c3.add(9); DRAW";
HashSet<Integer> d1=new HashSet<Integer>();
d1.add(1);d1.add(5);d1.add(9); return "";
HashSet<Integer> d2=new HashSet<Integer>(); }
d2.add(3); d2.add(5);d2.add(7);
HashSet<HashSet> check = new
HashSet<HashSet>();
check.add(r1);check.add(r2);check.add(r3);
check.add(c1);check.add(c2);check.add(c3);
check.add(d1);check.add(d2);
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Thank You
Proprietary content. © Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.

You might also like