To preface, sorry for the semi-vague question. I have been searching for weeks to this question.
So I understand the necessities a game needs. (init, update, draw).
To be more specific, I'm using Java with Slick2D as a learning environment. Slick2D makes the set-up of the game pretty simple. I think I understand MVC structure, but my biggest problem right now is where do I write the player movement code?
I have the Player class which has all the fields of where it's at, what image/animation it needs to render, and right now, all of the controls. It doesn't feel right, though that could just be my own insecurities. I feel that the player movement controls should be in its own class, the collision detection in its own class, and the all the player would have is simply what defines it(coordinates, size, hit box, etc.).
I'm not entirely sure how to explain this, as every time I think about it, my mind races all over the place and I have a hard time "chunking" this information in my head.
If you need more information, please let me know. I'm just trying to find the "right" place for everything to make my code more manageable, readable, and possibly reusable.
(edited to show program flow[not runnable]) As it is, my flow is,
public class Game extends StateBasedGame{
//with main included, this sets up the window, fps, etc...
start "level 1" state...;
}
public class level1 extends BasicGameState{
public void init(){
initialize player, environment, etc...
}
public void update(){
player.update();
}
public void render(){
environment.render();
player.render();
}
}
public class Player{
All player variables
public Player(){
construct player with coords and starting image/animation
}
public void init(){
initializes all images/animations this player could potentially use
}
public void update(){
All environment based input controls go here, example;
if(this.isGrounded && input.keyIsDown(KEY_SPACE){
make character jump;
change animation;
}
}
public void render(){
draw image/animation;
}
}
Collision detection should be taken care of in the update method. If you mean movement from input, you should create a separate class for input. Store the position coordinates for a character in the character object. The Input class should then change these coordinates. If you are talking about an AI you should have a separate AI class that controls the movement.
Every game is different. The important part is that you understand the code and that it works. I recommend finding helpful online tutorials that show example code so you can begin to understand the workflow of creating a game.
Related
I dont think its pretty to use this as a class parameter because there could occur errors if the order of initialization of the objects is not right.
Whats best practise to avoid this?
Example:
public class Game{
private Player p1, p2, currentPlayer;
private Board board;
Game() {
board = new Board(this);
}
private boolean hasFieldsToBeClicked() {
return board.checkFieldsToBeClicked();
}
From a design point of view: just don't do it here!
Meaning: a Board represents a board. Does your chess board know about the game you are currently having, or not?
In other words: passing this can be ok, but as you pointed out, it can also be a problem. Thus the best practice is: only pass this if you have good reasons to. Especially when it occurs within the constructor and this is still in the process of being initialized.
Enabling a chess board to know about an ongoing game isn't really a good reason.
Keep in mind: your classes/objects should model the real world. Only establish relations that are meaningful!
So the real answer here would be to look into why your Board class needs to know about the Game class, to then get rid of that dependency.
1) What about a builder, which creates the game and the board at first without the other. Then the builder can set the Board in the Game and the Game in the Board.
2) It seems the Board is an inherent part of the Game.
a) So you could use interfaces for Game and Board and implement both in one class.
b) If you want to separate the Game from the Board you could use an inner class for the Board within the Game.
Im learning libgdx and one of the things that really confuses me its raycasting. I read a tutorial of how to use it and I understand it but I really want to know what's in the back. I searched for the source code of this method.
public void rayCast (final RayCastCallback callback, float point1X, float point1Y, float point2X, float point2Y) { // FIXME pool RayCastCallback?
world.raycast(new org.jbox2d.callbacks.RayCastCallback() {
#Override
public float reportFixture (org.jbox2d.dynamics.Fixture f, Vec2 p, Vec2 n, float fraction) {
return callback.reportRayFixture(fixtures.get(f), point.set(p.x, p.y), normal.set(n.x, n.y), fraction);
}
}, this.point1.set(point1X, point1Y), this.point2.set(point2X, point2Y));
}
How we can see this method calls itself recursively and returns a call to reportRayFixture of the callback variable. The thing that really confused me it's from where the code select the Fixture, and how its checks every fixture. Can someone explain me really how its works.
This its the source code page https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/World.java
I will appreciate it!
Raycasting is when we draw an invisible line through space and see what it intersects with. A common use for this is to figure out what a player is clicking on- we draw a line from the camera in the direction that the player is clicking, and the first object our line touches is the line the player clicked on.
In Box2D, the RayCastCallback interface is used to allow you to write code that gets executed when your ray hits a Fixture (for example, you may want to ignore certain fixtures). I haven't used this personally, but I imagine you could use something like this in a shooter game to see if a wall-penetrating weapon could hit an object behind a wall (or something like that).
At a high level, what this lovely piece of code is doing is a little slight of hand- if you look at it really closely, what it's doing is taking in the libGDX RayCastCallback and wrapping it in a JBox2D RayCastCallback which has a slightly different API. It's more like it's overloading the method than calling it recursively.
What I don't know is why the author chose to create the Point1 and Point2 instance variables. I would think if you had multiple fixtures they would get overridden, so perhaps they are supposed to contain the last fixture hit by the ray? Even so, it looks like multiple raycasts would overwrite them.
This question already has answers here:
How do i get a graphics object in Java?
(2 answers)
Closed 9 years ago.
Im making a basic space invaders game. I got all the resources from the LWJGL .zip file (Im not using LWJGL librarys to create my game, just got the pictures, etc. from it.) Anyway, whenever i press "space" on my keyboard, my KeyListener creates a new bullet that my ship fires. However, i dont know how to draw the bullets image, since my KeyListener doesnt pass a graphics object, and you need one to draw a image. The code thats causing the problem is the "drawImage" method in the "Shot" constructor. Heres my code:
public class KeyTyped{
public void keyESC(){
Screen.isRunning = false;
}
public void keyLEFT() {
Screen.shipPosX -= 10;
}
public void keyRIGHT() {
Screen.shipPosX += 10;
}
//This is automatically called from my KeyListener whenever i
//press the spacebar
public void keySPACE(){
if(!spacePressed){
ShotHandler.scheduleNewShot();
}else{
return;
}
}
}
public class ShotHandler {
public static int shotX = Screen.shipPosX;
public static int shotY = Screen.shipPosY + 25;
public static void scheduleNewShot() {
//All this does is set a boolean to 'false', not allowing you to fire any more shots until a second has passed.
new ShotScheduler(1);
new Shot(25);
}
}
public class Shot extends ShotHandler{
public Shot(int par1){
//This is my own method to draw a image. The first parameter is the graphics object that i need to draw.
GUI.drawImage(*????????*, "res/spaceinvaders/shot.gif", ShotHandler.shotX, ShotHandler.shotY);
}
//Dont worry about this, i was just testing something
for(int i = 0; i <= par1; i++){
ShotHandler.shotY++;
}
}
}
Thanks guys! Any help will be appreciated!
(This is a re-post because the last time i posted this, i didnt get a sufficient answer, at least for my skill level)
Start by taking a look at
Painting in AWT and Swing
Performing Custom Painting
You may also find Concurrency in Swing of some usefulness.
The basic gist is you should have some kind of model which describes the state of the game play at any moment in time. This model is updated outside the content of the Event Dispatching Thread, normally in some kind of background thread, where the time it takes to perform the updates doesn't effect the ability for Swing to continue running and remain responsive to the user.
You will need to override the JPanel's paintComponent method. In here, you would paint the model state to the screen.
There are a bunch of other techniques which could be discussed, but lets get this started
Examples...
Java Bouncing Ball
Drawing 2 Balls to move in different direction on Java but one disappeared
Multiple bouncing balls thread issue
I am trying to make ball gradually move
Java ball object doesn't bounce off of drawn rectangles like it's supposed to.
https://stackoverflow.com/questions/15858623/how-to-use-a-swing-timer-to-animate/15859932#15859932
the images are not loading
Swing animation running extremely slow
How to make line animation smoother?
I'm working on an android game and have been considering my main game loop. Should the NPC class in my android java game have it's own move function, or should the move function be moved into the game class? Is there any advantage between option one and option two, CPU load, size of compiled apk, maintainability etc.
I wanted to know if either of these two different code examples I just wrote up if one was the "correct" way.
SUDO CODE: Option One - The NPC class has it's own move function
class Game {
Npc npcs[] = new Npc[10];
public Game(){
while(running){
for(loop=0;loop<npcs.count(); loop++){
npcs[loop].move();
}
draw();
}}}
SUDO CODE: Option Two - The move function is part of the Game class
class Game {
Npc npcs[] = new Npc[10];
protected moveNPC(){
for(loop=0;loop<npcs.count();loop++){
npcs[loop].x = // change x value
npcs[loop].y = // change y value
}
}
public Game(){
while(running){
moveNPC();
draw();
}}}
There will hardly be any difference in terms of efficiency or hardware use, so you should go with the Option One. NPC is a class that represents a group of objects that all have their behavior encapsulated in move() method - this is a basic OOP thing. Means your Option Two approach will work, but it's wrong from the Object Oriented point of view. Hope this helps.
I am a beginner in Java and for some practise, I am creating a text based noughts and crosses. What I have so far is a Player class, a Board class and a Game class. In the Game class, I have one instance of Board and two instances of Player. I have managed to write code for a player to make a move and to determine whether the game is a win or draw. I now want to ensure that a player can only have one move at a time and not more than one consecutive move i.e Player A, Player B, Player A, Player B...... rather than Player A, Player A, Player A...
The way I thought of doing this was to create a boolean field in the Player class of myTurn and have a method along these lines :
public boolean isMyTurn (){
if (myTurn == true){
return false;
}
return true;
}
I then invoke this method in the game glass before I make a move, but for some reason it doesn't work. Maybe I've made a mistake somewhere but if anyone has any other ways/ideas I could write some code to determine if a payers turn is valid or not, please let me know. Would appreciate if you could provide some examples too as I'm still a beginner.
I would make the Game class responsible for that. E.g.:
class Game {
...
public void makeTurn(){
if(isFirst)
firstPlayer.makeTurn();
else
secondPlayer.makeTurn();
isFirst = !isFirst;
}
private bool isFirst = true;
private Player firstPlayer, secondPlayer;
}
It even makes sense logically. The player can make many moves one after the other. It's the game (the rules of the game) that prevents him from doing that.
maybe I didn't understand well your problem, but:
Who sets myTurn?
Who "calls" player.play()?
Seems like this should be done by the same guy (a Game/GameManager class?).
So why don't players just play given a description of the game, and you let the task of managing turns to another class?
Cheers