I am trying to make a snake game in java but the thing i am trying to make is not a normal snake game. I want to make a snake game which is snake (player) can go to every direction (like in slither.io game).
And i am trying to make a snake from circles.
I am trying to use Graphics2D for it and I successfully draw a circle.
But I couldnt make it lot of circles which is attached to eachothers. (I tryed to use arrayList).
Also like in classical snake game i want to make snake grow when it eats food.
But instead of making it longer i need to add more circles.
Code i wrote for the circle (script name is also "Circle");
public void drawToScreen(Graphics2D g)
{
g.setColor(GameConstants.BORDER_COLOR);
BasicStroke stroke = new BasicStroke(5);
g.setStroke(stroke);
Ellipse2D border = new Ellipse2D.Double(getX()-getSize()/2, getY()-getSize()/2, getSize(), getSize());
g.draw(border);
g.setColor(getColor());
Ellipse2D shape = new Ellipse2D.Double(getX()-getSize()/2, getY()-getSize()/2, getSize(), getSize());
g.fill(shape);
setBounds(shape.getBounds());
// Here is for the username
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 14));
int width = g.getFontMetrics().stringWidth(getName());
g.drawString(getName(), (int)(getX()-width/2), (int)(getY()+5));
}
I have another script ("GamePanel") which I set up game, in that script I call some function whit this codes.
private Circle player;
player = new Circle(GameConstants.START_SIZE, spawnPoint.getX(), spawnPoint.getY(), randomColor(), GameConstants.START_VELOCITY, name);
player.drawToScreen(g2);
g2.translate(viewX, viewY);
I have zero clue what a "Script" is in Java.
But here is the source code to a game with very similar aspects that you can draw lessons from.
I made the Enemy ai a tad to intelligent, but you you will see how to do what you are asking in this code.
The Great Escape
Related
I am working on a project and i have already made a menu and a JPanel but now i want to draw over the JPanel and add some HUD to my game.
I am providing a picture with the final panel of my game and i want to add at the left a blue rectangle with the player heads and at the right another rectangle with actions, money etc but i want to construct them outside my Window class where i construct the frame and all of the JPanels. Generally now that the player has chosen to play a local game i want to be able to draw and erase on this panel as the game continues.
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(1);
return;
}
Graphics g = null;
window.render();
if (gameState == STATE.MultiPlay) {
handler.render(g);
hud.render(g);
}
if (gameState == STATE.LocalPlay) {
handler.render(g);
hud.render(g);
}
}
The code i provided is the render method i am using at my game engine class. With my game engine i have made this method circles 10 times per second and i wanted from here to instantiate the Graphics class and then go on with the other class and rendering everything i want to draw over that JPanel.
How can i draw over that JPanel using Graphics or something like that?
You must use Graphics object like that:
Graphics g= bs.getDrawGraphics();
I think it will be usefull, have a nice day.
PD: If you don't want to do that, you can also override the method paint(Graphcis g) and use the parameter.
I needed to draw a Car using Java and Graphics2D. I used multiple basicstrokes to come up with the shape of the car. How do I fill it with color? An example would be drawing 3 lines in the shape of a triangle and then wanting to fill it with color.
You can not simply fill a shape that was only created by drawing three lines. You have to define the shape, including all the lines that it consists of.
How exactly this is implemented depends on serveal factors. For example, whether you want to use the same stroke for all three lines, or whether they need different strokes.
It could be helpful if you had already provided some information of how exactly you are drawing the lines at the moment. I'll try to make a guess here...
So assuming that your current code roughly looks like this:
void paintCar(Graphics2D g)
{
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.BLUE);
// Draw the triangle
g.drawLine(100,100,200,100);
g.drawLine(100,200,150, 50);
g.drawLine(150, 50,100,100);
}
the easiest way to additionally fill this triangle would be to change it as follows:
void paintCar(Graphics2D g)
{
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.BLUE);
Path2D path = new Path2D();
// Build the triangle
path.append(new Line2D.Double(100,100,200,100), false);
path.append(new Line2D.Double(100,200,150, 50), true);
path.append(new Line2D.Double(150, 50,100,100), true);
// Draw the triangle
g.draw(path);
// Fill the triangle, with a different color
g.setColor(Color.CYAN);
g.fill(path);
}
But note...
... that there are more elegant and concise ways of achieving this. Usually, one would not append individual Line2D segments, but simply use the Path2D to build the shape:
void paintCar(Graphics2D g)
{
g.setStroke(new BasicStroke(1.0f));
g.setColor(Color.BLUE);
// Build the triangle
Path2D path = new Path2D();
path.moveTo(100,100);
path.lineTo(200,100);
path.lineTo(150, 50);
path.closePath();
// Draw the triangle
g.draw(path);
// Fill the triangle, with a different color
g.setColor(Color.CYAN);
g.fill(path);
}
So if you have the coordinates of your shape in an appropriate form (maybe stored as a list of Point2D objects), you may more easily build a shape that you can draw and fill then.
I am writing a simple game, or so it seemed. I created a class that draws a Arc2D (half a circle shape), that same class will repaint the arch as the mouse move.
Then I created a new class that draws ovals. This class has some simple mathematics to move the ovals on the screen. The movement of the ovals are not very important. So now that this is done I want to detect if the Oval collides with the arc(half a circle, Only the arc line) at any point.
What I have attempted is making the oval a Rectangle and use the intersect method. This code is in the draw method for the arc.
Arc2D temp= new Arc2D.Double(200, 200, 100, 100, angle, 180, Arc2D.OPEN);
MasterOval m = new MasterOval();
Rectangle r1 = m.bounds();//This gets the bounds of the oval
if(r1.intersects(temp.getBounds()))
System.out.println("hit");//display if intersects
For some reason I cant figure out why it will not display the word hit when it collides with the arc. Is there a way to see if they intercect? This is all code I can provide due to privacy policies. Please help.
Well, I'm not sure if your MasterOval class implements the Shape interface or not, but if it does (if it doesn't, consider using Ellipse2D.Double or something of that sort), the easiest way (standard perhaps ?) of checking for collision between Shape instances is using Area:
Shape1 shape1 = new Arc2D.Double(...);
Shape2 shape2 = new Ellipse2D.Double(...);
Area area1 = new Area(shape1);
Area area2 = new Area(shape2);
if (area1.intersect(area2)) {
...
}
Ok I have this code
#Override
public void render() {
// do not update game world when paused
if (!paused) {
// Update game world by the time that has passed
// since last render frame
worldController.update(Gdx.graphics.getDeltaTime());
}
// Sets the clear screen color to: Cornflower Blue
Gdx.gl.glClearColor(0x64/255.0f, 0x95/255.0f, 0xed/255.0f,
0xff/255.0f);
// Clears the screen
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Render game world to screen
worldRenderer.render();
}
And it draws a light blue background onto the screen. I am attempting to create a gradient that goes from a dark blue at the top, to a light blue towards the bottom. Is there a simple way to do this? I'm new to Libgdx, and OpenGL so i'm trying to learn from a book but I can't seem to find the answer to this one. I've heard of drawing a big square and having the vertices different colors, but I'm unsure of how to do this.
In libGDX, the ShapeRenderer object contains a drawRect() method that takes arguments for its position and size as well as four colors. Those colors are converted to a 4-corners gradient. If you want a vertical gradient, just make the top corners one color and the bottom corners another color. Something like this:
shapeRenderer.filledRect(x, y, width, height, lightBlue, lightBlue, darkBlue, darkBlue);
From the API for ShapeRenderer:
The 4 color parameters specify the color for the bottom left, bottom right, top right and top left corner of the rectangle, allowing you to create gradients.
It seems ShapeRenderer.filledRect method has been removed in late libGDX versions. Now the way to do this is as follows:
shapeRenderer.set(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rect(
x,
y,
width,
height,
Color.DARK_GRAY,
Color.DARK_GRAY,
Color.LIGHT_GRAY,
Color.LIGHT_GRAY
);
The parameters for rect method work in the same way as those in filledRect used to do, like in Kevin Workman answer.
There are some further details worth bearing in mind before comitting to ShapeRenderer. I for one will be sticking with stretching and tinting Texture.
private Color topCol = new Color(0xd0000000);
private Color btmCol = new Color(0xd0000000);
#Override
public void render(float delta) {
...
batch.end(); //Must end your "regular" batch first.
myRect.setColor(Color.YELLOW); // Must be called, I don't see yellow, but nice to know.
myRect.begin(ShapeRenderer.ShapeType.Filled); //Everyone else was saying call `set`.
//Exception informed me I needed `begin`. Adding `set` after was a NOP.
myRect.rect(
10, 400,
//WORLD_H - 300, // WORLD_H assumed 1920. But ShapeRenderer uses actual pixels.
420,
300,
btmCol, btmCol, topCol, topCol
);
myRect.end();
I was hoping to change transparency dynamically as player health declines. The btmCol and topCol had no effect on transparency, hence I'll stick to Textures. Translating pixel space is no biggie, but this is much more than the proferred single or double line above.
Ok dear folks, i've got this question and i don't really know a certain way to solve it.
I'm doing like a "Paint application" in java, i know everything is ready, but I need to paint the shapes with Computer Graphics Algorithms.
So, the thing is, once the shape is painted in the container how could I convert it like sort of an "Object" to be able to select the shape and move it around (I have to move it with another algorithm) I just want to know how could I know that some random point clicked in the screen belongs to an object, knowing that, I would be able to fill it(with algorithm).
I was thinking that having a Point class, and a shape class, if i click on the screen, get the coordinates and look within all the shapes and their points, but this may not be very efficient.
Any ideas guys ?
Thanks for the help.
Here is some of my code:
public class Windows extends JFrame{
private JPanel panel;
private JLabel etiqueta,etiqueta2;
public Windows() {
initcomp();
}
public void initcomp()
{
panel = new JPanel();
panel.setBounds(50, 50, 300, 300);
etiqueta = new JLabel("Circulo Trigonometrico");
etiqueta.setBounds(20, 40, 200, 30);
etiqueta2 = new JLabel("Circulo Bresenham");
etiqueta2.setBounds(150, 110, 200, 30);
panel.setLayout(null);
panel.add(etiqueta);
panel.add(etiqueta2);
panel.setBackground(Color.gray);
this.add(panel);
this.setLayout(null);
this.setVisible(true);
this.setSize(400,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(2));
dibujarCirculo_bresenham(g2d, 50, 260, 260);
dibujarCirculo_trigonometrico(g2d, 50, 130, 200);
}
/*This functions paints a Circle*/
public void dibujarCirculo_trigonometrico(Graphics g,int R,int xc,int yc)
{
int x,y;
for (int i = 0; i < 180; i++) {
double angulo = Math.toRadians(i);
x = (int) (Math.cos(angulo)*R);
y = (int) (Math.sin(angulo)*R);
g.drawLine(x+xc, y+yc, x+xc, y+yc);
g.drawLine((-x+xc), (-y+yc), (-x+xc), (-y+yc));
}
}
I assume that any image is a valid (isn't constrained to a particular set of shapes). To get an contiguous area with similar properties, try using a flood fill.
To colour in or move a particular shape around, you can use flood fill to determine the set of pixels and manipulate the set accordingly. You can set a tolerance for similar hue, etc so that it's not as rigid as in Paint, and becomes more like the magic selection tool in Photoshop.
There are a couple of approaches to take here depending on what precisely you want.
1) is to have objects, one for each drawn thing on screen, with classes like Circle and Rectangle and Polygon so on. They would define methods like paint (how to draw them on screen), isCLickInsideOf (is a click at this point on screen contained by this shape, given size/position/etc?) and so on. Then, to redraw the screen draw each object, and to test if an object is being clicked on ask each object what it thinks.
2) is, if objects have the property of being uniform in colour, you can grab all pixels that make up a shape when the user clicks on one of the pixels by using a floodfill algorithm. Then you can load these into some kind of data structure, move them around as the user moves the mouse around, etc. Also, if every object is guaranteed to have a unique colour, you can test which object is being clicked on by just looking at colour. (Libraries like OpenGL use a trick like this sometimes to determine what object you have clicked on - drawing each object as a flat colour on a hidden frame and testing what pixel colour under the mouse pointer is)