Tetris with Custom Images - java

I am working out a concept for a Tetris style game with a twist. I have worked through a few tutorials for the basic logic but with the way we are wanting to do this, I am not sure if the logic is even possible in our time frame.
Basically, we are using custom images for the Tetris pieces. We have three different colors for each and a different image for each possible rotation. On top of that, our game will be trying to pair letters together so we have images with each possible rotation with each possible letter placement. For example, for the "T" shape, we have right now 92 images of each possible rotation for just ONE of the three color's we want to use with the four letters we are using. After thinking about it for the past few days, there is going to be hundreds (maybe even over a thousand) images.
However, that's not the issue. The only way I can think of checking is using a TON (like well over a thousand) IF statements. For example, if piece 1 which is a "T" shape with an "A" on the right side, we need to check if "B" is next to any of the other possible positions the piece can ever be in. If a piece with an "A" on it is next to (either above, below, or on either side) a piece with a "B" on it, a good match with be registered. If at any point two letters that are the same land next to each other, the whole row of pieces that the are a bad match will disappear causing any pieces above it to fall down. Once these pieces land again, every single piece needs to be checked again to see if its new position is a part of any possible letter pair. The checking will always need to be happening for every single piece that is spawned onto the game board so the more pieces there are, the more checking that needs to always be happening.
So, is this something that will simply take way to long (we have just over a month) or is there something else that can be done besides a TON of IF statements? Is something like this even possible? After all we are talking most likely 1000 images and every single image needs to always be getting checked if it:
Has hit another image and needs to stop
Check if where the player placed it is next to another letter and if it is a good
letter match or not (this is the big issue)
Once a whole piece disappears, the pieces need to shift down again and get all the checking needs to happen once again.
The plan is to do this in java since its the only language I have a good understanding of but I am open to any and all suggestions. If its a lost cause, please let me know. Would like to come up with another concept before I invest a lot of time into this if it is a lost cause.
EDIT:
Here is a very quickly tossed together image that gives you an idea of what it looks like:
http://imageshack.us/a/img560/1814/dg80.png
Looking at this image, you see 4 pieces already in place at the bottom of the board and the player is guiding the straight piece down. The player wants to match the "A" at the bottom of the line with the "A" that is in the right "square" of the "T" shape. Once the piece has landed next to the "T", the code needs to say "Oh hey, another "A" just landed next to me so I am a good match and we both need to disappear". Once that has happened, the other pieces will shift down and the checking needs to happen again. Since there are SO many combinations of pieces and with players having free reign to put pieces in crazy spots, the checking needs to be insane. Every single piece needs to check with all the other pieces to ensure a valid combo is never missed.
Here is an example of what a piece looks like:
http://imageshack.us/a/img23/6632/1g3q.png

What you will probably want to do is think of your Gamefield as a 2 dimensional array with a set of cells. Each row is N cells wide and there are M rows. Now whenever a piece gets dropped anywhere you register the letters in the piece in the gamefield array.
Lets assume your pieces look like this:
public class GamePience {
public Character letter;
public Color color;
}
This gives you
GamePience[][] gamefield = new GamePience [M][N]; // null is empty, otherwise gilled
When a piece is dropped you copy it's letters to the array (for simplicity I'm assuming pieces are also 2 dimensional arrays because that works well)
gamefield[0][2] = piece[0][0];
Now after a letter is placed and copied to the field you can simply check the over the field
boolean destroyedLine = false;
do {
for (int x = 0; x < gamefield.length; x++) {
for (int y = 0; y < gamefield[x].length; y++) {
GamePiece cur = gamefield[x][y];
if (cur != null && x < MAX_FIELD_WIDTH && gamefield[x+1][y] != null) {
// there are gamepieces in both!
GamePiece neighbour = gamefield[x+1][y];
if (cur.letter == neighbour.letter) {
destroyLine(x); // this method should null out the line and shift everything down, you'll probably want to loop trough the whole line first and check if there are pieces in every cell
destroyedLine = true;
break;
}
}
}
}
} while(destroyedLine);
You can also easily check against the gamefield while dropping down pieces to check if the cells are already filled.
Now, all you need to do is fill out that logic and write some code to draw the gamefield and you are set ;) (you might want to think about using an LinkedList for the gamefield because that makes deleting rows trivial)

Related

Peg Solitaire buttons in Java

I'm very new to coding, and struggling with a part of my final project. The project is very open ended: make a graphical java application. I've chosen a peg solitaire game, which as you'll see from the image below:
http://i.imgur.com/dS65iZ2.jpg
Incorporates a similar concept of 'jumping' pieces that a game like checkers uses. This is what I made so far, a board made up of a 7x7 grid of jbuttons, each uses a square pic to represent a part of the board; though I've left buttons intentionally blank in place of the spaces that would be on a normal board.
The problem I've run into is the next step, the game logic itself; I'm trying to figure out how to implement a system where I can click on a peg, and then click on an empty space to 'move' the peg (Which in this instance, would just be switching the jbutton image to the 'slotted' square). However, the game has to recognize whether or not the space clicked on is filled, whether or not the second space clicked is empty, and whether or not the space BETWEEN these two spaces is filled - because in this game, pegs can only move over another peg, and only into a space that is empty.
The pegs cannot move diagonally, only on the four compass directions. I put together this with my instructor's help:
I tried to add to it and figure out how to implement what I described above but I just can't really grasp it. I know what I need to do, but struggling on how to execute it. This code allows me to click on the identified square and 'empty' it, and also allows me to click on the empty space to remove the peg from the square between this and the first square.
But I don't know what the code for identifying when a space is filled or not, or the code for even differing between the empty space and filled space. I assume it's some kind of if statement and the name of the space and tied to which picture is being currently used (if it's the empty hole pic or the filled slotted pic). And then an else statement and...
Well, like I said, I'm very new to all this, and google searching on the subject isn't helping me because I only half understand it, and don't know how to translate the information given to the project I have.
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == boxEleven)
boxEleven.setIcon(holePic);
if(event.getSource() == boxTwentyFive)
{
boxTwentyFive.setIcon(peggedHolePic);
boxEighteen.setIcon(holePic);
}
else if(event.getSource() == boxEleven)
boxEleven.setIcon(
}
}

Strategy for calculating possible paths between objects (with possibility for infinity) in swing?

I'm trying to build a logic function for my map building application that will tell me if there is an available path from one swing object to another.
Specifically I want to identify all the possible paths from one Jabel to another Jlabel.
Empty space is denoted by a white image, a wall is denoted as a blue image, player start is orange, and player finish is green.
So what I think I want to do is check each available path from the starting point. If the path ends at the goal return true, if it ends at a wall then make that the new starting path. My current Idea is to create a 2d array that populates with ints 0. When a the user changes a tile to something other than white, a corresponding spot in the array will change to 1 2 or 3 depending on what tile they placed. Then when they try to save the map the algorithm would use that 2d array to represent the map and check adjacent and linear paths.
Am I on the right track with this or is it more complicated?
I feel like this could turn out to be very slow(like n^2 or worse) if it's a complicated map because the paths can branch out. I'm thinking about using a sort of Dijkestras method for solving this, but I also don't know how exactly I would do that in swing.
There are some movement restrictions in the game as well.
You can't change directions unless you are stopped.
You can't stop unless you hit a wall or the edge of the map.
This eliminates a few options to sift through, as the number of paths become alot more limited.
Yes I think you are on the right path.. You can use something like this for collision:
In which you made a object, class Coordinate
constructor(){
block = new Coordinate[length];
path = new Coordinate[length];
for (int i=0;i<number_of_blocks;i++){
if (block[i].x==path[length_of_path].x && block[i].y==path[length_of_path].y){
//now you have a collision so go back
}
or
for (int i=0;i<number_of_blocks;i++){
if (block[i].x==path[length_of_path].x+1 && block[i].y==path[length_of_path].y){
//now you know you have a block on the right side
}
In which you have to make a object for, class Coordinate for example, to help store the coordinates.
class Coordinate {
int x,y;
Coordinate() {
x=0;
y=0;
}
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
This way you can easily check if there is a collision or not and if you're out of bounds. Then you change direction adding a new coordinate to you string with the new coordinates and so on. I think this is easier then using 2d Arrays.
If you're array is out of options you go back till there is another direction possible and go that way. (You only have to save seperatly what your previous coordinates were and overwrite them while you go back).
GL

Check if Node(instance of Class) is Clicked

Hey I am working on a small project in the aim to accelerate my learning and have come into a problem , I have an arraylist of class instances each with and x,y location and each have been mapped to fit inside a window , and am wondering how I may go about implementing functionality which would allow user to click on a node( an ellipse on screen at the mapped x,y value from a instance of class) and for my program to somehow have a toggle to display information about this node in another part of the screen , I have looked for code examples and havent found one that I can get working with my senario here is my class
class Ship{
float yPos;
float xPos;
Ship(String line){
String[] parts = line.split(",");
xPos = float(parts[4]);
yPos = float(parts[5]);
}
}
I am taking in data from a csv file and splitting it etc,
I have alot of code so if my example isnt enough I will add specific parts if needed,
Thanks in advance ,
Kind Regards,
Andrew
You have to add logic for detecting whether the mouse is inside the object.
Exactly how you do this depends on how your object is shaped.
If your object is a circle, you can simply use the dist() function to check whether the mouse is inside the circle.
If your object is a rectangle, then you just have to check whether the cursor position is inside that rectangle. Draw out a few examples on a piece of paper to help figure this out.
If your object is in a grid, then you can map the cursor position to a grid position.
If your object is more complicated, like a polygon, then your logic will have to be more complicated. Google is your friend with this one.
In any case, you're going to have to try something, put together an MCVE (note: this should not be your whole sketch, it should be a small example that we can copy and paste to run ourselves) and ask a more specific question. Good luck.

Most efficient method to randomly generate a location on some certain area?

I am working on a "greedy snake" game. I am using a 2d array to store the value of each location/grid of the map: either egg or snake body or empty. The egg needs to be generated on the empty spot. One solution could be:
while (new egg location overlaps snake body)
Within the range of 2d array randomly generate an egg location
However when the snake grows very big and fills up most area of the map, the generating new egg become very inefficient, since it has to check almost every element of the 2d array. How can this be optimized?
Maintain a list of all empty squares. Every time you need a new random empty square use:
Collections.shuffle(list).get(0);
First, I would like to say that there is nothing wrong with your solution. The only issue you get is that late game (when most of the squares are taken up by the snake) you may have to try a large number of times to find an empty space.
In this situation OldCurmudgeon's solution is a good fit. However, it suffers from a different issue. Maintaining a list of empty squares from a large empty grid is a waste of time.
So early in the game, your current solution is preferable. But late game their solution is better.
So I would suggest doing a check on the size of the snake. If the snake takes up less than half of the grid use your current solution. Only when the snake takes up more than half of the grid start maintaining a list of empty squares.
Give all the spaces the snake currently occupies as an input and then check from the remainder. Won't quite get to O(1) but will reduce how much of your array it needs to go through.
public Point generateRandomPoint(){
Random rand = new Random();
Point p;
boolean goodPoint = false;
//while the point selected is not empty
while (goodPoint!=true){
p= new Point(rand.nextInt(MAX_X),rand.nextInt(MAX_Y));
//is the point empty
goodPoint = array[p.x][p.y].equals("empty");
}
return p;
}
If you use this, then it only checks the space that the egg would be spawned on. Now, because it is random, it may have to check a lot of spaces, but unless your board is a couple thousand across, it should be almost instant (<<50 ms).

Implementing AI to hide behind obstacles

I am developing an AI simulation of predator and prey. I would like to simulate the AI hiding behind obstacles, if it is being chased. But I am still trying to figure out the best way to implement this.
I was thinking along the lines of checking on which side of the obstacle the predator is on and trying to go on the opposite side. Maybe using the A* path finding algorithm to ensure that it gets there using the shortest path.
Now the main reason I am writing is in case somebody is able to point me in the right direction of implementing this (maybe somebody has done this before) or have any other good ideas how to implement it. I have never done anything like this before in terms of programming AI or making any game.
All the obstacles are either horizontal or vertical squares/rectangles.
Please note that the circle in red is the predator while the circle in green is the prey being chased.
I can't give any code off the top of my head, but I can tell you a few things:
First, you need to define the goal of this program. For this case, it is to get the AI to hide behind an obstacle, keeping the user and the AI on opposite sides whenever possible.
Next, you need to decide what needs to be done inside the code (without writing any real code) to accomplish this goal. For instance:
We need to determine what "zone" of the scene is considered "behind the obstacle"
Next, we need to determine a path for the AI to get to that zone without going through the obstacle.
Lastly, we need to add some sort of delay to this so the AI doesn't constantly change its mind for every pixel the user moves across the screen
This isn't per se an easy problem, but it is certainly achievable without breaking too much of a sweat. I'd recommend you find a way, even if it is slow and requires a ton of code, then write the code for it, and lastly refine. If you worry about refinement, then you never get any of the problem solved.
HINT: Determine a vector that points from the player to the middle of the obstacle. Then, multiply the vector by 2 and add it to the position of the player and that gives you a point on the other side of the obstacle (assuming it is a rectangle). Apply a Math.min() or Math.max() restrictor to the x and y values you get to keep the AI as close or far from the obstacle as you wish. That should be a decent start! :)
Update -- I decided to add some code!
// This assumes a few variables:
int obstacleCenterX, obstacleCenterY;
int aiX, aiY, aiWalkSpeed;
int predatorX, predatorY;
private void updateAIMovement() {
int slope_x = obstacleCenterX - predatorX;
int slope_y = obstacleCenterY - predatorY;
int destination_x = predatorX + (slope_x * 2);
int destination_y = predatorY + (slope_y * 2);
if(aiX != destination_x){
aiX += (slope_x / Math.abs(slope_x)) * aiWalkSpeed;
}
if(aiY != destination_y){
aiY += (slope_y / Math.abs(slope_y)) * aiWalkSpeed;
}
}
I have not tested anything at all, but I think this might be somewhat of a right path to take. I could have done A LOT to improve just that little code snippet, but I didn't (such as some trig to make sure the player moves at a true speed when going diagonally, etc...)
Hopefully this helps a little!
I would check if there is something crossing the direct line between x and each observer. If it is, x is hidden.

Categories

Resources