Java- How to link AWT Rectangles? - java

I just started to write the game of snakes in java. (See this if you don't know what that is: http://codeincomplete.com/projects/snakes/ or http://elgoog.im/snake/). So, when the snake eats an object, its tail grows. In order for the turning physics of the game to work properly, each segment of the tail needs to have its own java.awt.Rectangle hitbox. My question is how can I link these hitboxes/segments of his tail so they always stay together, but are seperate components on my JPanel. Otherwise, if there is a better way to do this then let me know. Thanks.

There s should be a snake object, with a ordered set of simple snake piece, each piece showing type. Practice model view controller, each Snake piece should know nothing about graphics. When you at a segment, put by the last noon trail piece. So, your Snake would contain a list of pieces, like this:
List<SnakePieces> mPieces
SnakePieces should be simple, something like this
public class SnakePieces {
public enum Type {Head,Body,Tail};
public Type type;
}
Feel free to add other functions to SnakePieces as required. When you add a new piece, add it at the location
mSnakePieces.add(mSnakePieces.length()-1,newSnakePiece);
If you can, separate out the model (Snake movement), the view (Puts in the graphics for the piece depending on the type of SnakePiece), and the Controller (Feeds the inputs to the model). That's more advanced than required, but helpful. See Wikipedia on Model View Controller.
Also, see the Android Snake Game, which no doubt has some similarities to your application. Android does it via this:
/**
* mSnakeTrail: a list of Coordinates that make up the snake's body
* mAppleList: the secret location of the juicy apples the snake craves.
*/
private ArrayList<Coordinate> mSnakeTrail = new ArrayList<Coordinate>();
It just knows to draw the first and last tiles slightly differently.

Related

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.

OpenGL Objects Position and Physics

I have two simple questions:
First question:
Given is an object in OpenGL in an android application.
I want to apply phyics on the object like Gravtiy.
For this I've implemented a Public PositionVector {x,y,z,1.0f};
In the Object Object. So for example: Sphere.PositionVector = {0f,0f,0f,1f}
for the center of screen.
When I do the movement now, I have a modelMatrix and to update the Position should I multiply the modelMatrix with the PositionVector? But then I will still get 0,0,0,1.
mulitplyMV(tempVector,0,modelMatrix,0,PositionVector,0);
Where is the mistake? Or: What is the usual way to do this?
My goal is to have always the current positionvector of the Sphere.
Second question:
Does the shader have to do anything with the physics? Or may I calculate the gravtiy and the resulting vectors in the javaCode and apply then a translateMatrix to the modelMatrix?
Greetings,
Phil
So the first thing that really jumped out at me, was the question about movement. Normally if the movement was only for a visual effect, multiplying your position with a model matrix would be fine, but obviously you'll be wanting to handle collisions and that sort of thing as well.
What I normally do, is I keep track of each objects position, and update that value whenever it moves. When I draw my object, I first do a pass to leave out all objects that aren't in view and then only draw what my camera is seeing. So in this case, you'll only be drawing what is actually visible on the phone's screen at the moment.
So if you have a view matrix for your camera, to keep it simple for now you can leave out view culling, but you'll multiply your objects current position with the model matrix(in this case it is just an identity so it doesn't have any impact), and additionally with the view matrix and projection matrix. So its something like vec3 viewSpacePosition = projectionMatrix * viewMatrix * modelMatrix * position; (assuming I'm remembering that one correctly.)
Your physics calculations can be done either in your shaders or in your java code, though I recommend doing it on the java side while still getting the hang of things. OpenCL and transform feedback buffers can be quite tricky when you're still learning how some of the stuff works.
For the physics portion of your code, I would highly recommend taking a look an Glen Fiedler's series on game physics, you can find it here.
If you have any more questions, or if there is something you're still uncertain of let me know. :) Good luck!

object-oriented draughts implementation using collections of allowed moves and setwise operations

At my university I was given a task of implementing draughts game in a literate, object-oriented way following mvc design pattern. I was told that:
each of two game pieces should form a separate class that has separate fields for attack and non-capturing move in a form of collection;
checking the validity of a given move should be performed in a setwise manner.
I have no idea hot to do this, that is:
how to implement moves in the above defined way, i.e. in a form of collection
what sort of setwise operations should I use.
What sort of sets should I have, the procedural approach feels much more natural to me.
I'd be thankful for any suggestions on that or links discussing such implementations.
Some problems I find here. First of all, I guess model is given a mere pair of field indexes from a client view. So there is no initial information as to the nature of the move, i.e. whether it is a capturing on non-capturing move. In case of a king piece is not immediately given. Secondly, I guess the piece class should contain some sort of a vector, but how to account for men's limitation of moving only forward or either king's unlimited length of a move or requirement in some draught's rules that king should step one field after the captured piece?
Additional requirements were that implementation should be oriented towards legal directions of a game (diagonals) not around an array and that it should be elastic enough to fit different regional variations of the game.
Here is some insight on what you might want to try. Start with the view, if you can not create the "Checkers" board there is little use in going on.
Step 1: create the "view" the visual of the board with what ever gui programming language you wish.
Step 2: create the basic model, what the pieces are, ie, pawn or queen are the only two allowable pieces, set up icons for each single chip of course for pawn 2 stack for queen.
Step 3: setup the controller: one accept mouse clicks on the view board that captures whether it is selecting a position on the board that has a piece, and then realizes it is a piece and then outlines the possible moves of the piece. The controller should also tell the view board to update where the icon of the piece is on the board including when the game starts all the locations of the starting pieces which is stored in some collection in the model.
I would create an instance of the class for the pieces for each piece on the board easily done using a loop to create the pieces. Once you have those steps done you should be able to easily modify it to know when it is a capture move, an upgrade move(when a pawn reaches the other end of the board) illegal and legal moves.

How to create custom shape in java

I am doing some java games, and I figure it would be cool if the game is made without importing images. Therefore I need to create custom shapes and hand it to Graphics object to draw. The major character in my game will be a dango which is much like a slime, composing from a imperfect circle and two vertical lines as eyes. I should be able to construct dango by given a parameter indicating size. Also, it will be better if I can modify the position of the eyes, or the bottom curve to present the interaction with the floor. Further more, I would be glad if I can fill it with color and give it some texture or something. But all things start from a circle and two lines.
I checked some APIs including Shape, GeneralPath, PathIterator, Area, Ellipse, and some source code. I learnt how to use GeneralPath to draw straight line, quadratic curve, and bezier curve. But still I don't know how to implement my custom shape. I found this question in stackoverflow but no good answer is posted.
In case someone just read the title and skips the content of this question, I shall emphasize that this question is about create the custom shape, which means to implement the 'Shape' interface. Not just to draw a shape.
So after a day of research, I finally did it. For anyone who holds the same problem with me, I recommend you to do what I have done.
First, refer to the java api source code, here I chose the source code of Ellipse2D.class. Following the source code, you may ignore the 2 inner static class Ellipse2D.Double, Ellipse2D.Float, they are not so important at this point.
To implement the Shape interface, the most important method is
public PathIterator getPathIterator(AffineTransform at) {
return new EllipseIterator(this, at);
}
this method is called by paintComponent to get a PathIterator to draw. So as what the source code does, you may create your own ShapeIterator.
Then the source code of EllipseIterator. As you can see, there are 4 methods (excluding the constructor and the duplicate). You may leave getWindingRule() for furthur research. While isDone() and next() are rather simple to understand.
Then let's focus on public int currentSegment(float[] args).
The return values is int, which should be the static final int fields: SEG_CLOSE, SEG_CUBICTO, etc.. They give instructions on drawing your shape. SEG_MOVE will move the start point, SEG_LINETO will draw a straight line from start point to end point. There are few more like the quatratic curve and Bezier curve, you may check the details at java api.
The argument float[] args should also be regarded as return value statement. It delivers the parameters for the instructions above. For SEG_MOVETO, SEG_LINETO, you need 2 params, so modify args[0] and args[1] ( x and y). For SEG_QUADTO, you need 4 params, and SEG_CUBICTO needs 6.
Carefully follows the source code, it won't be hard to create a shape. I haven't complete all the methods in Shape interface yet, but the shape can already be drawn by a g2d instance.

How to model game object rendering and behavior in modular way?

I'm making a Java shoot em up game for Android phones. I've got 20 odd enemies in the game that each have a few unique behaviors but certain behaviors are reused by most of them. I need to model bullets, explosions, asteroids etc. and other things that all act a bit like enemies too. My current design favors composition over inheritance and represents game objects a bit like this:
// Generic game object
class Entity
{
// Current position
Vector2d position;
// Regular frame updates behaviour
Behaviour updateBehaviour;
// Collision behaviour
Behaviour collideBehaviour;
// What the entity looks like
Image image;
// How to display the entity
Renderer renderer;
// If the entity is dead and should be deleted
int dead;
}
abstract class Renderer { abstract void draw(Canvas c); }
abstract class Behaviour { abstract void update(Entity e); }
To just draw whatever is stored as the entity image, you can attach a simple renderer e.g.
class SimpleRenderer extends Renderer
{
void draw(Canvas c)
{
// just draw the image
}
}
To make the entity fly about randomly each frame, just attach a behavior like this:
class RandomlyMoveBehaviour extends Behaviour
{
void update(Entity e)
{
// Add random direction vector to e.position
}
}
Or add more complex behaviour like waiting until the player is close before homing in:
class SleepAndHomeBehaviour extends Behaviour
{
Entity target;
boolean homing;
void init(Entity t) { target = t; }
void update(Entity e)
{
if (/* distance between t and e < 50 pixels */)
{
homing = true;
// move towards t...
}
else
{
homing = false;
}
}
}
I'm really happy with this design so far. It's nice and flexible in that you can e.g. modularize the latter class so you could supply the "sleep" behavior and the "awake" behavior so you could say something like new WaitUntilCloseBehaviour(player, 50/pixels/, new MoveRandomlyBehaviour(), new HomingBehaviour()). This makes it really easy to make new enemies.
The only part that's bothering me is how the behaviors and the renderers communicate. At the moment, Entity contains an Image object that a Behaviour could modify if it chose to do so. For example, one behavior could change the object between a sleep and awake image and the renderer would just draw the image. I'm not sure how this is going to scale though e.g.:
What about a turret-like enemy that faces a certain direction? I guess I could add a rotation field to Entity that Behavior and Renderer can both modify/read.
What about a tank where the body of the tank and the gun of the tank have separate directions? Now the renderer needs access to two rotations from somewhere and the two images to use. You don't really want to bloat the Entity class with this if there is only one tank.
What about an enemy that glows as his gun recharges? You'd really want to store the recharge time in the Behaviour object, but then the Renderer class cannot see it.
I'm having trouble thinking of ways to model the above so the renderers and the behaviors can be kept somewhat separate. The best approach I can think of is to have the behavior objects contain the extra state and the renderer object then the behavior objects call the renderers draw method and pass on the extra state (e.g. rotation) if they want to.
You could then e.g. have a tank-like Behaviour object that wants a tank-like Renderer where the latter asks for the two images and two rotations to draw with. If you wanted your tank to just be a plain image, you would just write a subclass Renderer that ignored the rotations.
Can anyone think of any alternatives? I really want simplicity. As it's a game, efficiency may be a concern as well if e.g. drawing a single 5x5 enemy image, when I have 50 enemies flying around at 60fps, involves many layers of function calls.
The composition design is a valid one, as it allow to mix-and-match the behaviour(s) and render.
In the game we're toying with, we've added a "databag" that contains basic informations (in your case the position and the dead/alive status), and variables datas that are set/unset by the behaviour and collision subsytem. The renderer can then use these data (or not if not needed). This work well, and allows for neat effect, such as setting a "target" for a given graphical effect.
A few problems :
if the Renderer ask for data that the behaviour did not set. In our case, the event is logged, and default values (defined in renderer) is used.
It's a little bit harder to check for the needed informations beforehand (ie what data should be in the databag for the Renderer A ? what data are set by the Behaviour B ?). We try to keep the doc up-to-date, but we're thinking of recording the set/get by the classes, and generate a doc page...
Currently we're using a HashMap for the databag, but this is on a PC, not an IPhone. I don't know if perfomance will be enough, in which case another struct could be better.
Also in our case, we've decided for a set of specialized renderer. For example, if the entity possess a non void shield data, the ShieldRenderer display the representation... In your case, the tank could possess two renderer linked to two (initialization-defined) datas :
Renderer renderer1 = new RotatedImage("Tank.png", "TankRotation");
Renderer enderer2 = new RotatedImage("Turret.png", "TurretRotation");
with "TankRotation" and "TurretRotation" set by the behaviour. and the renderer simply rotating the image before displaying it at the position.
image.rotate (entity.databag.getData(variable));
Hope this help
Regards
Guillaume
The design you're going with looks good to me. This chapter on components may help you.

Categories

Resources