Overview of the Tutorial
This video tutorial guides viewers through the process of coding the classic game Pac-Man in Java. The tutorial begins with a demonstration of the final game, showcasing features such as movement, collision detection, and game over conditions. The instructor emphasizes the importance of setting up the development environment and provides links to additional resources, including the Java Programming Course: Introduction, Structure, and Setup Guide.
Key Steps in the Tutorial
-
Setting Up the Environment:
- Use Visual Studio Code for coding.
- Create a new Java project named "Pacman".
- Download necessary images and code from GitHub.
-
Creating the Game Window:
- Define the size of the game window based on tile size and map dimensions.
- Use
JFrame
to create the game window andJPanel
for drawing.
-
Loading Images:
- Load images for Pac-Man and ghosts using
ImageIcon
. - Store images in member variables for easy access.
- Load images for Pac-Man and ghosts using
-
Implementing the Tile Map:
- Create a 2D array to represent the game map.
- Use characters to denote walls, food, and ghosts.
-
Drawing the Game Elements:
- Override the
paintComponent
method to draw walls, food, and characters on the screen. - Use a game loop to continuously update the display.
- Override the
-
Handling User Input:
- Implement
KeyListener
to control Pac-Man's movement. - Update Pac-Man's direction based on arrow key presses.
- Implement
-
Collision Detection:
- Create a method to check for collisions between Pac-Man, walls, and ghosts.
- Implement logic to handle game over conditions and life tracking.
-
Scoring System:
- Track the score and lives remaining.
- Update the score when Pac-Man eats food pellets.
-
Game Restart and Levels:
- Allow the game to restart upon pressing any key after game over.
- Implement level progression when all food is eaten.
Additional Features to Implement
- Teleportation through the left and right borders.
- Pause functionality using a specific key.
- High score tracking.
- Power pellets and additional game mechanics.
Conclusion
The tutorial concludes by encouraging viewers to expand on the basic game mechanics and add their own features. The instructor invites feedback and questions in the comments and encourages viewers to subscribe for more tutorials. For those interested in learning more about Java fundamentals, check out Java Course Introduction: Mastering Coding Fundamentals and Data Structures and Java Basics: Outputs, Variables, and User Input Explained.
hey there hope you're having a wonderful day in this video we're going to be coding the game Pac-Man in Java so what
you see here is the final result of this tutorial and currently we have game over but if I press any key it will restart
the game so let's press a key and you can see Pac-Man is moving around collecting the food pellets and if
Pac-Man hits a wall it stops moving and I can change directions so I can move right down left down and if Pac-Man
collides with the ghost on the top left corner you can see we lose one life and again I just collided with the
ghost and now I'm down to one life and if I collide with the ghost one more time
we get game over and of course if I press any key again it will restart the game and I can continue playing the game
okay all right so before we start coding the game I just want to quickly mention that
on my YouTube channel you'll find various tutorials So currently I'm working on data structures and
algorithms in Python and beginner C++ and I have many game tutorials so I have tutorials for python so I have games
such as snake and tic tac toe and for Java I have match cards with Pokemon cards Space Invaders Flappy Bird
Blackjack mind sweeper snake and so on and for JavaScript I have Doodle Jump breakout Flappy Bird Space Invaders wo
2048 mind sweeper Kenny crush and so on so if you want to step to date on any new tutorials make sure you subscribe to
the channel and again you can find the list of tutorials on my channel as well as on kenip coding.com all right so for
this tutorial I will be using visual studio code and if you want to learn how to set up visual studio code with Java I
have a tutorial on that and I'll link the video in the description below all right let's begin press contrl shift p
at the same time look for Java create Java project no build tools and I will create
this project on my desktop and for the project name I will call it
Pacman all right I have my project folder and within my Pacman folder I have this Source folder with app.
Java and this is going to be our main file where we run our code so I can just click on this run button and you can see
we get Hello World all right so the first thing I want you to do is go to the video description and click on the
GitHub link the GitHub link will contain the completed code for the Pac-Man game as well as the images that we need for
the game so click on the GitHub link and download those files and here you can see we have our images we have the blue
Ghost orange ghost pink ghost and red ghost and we have these Pac-Man directions I've also included the scared
Ghost and the Cherry but in this tutorial we will not be implementing those features instead I just want to
focus on The Ghost and the Pac-Man but uh yeah once you downloaded the files just take the images and drag
and drop them to your Source folder so you should see these images all right right so now they're
all in my source folder all right so after you've done that let's start coding now the first
thing we need is a window for our game so I'm going to delete this line and over here I'm going to
import Java x. swing. jframe and the jframe is going to be our
window so before we create our window we need to determine how big we want the window to be so we need to specify a
width and a height so here we have a tile map which represents the map of our game and we
are going to divide the game window into tiles or squares in this case we have 19 columns
so starting from 0 to 18 because index starts at zero we have from 0 to 18 that is 19 columns and for the rows we have 0
to 20 so in total we have 21 rows and each one of these tiles is 32 pixels by 32 pixels so this means that the width
of our window going from left to right is 19 columns * 32 pixels and likewise the height is going to be 21 rows * 32
pixels okay so that's how we're going to define the width and height of our game and in a bit I'll explain how this tile
Map works so let's go ahead and Define some variables so we have an INT row count and I'm going to set this to 21
and int column count this is going to be 19 and we need to define the tile size so int tile size is equal to
32 so this means int board width is equal to column count time tile size and in Board height is equal to row count
time tile size all right so we have our width and height now let's create our window so I'm going to create a jframe
and the frame is basically the window so we'll call this Frame is equal to new jframe and here I can pass in a string
that will be the title of our window so I'm going to call this packman and let's make the window
visible so frame. set visible and I'm going to set this to true and I want the window to appear at
the center of our screen so frame. set location relative to and I'm going to make this null and let's make it so that
the player cannot resize the window so we don't want the user to use the mouse to expand the width and height of the
window so frame. set resizable and I'm want to make this false and finally we want the game to
terminate if the player clicks on the x button of the window so I'm going to do frame. set default closing operation JF
frame. exit on close all right oh and one more thing I almost
forgot let's set the size so frame. set size and I'm going to make it board width and Board
height all right let's save and run the program and you can see we have our game window all right so we have our window
the next thing we need is a j panel and the J panel is what we're going to be drawing on to show our game now I could
make a j panel here but instead what I'm going to do is I'm going to create another Java class file so I'm going to
go to Source folder right click new Java file and I'm going to select class and here I'm going to call it
Pac-Man so the idea here is I'm going to have Pac-Man inherit J panel and for those of you who don't know what
inheritance means basically I'm going to have this Pac-Man class inherit the jpanel class so that this class is
basically a version of jpanel except I can add more properties for the game so here I'm just going to import a few
things so import java. aw. asterisk import java. aw. event.
asteris import java. .set and then import java. u. random and import Java x. swing.
asterisk all right so we're going to have Pacman inherit jpanel so I'm going to to have this Pac-Man class extends J
panel and here I'm going to define a few properties so I'm just going to copy and paste this and paste it over here so our
J panel will have the same size as our window so I'm just going to make these properties
private and now let's create a Constructor so Pac-Man and I'm going to set preferred size and
for preferred size I need to specify a dimension so I'm going to create new dimension board
width and Board height and for the game I'm going to make the background color black so set
background color. black all right so we have our J panel and and I'm going to go back to
our app. Java file and I want to create an instance of this jpanel now so Pac-Man Pac-Man game is equal to new
Pac-Man all right so we have the J panel and I need to add this panel onto our window so frame. add
Pac-Man game and we want to make sure that we get the full size of the jpanel within
our window so I'm going to do frame. pack and here I'm going to copy and paste this so usually you don't want to
set your window visible until you have all the components in the window so I'll make the frame visible after I've added
the Pac-Man game J panel all right now let's save and run the program and you can see we have our Pac-Man game and you
can tell because the background color is black all right so we have our window now we need to create the game and the
first thing I want to do is load the images for our game and for the images we're going to
create member variables to store the images and the first one is going to be the wall image so private Image Wall
image next we need to load the images for the ghost so I'm going to create member variables for the ghost images so
private image blue ghost image and I'm just going to copy and paste this and I'm going to change each one so
this one is going to be orange ghost then we have pink ghost and then Red Ghost all right so make sure the images
are spelled correctly and then finally we have another four set of images and this will be for the Pac-Man so private
image Pac-Man up image and I'm going to copy and paste this and we're going to change this to
up down left and right and in our Constructor
I'm going to load the images so let's load the wall image first so wall image is equal to New
Image icon get class. getet resource and here we need to specify the file
path of where the image is so get class refers to this Pac-Man class and this file is located in our source folder and
our images are located in the same folder so here I'm going to do string do slash so the do slash means that we are
going to look from the same folder as the starting point and we just need to specify the image name so the wall is
going to be wall. PN and so this is going to create an image icon but instead we want the image so
I'm going to do do get image all right and I'm just going to repeat this for The Ghost and Pac-Man and all of these
images are PNG files so they're not animated so we're going to have static images unfortunately I couldn't find the
Sprites for the game so I had to create the pixel art myself but uh yeah so let's just continue loading the images
so I'm just going to copy and paste this and here I'm going to change this to Blue ghost image and the file name is
called Blue Ghost so blue Ghost and I'm just going to copy and paste
this this is going to be orange ghost image and we're going to change this to Orange and then this one is going to be
pink ghost image and we're going to change this to Pink and we have red ghost image
and we'll change this to red and let's do the same for Pac-Man so this will be Pacman up image and this
will be called Pacman up.png and let's just copy and paste this and this will be down Pacman
down left left
right and right and make sure the image name are all correct so that's all you need to
load the images and these images will be stored in these variables all right the next thing we
need to talk about is the tile map so here we have a tile map and this is basically how we're going to map out all
the tiles in our game so this is going to be represented as a 2d array and I will be using characters you could use
numbers but I will use characters because I think it's easier to write out so I'm going to use an array of strings
an array of strings is basically an array of an array of characters so you can think of each row as a string within
our array each tile is going to be represented by a character and if the character is at X this means we need to
place a wall here and we have empty tiles so this is a white space in this case if we have a white space I'm going
to place a food here now in a lot of games if it's actually empty then we make it nothing but I'm going to do the
opposite so this o here means that it is empty so it's a lot easier for me to just place a few O's here instead of
putting O's everywhere okay so remember basically if it's a white space we're going to place a food and if it's an o
that means no food it is empty and then we have r b p and O these are all in lowercase R stands for red b stands for
blue p is Pink again o is orange and the reason why I use lowercase is because Pac-Man also starts with p so I'm going
to represent Pac-Man with an uppercase p and I'm going to iterate through our tile map and create objects so how this
works is I'll start at 0 so 0 is the top left corner of our screen so if I want to say what is this point here for this
tile we have 1 2 3 4 for the x axis so four to the right and we have 1 1 2 down so the XY coordinate for that tile is
going to be 4 2 but remember this is four tiles to the right and two tiles down so pixel-wise we need to multiply
each one by the tile size 32 so this is going to be 4 * 32 which is 120 pixels to the right and down will be 32 * 2 so
64 pixels down okay and from here we need to specify the the width and height so the width is going to be the tile
size which is 32 pixels and the height is going to be the tile size as well so 32 pixels so starting from here we're
just going to iterate through our tile map so we start at 0 0 at the zeroth row and I check is there an X here if so we
have a block and then I jump to the next column which is the next tile size over and I see there's an X so I create
another block and then I jump to the next one and then the next one and so on and then after I clear this row we have
our second row which is at index one so here we have an X so that's a block and then I jump to the next one this is
empty so I put a food here jump to the next one this is empty so I put a food here jump to the next one this is empty
and I put the food here and so on basically we iterate through the tile map and if we get it next we create a
block and if we get RB P or o we have a ghost and if we have empty tile that is the food and the p is Pac-Man so we have
three things that we have multiple of which is the wall block the food and the ghost so I'm going to store all of these
in three different hash sets so that we can iterate through them the Pac-Man since there's only one Pac-Man we do not
need to store a Pac-Man in a hash set so I would just create a Pac-Man variable for
Pac-Man and the reason why I use a hash set instead of an array list is because if you know your data structures and a
algorithms when I check for Collision it is easier to search in a hash set instead of an array list so this is just
for performance purposes a hash that is very similar to an array list if you don't know uh you can look it up later
on but it's pretty much similar to an array list except the performance is better for looking up values and in a
hashset all the values are unique so you can't have duplicates in this case we're not going to have any duplicate
objects all right so in order to draw each image I need to specify where it is so the X and Y position and the width
and height and I need to store all this information for each wall food and Ghost and the Pac-Man so the best way to store
this information is just create a class to represent this object so I'm going to create a class
called block and we have a few things we have the X position y position with
height and image and just for restarting the game we want to save the original X and Y
starting positions because as the game goes on The Ghost and Pac-Man will be moving around so the X and Y positions
will be changing so we need to save the starting X and Y positions all right now let's create the
Constructor and and I'm going to take in an image the X position the Y
position the width and the height so this. image is equal to image this. X is equal to X this. Y is
equal to Y with height and we're going to set the
start x equal to X as well and start y equal to Y and down here let's create some hash
sets so hash set of block and I'm going to call this walls we'll create another
one this will be foods and then we have ghost and finally we just have one block to represent
Pac-Man all right so now we have our representation of the objects in our game the next thing we need is the tile
map in my case the tile map is going to be an array of strings which is an array of array of
characters all right so for the tile map I'm just going to copy and paste it here and I will leave this piece of code in
the video description you can also get this code in the completed code from the GitHub repository so here we have an
array of strings and each string is a row within our game so again X is the wall O is just skip don't do anything
uppercase P is for Pac-Man and the white space is for the food and of course we have the ghost so B is blue o is orange
p is pink and R is red which is over here all right so we have our tile map and now I want to go through the tile
map and create the objects for the Walls Foods ghost and Pacman so down here I'm going to create another function public
void and I will call this low map so in the beginning I need to initialize all the hash sets so walls is
equal to new hash set of block Foods is equal to new hash set of block we have
ghost new hash set of block all right so now we need to iterate through the map so for int R so
R stands for row go zero R less than row count r++ for INT C is equal to zero so C is
for column C less than colum count
C++ I'm going to get the current row so string row is equal to TI map index of R and we need to get the curent current
character so car tile map car is equal to row. car at C all right so we have the character at this specific tile but
we need to figure out where this tile is so remember to draw you need an X and Y position as well as a width and height
so the width and height are going to be tile size so we just need the X and Y position so to get the EXP position we
need to see how many columns we are from the left so this is C * tile size so how many tiles from the left and
the Y position is going to be how many rows from the top so R * tile size so just very quickly if I want to
know what is the X and Y position of this tile we need to know how many tiles from the left so how many columns 1 2 3
4 so this is four columns and we multiply this by tile size which is 32 to get the actual ual pixel value and
for the Y position it is 1 2 3 so this is three tile size so three down so this will be 3 * the tile size okay so we are
calculating the X and Y position every time as we iterate through this 2D array all right so if tile map character is
equal to X this means we have a wall so I'm just going to create a block block wall new block and we need to pass in
the image X Y width and height so wall image X Y tile size and tile size and then we just need to add this block to
the walls hashset so walls. add wall now if it's not in X else if tile map car is equal to lowercase
b this is the blue Ghost so I'm going to create a block called ghost new block blue ghost image X Y tile size tile
size and then we do ghost. add ghost so let's copy and paste this for the other three
ghosts and this one is going to be the orange ghost so orange ghost image and then we have the pink ghost so pink
ghost image and finally we have the Red Ghost all right and then we have else if
tile map car is equal to uppercase P that is Pac-Man in this case we will do Pac-Man is equal to new block and by
default I'll just have Pac-Man face the right side so Pac-Man and write image X Y tile size tile size else if tile map
car is equal to a white space and that is the food so block food is equal to new Block in this case we don't have an
image instead I would just programmatically draw a rectangle so for image I will set it to null and this
will be a little tricky so we need to do some math here the rectangle is going to be small so it's not going to be 32
pixels by 32 pixels so for the X and Y position I will create an offset of 14 so X will be x + 14 and Y will be y +
14 and the width is going to be 4 pixels and the height is going to be 4 pixels and then I'll do foods. add food so
basically for the food we have this tile and we want the tile to be in the middle like so so we have four pixels by 4
pixels we need to fill in the Gap so if the height and width are both 32 pixels we do 32 - 4 that's 28 and then we
divide by 2 which is 14 so 14 14 so this means we need to take this tile starting from the top left corner move right by
14 and then move down by 14 and then from here we can draw the food all right and that's it for our map
codes we do have one more which is the Big O which is empty skip so there's no point in me adding that check because
we're not going to do anything so in our Constructor I'm just going to call load map and let's just add some print
statements to see how many walls foods and ghosts we have so system.out.print line walls do size and
then let's do the same foods and ghosts all right now let's save and Runner program and we get
196 walls 184 food pellets and four ghosts and of course we have our game window all right so we know our load map
is working we have all the objects in our hash sets so I'm just going to get rid of these print statements all right
so now that we have our objects let's draw all of them onto our game so down here I'm going to create a new function
called Paint component and it's going to take in graphics
G and I'm going to do super. paint component so basically it's going to invoke the function of the same name
from J panel so that's what super does and then after that we can just call a draw function and pass in G so down here
I'm I'm going to create a draw function that takes in graphics G so as an example I'm going to show you
how to draw a rectangle so if I want to draw Pacman right now we have Pacman as a block object and it has the
information XY position and width and height so I can do g. fillrect Pacman dox Pacman doy Pacman dowith and
pac-man. height and now if I save and run the program we get our Pac-Man over here okay so instead of a rectangle I'm
going to draw an image so this will be g. draw image and the parameters are similar except we need to place the
image in the front so pac-man. image and at the end I'm just going to pass in null so there are six
parameters and the last one we don't need so I'm just going to pass in no and let's save and run the program and as
you can see we have Pac-Man over here all right now let's do the same for the rest of the objects in our hash sets so
for Block ghost ghost we're going to do g. draw image ghost. image ghost. X ghost. Y
ghost dowith ghost. height n null and if I save and run the program you can see we have our four ghosts over
here and let's do the same for the walls and food so for black wall walls g. draw image wall. image wall. X
wall. Y wall. width wall. height n null and let's do the same for the food so block
food Foods and remember we don't have images for the food instead we're drawing
rectangles so I'm going to do g. fillrect food dox food doy food. width and food.
height and before I do this I'm going to set the color to white so g. set color color.
white all right now let's save and run the program and here you can see see we have
our map and what's cool about this is now that I have my code to load the map I
can just modify the tile map here so let's say Pacman is over here I can add an X here and an X here and if I save
and run the program you can see I've just added a block to the left and right of Pac-Man
but I'm going to undo that and basically I want to encourage you to design your own tile map if you want and you can
create your own layout for the Pac-Man game after this tutorial but uh yeah let's continue on so we have our tile
map and we have all the Walls Foods and ghosts and we're drawing all the objects now the thing here is when we run our
code this paint component only gets called once and therefore we only draw one time now in a game we are constantly
moving all the characters so The Ghost and Pac-Man move up down left and right and we need to constantly redraw on the
J panel to to reflect those new positions and to do that we need a game Loop and here I'm going to
implement action listener and I'm going to hover over Pac-Man and you can see we need to do a quick fix because if we
Implement action listener we need to implement a method so if I scroll down you can see we need this action
performed method so this is going to be used for our game Loop and what we we need to do is
repaint so repaint is going to call paint component again and in order for this code to execute we need a game Loop
which is a timer so let's scroll up over here I'm going to create a timer called game Loop and then within our
Constructor I'm going to do game Loop is equal to new timer 50 this so we have two parameters 50 and this 50 is the
delay and this refers to this Pac-Man object so when we use a timer we need an action listener so instead of creating a
separate action listener object I'm going to have Pac-Man take on the properties of action listener and we
just need to define the things we want to repeat in our action performed so every 50 milliseconds we are going to
call Action performed which will call repaint okay so basically every 50 milliseconds we're going to repaint
and there are 1,000 milliseconds in 1 second so 1,000 ID 50 gives us 20 so this is 20 frames per second and after
we create our timer we need to start it so gam loop. start so now if I save and run the
program we have a game and it's running in a loop it's drawing over and over again but we don't see the changes
because Pac-Man and the ghosts are not moving so let's add some key listeners so that when we press the arrow keys
pack and will move up down left or right so up here I'm going to implement key listener and just like with action
listener we have some unimplemented methods so if I hover over Pac-Man and click on Quick Fix add unimplemented
methods you can see on the bottom we have three methods key typed key pressed and key released so key typed is when
you type on a key that has a corresponding character so for instance if I press a we get the letter A or if I
press press zero we get the number zero but if I press the arrow keys nothing happens because the arrow keys don't
give us characters when we're writing so we're not going to use this next we have key pressed and key press is basically
when you press on any key so I can press on arrow keys I can press on any key with a letter as long as I'm pressing
the key I would trigger this function and actually I can hold on to the key as well now we don't want to hold on to the
key so I'm going to collapse that the only thing we need is key released so key released is similar to key press
except it only triggers this function if we press a key and we let go and we release the key so if I press a key and
I hold on to the key nothing will happen unless I let go so for now we're just going to add a
print statement so system.out.print line key
event plus E.G key code now we need to make our key presses work so in our Constructor I'm going to add two things
one is ADD key listener and I'm going to have it listen to this so when Pac-Man implements key listener it takes on the
property of a key listener so I don't need to create a separate key listener object I can just reference Pac-Man and
so if I add key listeners it's going to listen for key presses and use these three functions to process the key
presses next I want to make sure that the J panel is the one listening for the key presses now in a window you can have
multiple components and they can all be listening for key presses in this case we only have one component but we want
to ensure that this is the component that listens for the key presses so I'm going to do set Focus ofo to true and
finally back in our app. Java file over here I'm going to do Pacman game. request
Focus all right so make sure you have this line in app. Java and these two lines in Pac-Man so now if I save and
run the program I can press left up down right okay so the key codes for up down left and right are between 37 and 40 all
right so now that we are able to register our key presses now when we press on the Arrow key we want to move
the Pac-Man so very quickly I just want to go over how moving the Pac-Man Works currently we have Pacman over here and
if I want to move left or right this is going to be within the X AIS so if I move left that's X and if I move to the
right that is positive X so the left is zero and the right is the 18th column and likewise if I go up that is negative
because I am moving towards zero and if I go down that is positive because I'm moving towards the 20th row so in order
to move the Pac-Man we need to specify a velocity so we have velocity in X Direction and velocity in the y
direction so we need to specify these two velocities so here I'm going to add three more member variables so car
Direction and this doesn't really matter but by default I guess I can just set it to U for up and we're going to create a
velocity X I'll set this to zero for now and it's velocity Y which I'll also set to zero
if you have both velocity X and y z that means you're not moving along the columns or rows okay so you're not
moving at all and we're going to use these same member variables for our ghost because it is within the class
block and this is the same class we use for the walls which don't move so we don't really need that information but
we're just going to pack it all within the same class just to make things easier all right so when I press on an
arrow key I want to update the direction so here I'm going to create a function void update Direction and it's going to
take in a character Direction and we'll just assign this do Direction equal to
Direction and then afterwards I want to update the velocity according to the direction so I'll do update
velocity and this is a function that we need to Define so down here I will do void update
velocity so for the direction I would just use four different characters up down left and right so this will
be U D L or R all in uppercase so here I'm just going to make some checks if this. direction is equal to U so up this
is only in the Y AIS so this do velocity X is equal to zero and this. velocity Y is going to be negative because we're
going upwards towards Zer so negative and I'm going to make it tile size / 4 so tile size is 32 pixels so divid 4 is
8 pixels so every frame we're just going to go up 8 pixels and another way to look at it is every frame we're just
going to inch a quarter of the tile size else if this do direction is equal to D this. velocity X is zero still because
we're going down and and this. velocity y because we're going down we're going towards the 20th row so I'm going to set
this to positive so tile size ID 4 and let's do the same for left and right so else if this. direction is equal to
l this velocity X is going to be negative because we're moving towards the zero column so negative tile size /
4 and this do velocity Y is going to be zero and let's just copy and paste this for the last
one and I'm going to change this to R for right and we're just going to make this
positive all right so if I press on a key I want to call update Direction on Pac-Man which then updates the direction
and calls update velocity so down here in our key released function I'm going to make some checks so let's just
comment this out so if e do get key code is equal to key event.
vkor up I'm going to do pac-man. update Direction and we're going to pass in
upper case U and let's just copy this and do the same for down so else if E.G key code is equal to VK down we're going
to update direction to capital D let's copy and paste this again this time vkor left we will update to capital
L and then finally VK WR we will update this to capital r all right so if I press up down left to right we're going
to update the direction that Pac-Man will face and we're going to update the velocity X and Y accordingly so this
will update the velocity but we need to actually move Pac-Man so so I'm going to scroll up and under the draw function I
will create another function called move so we're going to do Pacman dox Plus equal pac-man. velocity X Pacman
doy plus equal pac-man. velocity y So based on our code one of these will be zero therefore I'm just going to add
both of them to X and Y that way I don't need to make any checks because one of them is going to be zero anyway this
just makes it easier to write cleaner code but anyway we have our move function that updates our X and Y
position of Pac-Man now we need to just call the function so the velocity is tile size divid 4 so every frame we
expect Pac-Man to move one quarter of the tile size so I want to do this before I draw so I'm going to do move
then repaint and that's basically how a game works so you update the positions of all the objects and then you redraw
then next frame you update again and you redraw again so this is going to happen in the game Loop so let's save and run
the program and you can see I have Pac-Man and if I press up Pac-Man moves up and I can press left
down right okay so we need to change one thing we need to make a check to see if
Pac-Man is colliding against a wall if so Pac-Man needs to stop moving so I need to define a collision function
so over here I'm going to do public Boolean collision and we're going to take in two
blocks so block a Block B and we are going to use this function to detect collision between the Pac-Man
and the ghost the Pacman and the wall and The Ghost and the wall Pac-Man with the food therefore we're going to reuse
the same function that takes in two different blocks now this Collision function will use a specific formula for
detecting the intersection between two rectangles so every object every image on our screen is a rectangle and that
includes Pac-Man although Pac-Man is round the image for Pac-Man is actually a square you just don't see parts of the
square because it's invisible it's transparent so here I'm just going to write a formula and because this video
is already quite long long I'm not going to explain how the formula works so just copy what I'm writing here trust me it
works so return a.x less than b.x + b.width and a.x + a. withth is greater than
b.x and a.y is less than b.y plus b do height and a doy plus a do height is greater than
b.y all right so this is going to be the Collision detection formula that we'll be using for our function now in our
move function I'm going to make a check so here we have Pacman X and Y positions being updated and I'm going to iterate
through all the walls in the hash set so for block wall walls if
collision between Pacman and and this current wall I'm going to undo this so Pacman
dox minus equal pac-man. velocity X Pacman doy minus equal pac-man. velocity y so basically how this logic works is
we're just going to take a step forward and I'm going to check through all the walls if one of them has a collision
with Pac-Man I take a step back so after this move function finishes it will basically be as if Pac-Man never moved
if there is a wall and just to terminate the for Loop earlier I'm just going to break so once we find our first
Collision we don't need to continue searching through the rest of the hash set because we already found the wall
that we Collide into all right now let's save and run the program okay and I'm going to move to the
left and we hit a wall if I move up we hit a wall left down right
down and you can see I suddenly stopped and that is because while packman was going down I press the right arrow key
and suddenly it changed direction to face right now the thing is Pacman should only change directions if it is
able to so this means that if it changes Direction it should not be in a direction where it hits a wall and in
our update Direction I'm going to store the previous Direction so car prev Direction
is equal to this. Direction and here we're just going to iterate through all the walls so every time I update
directions I need to make sure that Pac-Man is able to change directions without crashing into a wall so we're
just going to use the same strategy we're going to take a step forward so this.x plus equal this. velocity X this
doy plus equal this. velocity Y and then we're just going to iterate through all the walls so for block wall
walls if Collision so Pacman is going to refer to this so This object if this object collides with the wall and we're
going to use this same function for the ghost as well because the ghosts are blocks so if this object which is the
Pac-Man or the ghost if it collides with the wall then we're going to take a step back so this.x minus equal this.
velocity x this.y minus equal this. velocity y so we take the step back and we need to
update the direction so this. direction is equal to prev Direction and then we need to call update velocity
again so let's save and run the program all right so if I move to the left and up and I try to move to the
right you can see Pacman does not stop unless we have an opening like so okay all right so that's the movement
for Pac-Man now what we need to do is change the image for Pac-Man so that when it moves up it's facing upwards and
if it moves down it faces downwards and I'm going to do that in our key release function so whenever we press on an
narrow key it goes up down left or right we make a check to see that this direction will not result in Pac-Man
crashing into a wall so what we need to do is just simply check for the direction that Pacman faces so if
pac-man. direction is equal to uppercase U we're going to do pac-man. image is equal to pacan up
image and let's just copy and paste this else if the direction is D then this is Pacman down image so let's copy pin
paste again so we'll change this to L for left and Pac-Man left image and one more time R and Pac-Man write image all
right and the reason why we're doing it afterwards instead of putting it underneath each case here is because if
we update Direction it doesn't necessarily mean that pressing left will make Pacman move left because there
could be a wall there all right so that's the check we made earlier all right so now if I save run the
program if I move to the left you can see Pacman faces left I can go up and I can reverse course and go down and then
I can move to the right down left down all right so Pac-Man is able to move
around now we also want the ghost to move around so we're going to make the ghost move around
randomly so over here I'm going to create two new variables so car directions
and this is going to be an array of four characters so u d
l and R so this is up down left and right and we're going to create a random object so random random is equal to new
random basically for each ghost we're going to randomly select the direction so in our Constructor after we load the
map I'm just going to iterate through each ghost so for Block ghost ghost we're going to do car New
Direction is equal to directions index of random. next in 4 so directions has four characters and random. next int
returns a number between 0 and four but it doesn't include four so it's going to be 0 1 2 and 3 and I'm going to do
ghost. update Direction new Direction okay so basically we assign each ghost a direction and update direction will
update the velocity for each ghost now we need to move the ghost and we're going to do that in our move function so
we're going to do for Block ghost ghost and we're going to do ghost. X Plus equal ghost. velocity X ghost. Y
plus equal ghost. velocity Y and we need to do the same check for collisions against the wall so right now if I save
and run the program you can see the ghost just move in random directions and they can move
past the walls so we need to make the same check so we're going to iterate through all the walls for each ghost so
for block wall walls if Collision ghost and wall we're going to
take a step back so ghost. X minus equal ghost. velocity X ghost. Yus equal ghost. velocity Y and in this case we
want the ghost to change directions immediately if it collides into a wall so we're going to do car New Direction
is equal to directions at index random. next in of 4 and then ghost. update Direction new Direction okay so for each
ghost we're going to move a step forward and if it collides into a wall it's going to move a step back and then
change directions all right so if I save and run the program you can see this Pac-Man
moves around but the rest go off screen and that is because we have a gap here and this is where if Pac-Man or the
ghost goes towards the left they will teleport to the right side and if they go to the right side they will teleport
to the left side so I will let you implement this and I want you to take what you learn from this tutorial and
try to implement that yourself so for the time being I'm just going to make a quick fix basically if the ghost hits
this left boundary or the right boundary it will stop and change directions so here I'm just going to do or ghost. X is
less than or equal to Zer so the left side of the ghost touches the left border or ghost. X Plus ghost. y width
is greater than or equal to board width so ghost. X is the left side of the ghost if we want the right side we need
to add the width so just to quickly visualize this if we have a ghost the X position is over here remember X and Y
starts at the top left corner so the left side is ghost. X and if we want the right side we need to add the width
which is the tile size so over here this will be x + width all right so now let's save on the program all right so now you
see the ghost each hit the left and right border and they reverse course now this is an issue because now
these two ghosts are stuck on this row so what we can do is we can make another quick fix and that is if the
ghost is on this particular row we're going to try to make the ghost go upwards so this is row number N9 so this
is 9 * tile size so if the ghost is on this row it's going to try to forcefully change upwards so over here before we
even move the ghost we're going to check to see if the ghost is on the ninth row so if ghost doy is equal to tile size
time 9 and ghost. direction is not equal to up and ghost that direction is not equal to down
this means that the ghost is moving left and right so it's stuck on this row so in this case we're going to do ghost.
update Direction U so if the ghost is stuck on this row we're going to try to force it to go up so let's save and run
the program all right so now you can see if the ghost is in this row it's going to try to go upwards unless it's going
up and down already all right so we have our ghost moving in random
directions all right so now we have Pac-Man and the ghost moving around now we need to make them interact with each
other and the food so we need to implement three things here we need to keep track of the number of lives
Pac-Man has and the score every time Pacman eats the food and whether it's game over or not so I'm going to start
with score so we're going to do in score equal to zero and I'll also add lives so by default we're going to start with
three lives and then Bulan game over we're going to set this to false
Pacman has three lives so this means that if Pac-Man collides with a ghost it will lose one life and if it loses all
three of its lives then we set game over to true and if it's game over we stop the player from moving Pac-Man so let's
start with the score every time Pac-Man collides with a food pellet is going to eat the food and gain 10 points and
every time Pac-Man and eats a food we want to remove that food from the hash set because once you eat the food the
food is gone so here I'm going to do block food eaten is equal to null So currently
Pac-Man has not eaten anything but we're going to iterate through all the foods so for Block food
Foods if Collision Pac-Man and the food Pac-Man will eat the food
so food eaten is equal to food and score plus equal 10 and then we're going to remove the food eaten from the hash set
so foods. remove food eaten all right so once Pacman eats the food we want to update the score so in our draw function
I'm going to add the score so I'm going to do g. set font new font arial font. plane and let's make the font size 18 so
if game over currently it is not game over but if it is game over we'll do g. drawring game
over plus string. value of score and for the X and Y position of the string I'm just going to do tile size / by two and
tile size / two else so if it's not game over we want to display the score along with the
number of lives that Pac-Man still has so we're going to do g. draw string X Plus string. value of lives
plus space score colon plus and I'm just going to copy and paste
this let's add a semicolon here okay so now if I save and run the program you can see if I move to the left
Pac-Man is eating up all the food pellets and the score is going up by 10 each
time okay now we need to make it so that when Pacman collides with the ghost Pacman loses a
life and we reset the positions of all the ghosts and Pac-Man to the starting positions all right so in our block
class we're going to add another method so we're going to add a reset function so void reset and this is just going to
reset the X and Y position so this.x is equal to this. startx and this.y is equal to this. start y all right so
let's go back to our move function and within our move function in this for Loop where we check collisions for the
ghost we're going to add a check to see if the current ghost has collided with with Pac-Man so if Collision ghost and
Pac-Man we're going to remove one life and then we're going to reset positions so we need to Define this
reset positions so down here I'm going to do public void reset positions and I'm going to do pac-man.
reset so this sets the X and Y positions back to the starting positions and I don't want Pac-Man to move until the
player clicks on an arrow key so pac-man. velocity X is equal to Z and pac-man. velocity Y is also equal to
zero and then let's do the same for each of the ghosts so for Block ghost ghost we're going to do ghost. reset and
we're going to update the Velocity in the the case for the ghost we'll just give the ghost a new Direction so car
New Direction is equal to directions at index random. next int 4 and then ghost. update Direction new
Direction so let's save and run the program and you can see we have Pac-Man over here and if Pacman collides with
one of the ghosts come on then we reset okay and then here we have zero lives so
if Pacman has no more lives we want to stop the game so let's go back to our move function and over here when we
Collide With The Ghost and Pac-Man if lives is equal to zero then we set game over to true and
then we return and if game over we want to stop drawing and moving Pac-Man so Within action performed I'm going to do
if game over Game loop. Stop and once we stop the game Loop we will no longer call
this function therefore we're not going to constantly move and repaint so let's save and run the
program all right so we're moving Pacman around and let's Collide come on okay that's one down that's two
down and three so we sto drawing we stop moving the characters and now we have game over with a score of 180 now I want
to reset the game if I press on any key so that I can try again so let's reset the game so in key released I'm just
going to make it so that any key press will make the game reset if you want you can make it a specific key you can make
it any Arrow key or the space bar key up to you so I'm just going to do if game over and if we want to reset the game we
just need to set everything to the starting conditions so I'm just going to reload the map and the reason why I need
to reload the map is because I need to add all the food back into the hash set then I'm going to reset the
positions and reset positions will give each ghost a new direction to move in we need to set the lives back to three
score needs to be zero and we'll set game over back to false and then we simply restart the game Loop so gam
loop. start all right so now let's save and run the program and we have Pacman so
let's try to collide so that's one that's two and three game over now I'm going to
press on any key and it should reset the game so the ghost will be back here and Pac-Man will be over here and all the
food will reset and the score becomes zero so I'll press any key and we reset everything okay so we have three lives
again and zero score all right so now we're able to reset the game if Pac-Man runs out of lives but there's another
condition and that is if Pac-Man eats all the food we progress to the next level so Pac-Man is a pretty simple game
basically the next level is going to be the same map but with the food reset or if you want you can create your own map
so you can make another map for the next level but for this tutorial I'm just going to reload the map so in the move
function after we remove the food I'm going to make a check if Foods dot is empty so if the hash set is empty that
means Pac-Man has eaten all the food and if that is the case I would just reload the map and reset the
positions all right so let's save and run the program and I would try to eat all the
food so this might take a while so I'll probably just cut this part so you don't have to watch me try to play this game
all right no all right so I'm almost there and
honestly this game is it can be quite difficult even though the ghosts are moving at random
all right there you go okay so we move on to the next level and I still have one life
left and uh yeah so that's pretty much it for this game all right so we have game over so that's pretty much it for
this tutorial we have a fully functional game of Pac-man you can continue working on this game if you want there are some
features that I would like you to add and one of those features is moving to the left of this border so if Pac-Man
moves to the left of this border it should re pair on the right side and vice versa another feature you can add
is a pause feature so by pressing the letter P Pac-Man should pause the game so none of the ghost and Pac-Man should
be moving and the way you would implement this is just creating a new variable called paused and make it a
Boolean and if the player presses on P then you just flip the Boolean to true and stop the game Loop another feature
you can add is keeping track of the high score since we can reset the game every time the Pac-Man loses all its Lives
having a high score displayed over here would also be nice and yeah you can add other features of the game such as
adding some power pellets so that when Pacman consumes any of these pellets all the ghost become scared so I've added
that Sprite over here for you if you want to implement that feature and there's also a cherry so you can do
whatever you want with this Cherry you can add extra points when Pac-Man eats the Cherry so you can place it anywhere
you want in the game and if you want a really good challenge you should make it so that the ghosts don't necessarily
move too randomly so in the case of this tutorial the ghosts are just moving randomly and every time they hit a wall
they change directions now the problem with this algorithm is let's say we have this blue Ghost if it moves to the left
it goes down and then it turns right and technically the blue Ghost can go up but because going up does not constitute
hitting a wall the ghost would just continue moving on so technically if Pac-Man is in this area or this area the
ghost will never try to enter because it's not going to hit a wall so it's just going to move forward so this is
all up to you there's a lot of features you can Implement and you can find the list of suggestions on the GitHub
repository so I definitely encourage you to continue working on this game and uh yeah that's it for this tutorial if you
found this tutorial helpful make sure you leave a like and if you have any questions let me know Down Below in the
comments and if you want to stay up to date for more tutorials like this one make make sure you subscribe to the
channel and I'll see you in the next video bye-bye
Heads up!
This summary and transcript were automatically generated using AI with the Free YouTube Transcript Summary Tool by LunaNotes.
Generate a summary for freeRelated Summaries

Java Programming Course: Introduction, Structure, and Setup Guide
Learn about Java programming fundamentals, data structures, and how to set up your coding environment.

Java Programming: A Comprehensive Guide to Understanding Java and Its Concepts
Explore Java programming concepts including OOP, exception handling, and collections. Learn how to build robust applications!

Java Course Introduction: Mastering Coding Fundamentals and Data Structures
Kickstart your Java programming journey with our guided course covering basics to algorithms for aspiring developers.

Java Basics: Outputs, Variables, and User Input Explained
Learn Java's fundamentals: how to give output, use variables, data types, and take user input effectively.

Creating Game Designs with Stable Diffusion and Photoshop: A Comprehensive Guide to Jungle Piics
Learn how to design a match-three game using Stable Diffusion and Photoshop, from logo creation to game assets.
Most Viewed Summaries

A Comprehensive Guide to Using Stable Diffusion Forge UI
Explore the Stable Diffusion Forge UI, customizable settings, models, and more to enhance your image generation experience.

Mastering Inpainting with Stable Diffusion: Fix Mistakes and Enhance Your Images
Learn to fix mistakes and enhance images with Stable Diffusion's inpainting features effectively.

How to Use ChatGPT to Summarize YouTube Videos Efficiently
Learn how to summarize YouTube videos with ChatGPT in just a few simple steps.

Pag-unawa sa Denotasyon at Konotasyon sa Filipino 4
Alamin ang kahulugan ng denotasyon at konotasyon sa Filipino 4 kasama ang mga halimbawa at pagsasanay.

Ultimate Guide to Installing Forge UI and Flowing with Flux Models
Learn how to install Forge UI and explore various Flux models efficiently in this detailed guide.