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
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.
Say there is a simple game where I have a class called Player, which holds all the information that a player would have, e.g. name, xPosition, yPosition, width, height, etc.
The Player class has also has methods associated with it that describe what a Player can do, e.g. move(), draw(), etc.
In the game, I need to be able to know when a Player collides with any other object in the game like a wall, ceiling or other world object.
I can go about this in 2 ways:
Create a class like CollisionDetecter that has a method like detectCollision(). Include an instance of this class in the Player class and call the detectCollision() method when appropriate
Rationale:
Detecting collisions isn't really an intrinsic property of a Player like it's xPosition, yPosition or name is, so it doesn't belong in this class.
Less clutter in the Player class. (Does this count?)
Create a method like detectCollision() in the Player class which checks to see if the Player has hit anything
Rationale:
Detecting collisions is something that a Player does so the detectCollision() method should be directly in the Player class.
Only Players need to be able to detect collisions, so why should I create another whole class with just 1 method for this? Why not just include it as a method in the Player class?
I feel like I'm always struggling with debates like this.
Which method is the most appropriate and why? Are both of these bad and should I be doing something else?
In General :-
Sometimes, its better to start with it on the player class and see what the consequences are. Refactoring is ultimately your friend, if you see that the method you are writing is needing things not really related to Player, then you start working out a new design.
In Specific :-
Perhaps Player is a GameObject, and Collision Detection is a Generic concept that determines collisions between game objects.
Perhaps a player is not really a class, perhaps Player is just a GameObject with a Movement Strategy, ie Player really is composed of more fundamental aspects of a game.
First of all, I am not sure whether it is allowed to ask this kind of question. So I am trying to create a board game and I was stuck at the implementation of generating valid moves for Piece. Here is the extract of the class diagram.
You can think this board game like chess, so we need to know the location of other pieces while generating valid moves. The problem is I have no idea how to check it. Is my class diagram wrong? Or should I check at the board every time I check a square? And how do I do that in Java? Thanks for helping.
The piece should not decide what its valid moves are, it should only be aware of where it is and how it's capable of moving. It is not responsible for that sort of logic.
The board should manage whether or not that's allowed or not (that is, it takes a piece which returns its possible moves to it, and in turn returns the valid moves).
The Piece class exposes a getPossibleMoves method that returns the list of positions it can reach:
public List<Square> getPossibleMoves(){ // might want to differentiate types of moves
Then, the board class has a getValidMoves method that takes a piece and returns its valid moves.
public List<Square> getValidMoves(Piece piece) {
return piece.getPossibleMoves().
stream(). // and filter by
filter(move -> isOnValidBoardCoordinate(move)). // can shorten
filter(move -> doesNotIntersectOtherPiece(move)).
filter(move -> otherValidation(move)).
collect(Collectors.toList());
}
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.
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.