in the class GameScreen I wrote this code for a score:
if (Gdx.input.justTouched()&& executed==true) {
MyGdxGame.camera.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
for (int i=0;i<4;i++) {
if (sprite[zahl[i]].getBoundingRectangle().contains(touchPoint.x, touchPoint.y) && zahl[4] == zahl[i]) {
int scoreValue = Integer.parseInt(score);
scoreValue++;
score = String.valueOf(scoreValue);
executed= false;
}
if (sprite[zahl[i]].getBoundingRectangle().contains(touchPoint.x, touchPoint.y) && zahl[4] != zahl[i]){
this.dispose();
game.setScreen(new GameOverScreen(game));
return;
}
}
}
The second if refers to the class GameOverScreen. So if a user loses the game, the GameOverScreen would be shown. Now I want to show the reached score on the GameOverScreen. Therefore I have to use the changing variable score from the GameScreen class in the GameOverScreen class.
My question is: How can I use variables through different classes?
You could create a constructor that takes the score as the parameter in your GameOverScreen.
e.g:
game.setScreen(new GameOverScreen(game, TheScore));
You can save the variable on Android sharedpreferences. See the example here
Related
I am making Flappy Bird in JavaFX and I have created a method to tell the score. I have tried using a timeline but if I make it call the method too often, it gets very glitchy and if I make it slower, the score increments wrongly. I need a way to have the score method constantly being called without making the game slow and glitchy.
Here is the method for the score:
public class Score {
static int score = 0;
static boolean incrementScore = false;
public static int ScoreCount() {
for (int i = 0; i < 100; i++) {
if (FlappyBird.bottomPipes[i].getTranslateX() == Bird.birdView.getTranslateX())
incrementScore = true;
if (incrementScore)
score++;
incrementScore = false;
System.out.println(score);
}
return score;
}
}
If anyone knows a good way to do this, please let me know.
If you would like to run the program, it can be downloaded here
You should consider calculating your score in every frame. Timeline is not suitable for this purpose. Rather use an AnimationTimer like this:
new AnimationTimer(){
#Override
public void handle(long now) {
Score.ScoreCount();
}
}.start();
handle will be called in every frame the timer is active.
I am writing a noughts and crosses code that can take console arguments to decide which strategy to use (different AI classes). If the user selects 'ultimatecomputerplayer' then this is implemented as p1/p2 depending in which order they input this and the other strategy (could be 'humanplayer' etc.)
My problem is that the ultimate class needs to know which symbol it is, at the moment the game running class just assigns p1 to X and p2 to O but my ultimate class is written assuming it is X so this poses an issue.
This is the code that assigns the strategies and symbols:
NCGridV3 theGrid = new NCGridV3(gridSize, gridSize);
GameRunnerV3 theGame = new GameRunnerV3();
Scanner sc = new Scanner(System.in);
ArrayList <NCPlayer> ret = new ArrayList <NCPlayer>();
for (int i = 1; i < args.length; i++)
{
switch (args[i])
{
case "RandomComputerPlayer":
ret.add(new RandomComputerPlayer());
break;
case "SimpleComputerPlayer":
ret.add(new SimpleComputerPlayer());
break;
case "UltimateComputerPlayer":
ret.add(new UltimateComputerPlayer());
break;
case "HumanPlayer":
ret.add(new HumanPlayer(sc, theGame));
break;
}
}
NCPlayer p1 = ret.get(0);
NCPlayer p2 = ret.get(1);
p1.setMySymbol(SquareStatus.CROSS);
p2.setMySymbol(SquareStatus.NOUGHT);
I tried to assign the strategy's symbol like so:
public class UltimateComputerPlayer extends GenericPlayer implements NCPlayer
{
public UltimateComputerPlayer()
{
super();
}
#Override
public GridCoordinate getNextMove(NCGridV3 currentGrid)
{
SquareStatus symbol = GenericPlayer.getMySymbol();
But eclipse tells me I cant make a static reference to a non-static method.
Another option I tried was passing an integer into the UltimateComputer Class which would be 'i' from the loop in the game runner class, then having the symbol assign dependent on which place the class was called like so:
public UltimateComputerPlayer()
{
super();
SquareStatus mysymbol;
if (NC == 1)
mysymbol = NCGridV3.SquareStatus.CROSS;
if (NC == 2)
mysymbol = NCGridV3.SquareStatus.NOUGHT;
}
#Override
public GridCoordinate getNextMove(NCGridV3 currentGrid)
{
.......
But this variable is not assigned in the GridCoordinate class and I dont know how to make it.
Any help is greatly appreciated, Thanks.
The second option can't work because NC is not defined (at least I can't tell where it would be) and also you assign the symbol to a local variable SquareStatus mysymbol in your constructor, which is gone as soon as you leave the constructor. You firstly have to make mysymbol an instance variable (by moving it above the constructor). Then you have the choice to either use the setter after construction or add the number to the constructor
class UltimateComputerPlayer {
private SquareStatus mysymbol;
public UltimateComputerPlayer(int nc) {
super();
if (nc == 1)
mysymbol = NCGridV3.SquareStatus.CROSS;
if (nc == 2)
mysymbol = NCGridV3.SquareStatus.NOUGHT;
}
// [...]
}
However that seems to be a generic concept and should be moved up into the parent class. Also, I would avoid using magic numbers inside the class. Make the decision of what symbol to use outside the class and call the constructor with the symbol as parameter, rather than the number.
And as #VictorSorokin says, in your first solution, just call getMySymbol() instead of GenericPlayer.getMySymbol()
So im making a program and a different class refers to an int in a different class:
if (Doihavetools==0 && Stone.StoneCounter>=10 && Wood.WoodCounter>=50){
but in the other class, the int is initialized before the value is "++"ed
int WoodCounter;
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("Chop some wood")) {//ADD A .25 SECOND DELAY INBETWEEN CLICKS
Random Rand = new Random();
int W = Rand.nextInt(3) + 1;
if(W==2){
WoodCounter++;
}
Wood.setText("Click To Collect Wood : Wood:" + WoodCounter);
System.out.println(WoodCounter);
}
}
Is there a way so i can successfully initialize it and add to it at the same time? (i want to be able to continuously add to it)
Thanks in Advance,
Jack
I think what you want is for the variable to hold it's value. Try making another variable, a boolean, and before you initialize it, make a check to see if you have already done so. Also, declare this boolean in the class where
if (Doihavetools==0 && Stone.StoneCounter>=10 && Wood.WoodCounter>=50){
is present, at the top. (make it public)
so... then you can
if(initialized == false)
{
int WoodCounter;
initialized = true;
}
Either that, or just use Wood.WoodCounter instead of declaring a new variable.
You shouldn't declare a woodCounter variable unless you want to use it for something. Write wood.woodCounter to access the variable you seem to intend.
Basicly I am creating a game that you click on falling objects, E.G cookies, and I need to know how to check and see if a certain cookie has been pressed so it can disappear but the problem is that its in an array.
Here is a bit of my code:
Input class...
public class Input implements MouseListener, MouseMotionListener{
#Override
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(MainGame.CG)){
if(MainGame.MG.inGame){
//There is actually something else here but its classified (haha sorry about that)
if(e.getPoint().x > /*I NEED SOMETHING HERE*/){
//tells you if the object has been pressed
MainGame.CG.cookieClicked = true; //CG = ClickerGame
}
}
}
}
}
class with array...
public class ClickerGame extends JPanel{
public int amount;
public FallingObject[] fo = new FallingObject[120]; //THE ARRAY I'M HAVING TROUBLES WITH
/*THE REST IS A SECRET (SORRY ABOUT THAT)*/
}
If you don't understand here is a picture to demonstrate what I need...
In order to avoid having to check the coordinates of 120 different items on each click, make every element inside FallingObject[] aware of three things:
Its own area of influence (see sn00fy's answer)
The containing class (in this case probably ClickerGame
Its location in the array (an int)
To do this, you would need to change your FallingObject constructor to look something like this:
public void FallingObject(ClickerGame master, int index); //add whatever else is needed for Falling Object.
Then you could instantiate the array as follows.
for(int i = 0; i < 120; i++) {
fo[i] = new FallingObject(this, i ); //add anything else needed for the constructor
}
Then each FallingObject is responsible for its own state, and when clicked it is able to report back to the ClickerGame instance. All you need now is a method in ClickerGame which each FallingObject can call.
public void clickedObj(int index) {
FallingObject temp = null;
if(index >= 0 && index < 120) {
temp = fo[index];
//Do stuff with temp :)
}
}
To call this method from within FallingObject just reference the 'master' variable (which you should probably save as a global variable within the class.
You have to check every element in your FallingObject[] array if it intersects with the mouse pointer coordinates at the moment of the click.
You can implement a simple rectangle test or use a circle for each cookie as explained here:
Equation for testing if a point is inside a circle
I have some code that creates Objects called Weights. Now there are subclasses of these Weights called - WeightSmall, WeightMedium, and WeightLarge - each with their own static variable called onScreen. This variable should increment when one of either WeightSmall, WeightMedium or WeightLarge is added, however these get return on the call of the create method rather than being added to an array. I have an array of Weight objects - is there a way to access what subclass type an element is in the array of the parent class?
Here is the code for creating weights:
public Weight createWeight() {
decider = Math.random() * 1;
// creates rocks randomly with the lowest chance for l, and the highest chance for m
if (decider <= 0.33) {
// small weight
return new WeightSmall(BitmapFactory.decodeResource(getResources(), R.drawable.weight_s), new Random().nextInt(screenWidth), -10);
} else if (decider <= 0.5 && decider > 0.33) {
// large weight
return new WeightLarge(BitmapFactory.decodeResource(getResources(), R.drawable.weight_l), new Random().nextInt(screenWidth), -10);
} else {
// medium weight
return new WeightMedium(BitmapFactory.decodeResource(getResources(), R.drawable.weight_m), new Random().nextInt(screenWidth), -10);
}
}
What needs to happen is for WeightSmall lets say, it needs to check WeightSmalls onScreen variable to see if it's smaller than, let's say 3. if it is return the weight. However I can't think of a way to access WeightSmall's onScreen variable as it needs to be created more than once and I tried implement them into an ArrayList but it causes complications in the update method. Here is the rest of the code (that matters) for the class:
public void render(Canvas canvas) {
if (canvas != null) {
canvas.drawColor(Color.WHITE);
player.draw(canvas);
Weight[] weightArray = weights.toArray(new Weight[0]);
for (Weight weight : weightArray) {
weight.draw(canvas);
}
}
}
// updates the weight's position on the screen and checks collision with the player
public void update() {
Weight[] weightArray = weights.toArray(new Weight[0]);
for (Weight weight : weightArray) {
weight.update();
if (weight.getBounds().intersect(player.getBounds())) {
player.setTouched(false);
Intent gameOverIntent = new Intent(this.getContext(), GameOverActivity.class);
this.getContext().startActivity(gameOverIntent);
((Activity) getContext()).finish();
}
}
}
// count down timer spawning weights in every tick
public void timer() {
if (start == true) {
if (weightSpawnTimer != null) {
weightSpawnTimer.cancel();
weightSpawnTimer = null;
}
weightSpawnTimer = new CountDownTimer(30000, 800) {
public void onTick(long millisUntilFinished) {
weights.add(createWeight());
}
public void onFinish() {
weightSpawnTimer.start();
}
}.start();
}
}
Edit for clarity: What I need to happen, is in the onTick method, check if the subclass of weight's onScreen variable is <= 3, if it is, create a new weight, if it isn't do nothing. Once the weight is then offscreen, decrement this variable so new weights of that subclass can then be created.
What about
class WeightSmall {
public WeightSmall(...) {
// increment static
}
}
Let each class be responsible to increment it's own number in case an instance is created.
Modifying a static variable from an instance is usually considered bad practice. The few legit use-cases are typically some sort of instance counting. At least when you don't count down.
Counting down is where the trouble starts because Objects do have a defined start but their end is not guaranteed. You can count down in finalize - i.e. when the garbage collector has found your instance - but that's not guaranteed to happen soon or at all. Using that to find out how many instances are on screen would correlate to the actual number but could be completely wrong.
So in a case when you want to know how many objects you show on screen you must actively count that number down once the place responsible for showing the objects let's go of one.
And since that is already a responsibility for the class that wants to know how many objects are on screen, it should as well keep track of the numbers in a local variable of it's own.
By using a static property you limit yourself to have just 1 screen. If you let the other place count the number you don't limit yourself.
Static variable initialized at 0, then on the constructor your make it +1