Pacman maze in Java - java

So I'm building the pacman game in Java to teach myself game programming.
I have the basic game window with the pacman sprite and the ghost sprites drawn, the pacman moves with the arrow keys, doesn't move beyond the walls of the window, etc. Now I'm trying to build the maze, as in this picture:
Without giving me the direct/complete solution to this, can someone guide me as to how this can be built? I'm talking only about the boundaries and the pipes('T' marks) here which you can't go through and you have to go around. Not the dots which the pacman eats yet.
Here are my questions:
1) What's the most efficient algorithm/method for creating this maze? Will it have to be drawn each time the paint() method is called or is there a way to draw it only at the start of the game and never again?
2) How will this actually be drawn to the screen? I assume the fillRect() will be used?
3) Any hints on collision detection (so the pacman/ghosts can't go through the walls) would be helpful.
4) Any hints on how the vacant space between the pipes will be calculated so the dots can be filled between them will also be very helpful.
Thanks

I wouldn't do it that way.
I'd draw the graphical map and then create a 2D data array which represents the map. The data map would be responsible for determining collisions, eating dots, where candy is and where the ghosts are. Once all the logic for everything is handled just use the 2D array to display everything in their proper pixel coordinates over the graphical map.
For example the user is pressing the left key. First you determine that pacman is at element 3, 3. Element 3, 2 contains information denoting a wall so you can implement the code to make him ignore the command.
EDIT:
Each element would represent about where a dot could be. For example:
No, looking at the board I would say the array would look something like this.
d,d,d,d,d,d,d,d,d,d,d,d,w,w,d,d,d,d,d,d,d,d,d,d,d,d
d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d
p,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,p
d,w,w,w,w,d,w,w,w,w,w,d,w,w,d,w,w,w,w,w,d,w,w,w,w,d
d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d
And so on. You might want to pick a more flexible data structure than just characters however since some areas need to contain a bunch of different information. IE even though the ghost spawning area is blank, pacman isn't allowed in there. The movement of the ghosts and pacman is different for the side escapes, the candy spawn point is a blank spot but if you want to remain flexible you'll want to denote where this is on a per map basis.
Another thing you'll want to remember is that pacman and the ghosts are often inbetween points so containing information that represents a percentage of a space they're taking up between 1,2 and 1,3 is important for collision detection as well as determining when you want to remove dots, powerups and candy from the board.

You can paint the map into a BufferedImage and just drawImage that on every paint(). You'll get quite reasonable performance this way.
If you are happy with the walls being solid, you can draw each square wall block with fillRect. If you wish to get the same look as in the picture, you need to figure how to draw the lines in the right way and use arcs for corners.
The Pacman game map is made of squares and Pacman and the ghosts always move from one square to the neighbouring square in an animated step (i.e. you press right, the pacman moves one square to the right). That means that collision detection is easy: simply don't allow moves to squares that are not empty.
I do not understand what you are trying to ask here.

1) Just to give my advice on redrawing. Something that you can do if you find redrawing the entire image is slow, is determine only the elements that have changed on the screen and redraw those. An approach for this would be the following: Determine the sprites that have moved. Determine (approximate) a rectangle around those sprites. Redraw those rectangles only. This way you are only refreshing parts of the screen and not the whole screen. This should result in an increase in performance over redrawing the entire screen.
The other answers have been reasonable for the other questions you have asked.

Related

Java: Drawing grid to screen using 2D Array without lag/screen flickering

I am attempting to create a very simple top-down game in Java, but I am unsure how to approach a problem dealing with program performance.
I used a 2D array to store certain values that represent certain things, such as the surrounding environment and the player's position. I then used the paint() method to draw a grid to the screen based on a section of the 2D array. The player is always in the center of the grid. I have it coded such that the player never truly "moves", but rather the environment around him "moves" (if you press a key to move up, a new section of the array is drawn that is the same as the past section except it has a new row at the top and the bottom-most row is now the past section's second-to-bottom row, all the while the player stays in the center, if that makes sense).
Thus, we have a situation where the whole screen needs to be redrawn each time the player moves. As you might have gathered, this is bad for the program's performance, since it has to iterate through a 2D array and draw it the screen each time I call repaint(). If the user hits the key to move upwards twice in succession, the program will lag and the screen will flicker as it redraws the whole section of the array.
How can I improve the performance issue, given that I want to keep the player in the center of the screen at all times and have the environment move around him? Should I instead investigate Jscrollpanes? Is iterating through arrays in the paint() method not the way to go?
Thank you so much for both your time and also helping an inexperienced programmer.

Java Game Hitbox Detection & Rounded Corners

I am working on a simple 2D game with Java, swing and no framework. I have a rectangular player that the user can move around. On the map are few obstacles which the player should not be able to go through. I did this by making a new Rectangle Object for the player and each obstacle with their bounds. But I’m not really sure if this is the right way to do it. It works but the movements of the player are not really user friendly. If the player wants to pass two obstacles they must be on the perfect coordinates to pass.
Is it even a good idea to check for intersections between the player and the obstacle with a Rectangle object or should I do it another way?
Now for my 2nd question:
I’d like to replace the rectangular hitboxes with the same hitbox but with rounded corners so the player could pass more easily.
This is what the game looks like with hitboxes enabled.
The code that checks if the player and the obstacles have yet intersected:
for (Player p : this.getPlayerArray()) {
Rectangle recPlayer = p.playerBounds();
for (Obstacle kiste : obstacleArray) {
Rectangle recKiste = kiste.obstBounds();
if (recPlayer.intersects(recKiste)) {
p.setX(100); //Not actual code here
}
}
}
The function that returns the hitbox of the player / obstacle:
public Rectangle obstBounds() {
return new Rectangle(this.getX(),
this.getY(), image.getImage().getWidth(null),
image.getImage().getHeight(null));
}
Many years ago I wrote a Khepera simulator as part of my undergrads' final year project. I started by doing collision detection as you are doing, that is intersecting areas... My supervisor made me notice that since the shape of my robot was a circle I just could check if the center of the robot was inside another shape, if that was the case a collision occured.
Your case is even simpler since you move on tiles... so either you do (as suggested in the comments) maintain a set of "move/no move" tiles and check that, or you just check that the position of your player is within, or not, a 'forbidden' rectangle, i.e. an obstacle. If it is, then you have to reset the position of the character to be 'outside' of the obstacle (minus the character's bounding box, obviously)
I strongly suggest to do it the tiles way: allow only up/down/left/right movements and check against a 'forbidden' set of movements given a tile-position. If you really want 'freedom' of movements than go with circles (bounding boxes/circles) because they are easy to reason with, easy to do a position reset (in case of collisions) and perfect for your case (every tile can contain a circle, whether an obstacle or the player.)
There are many ways to go about collision checking, but I think a simple approach would do just fine for your use-case.
First from the looks of your screenshot, a tile is either an obstacle or passable, but never half of each. In that case it would be simplest to just check on which tile the center (or feet, choose what looks best) of the character are.
If its an obstacle, they cant go there, simple as that. Note that this will allow the player to move partially into an obstacle, but many games do it this way and players are certainly used to this behavior, especially in 2D games with graphics designed to look like an isometric projection (which I would yours class as). A variation of this would be to simply make the player collision rectangle smaller (say half a tile, again centered at the player sprites chest or feet).

Draw curved custom object in LIBGDX?

I've recently been looking into LibGDX and seem to have hit a wall, seen in the picture, the blue dot represents the users finger, the map generation it self is where i seem to get stuck, does LibGDX provide a method of dynamically drawing curved objects? I could simply generate them myself as images but then the image is hugely stretched to the point of the gap for the finger can fit 3! But also would need to be 1000's of PX tall to accommodate the whole level design.
Is it such that i should be drawing hundreds of polygons close together to make a curved line?
On a side not i'll need a way of determining when the object has from bottom to top so i can generate another 'chunk' of map.
You don't need hundreds of polygons to make a curve like you drew. You could get away with 40 quads on the left, and 40 on the right, and it would look pretty smooth. Raise that to 100 on each side and it will look almost perfectly smooth, and no modern device is going to have any trouble running that at 60fps.
You could use the Mesh class to generate a procedural mesh for each side. You can make the mesh stay in one spot, locked to the camera, and modify it's vertices and UVs to make it look like you are panning down an infinitely long corridor. This will take a fair amount of math up front but should be smooth sailing once you have that down.
Basically, your level design could be based on some kind of equation that takes Y offset as an input. Or it could be a long array of offsets, and you could use a spline equation or linear equation to interpolate between them. The output would be the UV and X coordinates which can be used to update each of the vertices of your two meshes.
You can use the vertex shader to efficiently update the UV coordinates, using a constant offset uniform parameter that you update each frame. That way you don't have to move UV data to the GPU every frame.
For the vertex positions, use your Mesh's underlying float[] and call setVertices() each frame to update it. Info here.
Actually, it might look better if you leave the UV's and the X positions alone, and just scroll the Y positions up. Keep a couple quads of padding off top and bottom of screen, and just move the top quad to the bottom after it scrolls off screen.
How about creating a set of curved forms that can be put together variably. Like the gap in the middle will at the top and bottom of each image be in the middle (with the same curvature at end and beginning points)...
And inbetween the start and end points you can go crazy on the shape.
And finally, you can randomly put those images together and get an endless world.
If you don't want to stop in the middle each time, you could also have like three entry and exit points (left, middle, right)... and after an image that ends left, you of course need to add an image that starts left, but might end somewhere else...

Collision detection between ball & maze made dynamically from text file

Ok so I am creating a ball tilting game, where you navigate a ball around a maze. The ball works, and is all good in the area however I am having some problems in the maze.
The maze is programmatically created through a .txt file that contains 1's and 0's (1's being walls, and 0's being floor.) I have a for loop that goes through the whole .txt file and places a white(wall) or black(floor) square at the proper coordinates on a canvas. This is similar to the apps-for-android Amazed game if you have seen it link. However, instead of placing wall-type detection on his tiles, he just resets the game and deducts a life point if the user rolls onto a 'void' tile.
However I am looking to have 'walls' and not 'voids'. Where if the ball touches the wall, it doesn't go beyond that point, but can still move freely on the other axis. Unless it hits a corner, of course.
The problem I am having is actually creating this detection. I have tried a number of ways but nothing so far has been successful or useful.
I have tried:
- Have an ArrayList of all of the coordinates of the wall tiles, and every game tick, it checks to see if the ball is touching one. However this just slowed the game down to a crawl and was just extremely terrible.
- Check to see what tile the ball is on, and if it's on a wall tile, to stop it on an axis but let it move freely on the other, however this still didn't work as there were some issues when the ball was to the right of the wall tile, but also under it, it couldnt move up, as the code detected it being under the ball.
And a few other ways but I really cannot remember! It's been a bit hectic.
So, I am asking, if anyone has any experience in this area could they please give me a push in the right direction? Im hoping to have the maze walls sorted by Tuesday however it's looking grim!
If you need any more information, please ask.
Thank you in advance for any and all replies.
Instead of having an ArrayList that you have to iterate over, why not store the maze the same way you do the text file? Use a 2D boolean array filled with true for wall and false for floor, or vice versa.
This simplifies finding a wall considerably. All you have to do is figure out where in your grid the ball is. Then you can just check the cells immediately surrounding it. Even if you include diagonals(which probably isn't necessary for an all-90-degree maze), this equates to checking 8 booleans from an array, basically instant.
As for the axis issue, just stop movement in that direction. No need to freeze a whole axis. For instance, if the wall is right of you, just don't allow x to go higher. No reason to not let it lower unless there's a wall to the left.
This is just a general idea, though. Since it's homework, no code for you ;)
Edit:
The 2D array is just that, a boolean[][] which holds true in each of the spots where you want a wall to be. When you read in your text file, just assign it straight away.
Assuming each line in your text corresponds to an y row, and each 0/1 is the x for that column, when you read a 1, assign map[x][y] = true.
I'm honestly not sure what else you need elaboration on. It's a common format to do simple tile-based maps, though. If you google "2d array tile map", you'll find several resources to help with it.

Making car (JPanel) turn in a smooth curve in Swing

At the moment I have a simple animation where a car (JPanel) approaches a junction where after it waits for traffic lights to turn green and continues straight on. However I'm going to the next step now where I want the car to turn 90 deg right in a smooth curve to turn onto the perpendicular road. I have sketched roughly how it looks and the curve represent the way I want the car to turn:
I'm not too sure how to do this. I suppose I would need to represent some sort of bezier curve? Or matrix transformation to rotate the car?
Can someone give advice on the best way to do this in Swing.
If you are new to graphics in Java, I recommend this tutorial. If I were to code what you are doing, I see two options.
First and easiest, you can model turning as "first driving straight, then turning 90º along the edge of a circle centred on the corner I am turning around, and then driving straight again". The easiest way to do this is to define a JPanel that draws your Image (yes, a JPanel; if you don't paint their background, you can layer JPanels on top of each other - and they will be painted in the correct order; make the background JPanel opaque so that it cleans up before drawing the next frame), and give it an AffineTransform that makes the image display in the position you want it to. You will need to adjust the increments in the transform so that the speed appears constant; trial and error, or a bit of geometry (90º of radius R implies R*pi/2.0 total travel along the curved path) , will help you out there.
The hard way is to consider the car's route to be an arbitrary Shape (which you can define using Bezier curves, for example), extract a flattened PathIterator from it, advance in equally-spaced jumps along that iterator, and calculate the rotation you need from the position along the curve and the heading at any given point (you can estimate the heading by taking 2 successive samples, and aligning the car according to these samples). This is harder than using the above method, but allows your car to follow arbitrarily complex paths.

Categories

Resources