import java.awt.*;
import hsa.Console;
public class Game{
static Console c;
public static void Wait (int time){
try{
Thread.sleep (time);
}
catch (InterruptedException e){
}
}
public static class Tile{
public int x,y,stack;
public Tile(){
x = 0;
y = 0;
stack = 0;
}
public Tile(int xco, int yco, int stacknum){
x = xco;
y = yco;
stack = stacknum;
}
public void draw(Tile tile){ //To draw the tile
if(stack>0){
c.setColor(Color.red);
c.fillRect(x*78+1+x,y*78+1+y,78,78); //Calculate coordinates
}
else{
c.setColor(Color.blue);
c.fillRect(x*78+1+x,y*78+1+y,78,78);
}
}
}
public static void main (String[] args){
c = new Console ();
for(int i=0;i<640;i+=79) c.drawLine(i,0,i,474);
for(int i=0;i<500;i+=79) c.drawLine(0,i,632,i);
//8x6 tiling
Tile[][] tile = new Tile[8][6];
for(int i=0;i<8;i++){
for(int j=0;j<6;j++){
tile[i][j] = new Tile();
tile[i][j].x = i;
tile[i][j].y = j; //Set x and y coordinates
tile[i][j].stack = 5;
}
}
Tile.draw(tile[0][0]);
}
}
Here I have a tile of 8x6 squares using a multidimensional array. I would think that the coordinates would correspond to the correct numbers, but for some reason the coordinates seem to copy the ones created before it. Could someone tell me why this is happening and how the code should be corrected? Btw I started java so I'm not completely used to object oriented programming :P
Your co-ordinates are declared as static:
public static int x,y,stack;
Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a static class variable, which is in one fixed location in memory.
You should however remove the static modifier to have specific value for each object of Tile
Edit:
From your below comment and for your better understanding, to work with draw() function:
Approach 1: If we wish to have draw function to be static:
public static void draw(Tile tile){ //To draw the tile
if(stack>0){
c.setColor(Color.red);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
//Calculate coordinates
}
else{
c.setColor(Color.blue);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
}
}
You can call this function by Tile.draw(tile); where tile is an instance of Tile
Approach 2: If draw(Title tile) function is non static: you don't need to pass the tile instance at all:
public void draw(){ //To draw the tile
if(stack>0){
c.setColor(Color.red);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
//Calculate coordinates
}
else{
c.setColor(Color.blue);
c.fillRect(tile.x*78+1 + tile.x, tile.y*78+1+tile.y, 78, 78);
}
}
Then create an instance Tile title = new Title() and call title.draw()
You've marked x, y, z as static so all instances of your class use the same ones, just remove the static keyword
Related
i need your help :)
i have a class Main :
public class Main {
private static ArrayList<Integer> xCoords = new ArrayList<Integer>();
private static ArrayList<Integer> yCoords = new ArrayList<Integer>();
public static void main(String[] args) {
Adress adress2 = new Adress(6, 8);
TourManager.addAdress(adress2);
Adress adress3 = new Adress(3, 4);
TourManager.addAdress(adress3);
Adress adress4 = new Adress(9, 12);
TourManager.addAdress(adress4);
Adress adress5 = new Adress(12, 16);
TourManager.addAdress(adress5);
// Initialize intial solution
Tour currentSolution = new Tour();
currentSolution.generateIndividual();
Tour best = new Tour(currentSolution.getTour());
System.out.println("Distance From adress (0,0): " + best.getDistance());
System.out.println("Solution distance : " + best.toString()+ "\n");
// i try to sent x and y Coordinates in my too ArraList xCoords, yCoords list
// in the oder to be used in the second class to draw line.
for (int i = 0; i < best.tourSize(); i++) {
xCoords.add(i, best.getAdress(i).x);
yCoords.add(i, best.getAdress(i).y);
}
for (int i = 0; i < best.tourSize(); i++) {
System.out.print(yCoords.get(i)+ " - ");
}
new Draw(); // new instance
}
Hier my second class to draw line :
public class Draw extends JPanel {
//private static ArrayList<Integer> xCoords = new ArrayList<Integer>();
//private static ArrayList<Integer> yCoords = new ArrayList<Integer>();
// how can i recover the tow ArrayList xCoords, yCoords in the order to make a loop for to exract x,y
public void paintComponent(Graphics g)
{
final int offset = 5;
super.paintComponent(g);
g.setColor(new Color(54,34,56));
for(int i = 1; i <xCoords.size() ; i++)
{
g.fillOval(xCoords.get(i), yCoords.get(i), 8, 8);
g.setColor(Color.RED);
g.drawLine(xCoords.get(i-1)+offset, yCoords.get(i-1)+ offset, xCoords.get(i)+ offset, yCoords.get(i)+ offset);
}
}
public Draw() {
final int width = 400; // Breite des Fensters
final int height = 450; // Hoehe des Fensters
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(width, height);
f.add(this);
f.setVisible(true);
}
}
i tried to instantiate Tour in Draw class, create a Loop for to add x,y coordinates in ArrayList then make another Loop to exract x, y to draw a line but in my tour i have no data and i should recreate Adress (x, y) to have data !
If you want to pass something to another class, just write a Constructor of the Class and add parameters for the things you want to pass.
In your case it would be smth like this:
public class Draw extends JPanel {
...
public Draw(ArrayList<Integer> xCoords, ArrayList<Integer> yCoords) {
// your code here. You can access the arraylists by the parameter name yCoords and xCoords
}
...
}
After that you just create an object of the class Draw and pass your arrays.
Hope this helps!
this is my problem:
I was trying to use the new for loop in java to print out some strings with doubles. When i compile the code, no errors, but no output, it's like if the for loop isn't working, any help?
the loop it's right in the end, i've printed all the code just to be sure.
abstract class Figure3D {
private float[] center;
protected void setCenter(float[] center){this.center = center;}
public abstract double calcolateVolumn();
protected abstract String figureType();
public void printVolumn(){
System.out.println("Volumn "+ figureType() + calcolateVolumn());
}
}
class Cube extends Figure3D{
private float side;
public Cube(float side, float[] center){
this.side = side;
setCenter(center);
}
#Override
protected String figureType(){
return "Cube ";
}
#Override
public double calcolateVolumn(){
return side*side*side;
}
}
class Sphere extends Figure3D {
private float radius;
public Sphere(float radius, float[] center){
this.radius = radius;
setCenter(center);
}
protected String figureType(){return "Sphere ";}
public double calcolateVolumn(){return ((4f/3f)*radius*radius*radius*3.14f);}
}
import java.util.ArrayList;
import java.util.List;
class TridimensionalFigures {
public static void main(String[] args) {
List<Figure3D> figures3d = new ArrayList<>(10);
Sphere sphere;
Cube cube;
for (int i = 0; i < figures3d.size(); i++) {
sphere = new Sphere(i, new float[] {i, i, i});
figures3d.add(i, sphere);
i++;
cube = new Cube(i, new float[] {i, i, i});
}
//TOFIX: it needs to print out the volums of all the objects in the arraylist
for (Figure3D figures : figures3d) {
System.out.printf("The volumns is: %s %n", figures.calcolateVolumn());
}
}
}
figures3d.size() is 0, so you are not adding anything to the list.
Try changing
for (int i = 0; i < figures3d.size(); i++) {
to
for (int i = 0; i < 10; i++) {
The problem is, the list is never actually populated.
You set it's initial capacity using the constructor, but that doesn't change the size; it just prevents reallocations later.
Because the size is 0, the populizing loop never runs, so the second loop (in question) is skipped due to the list being empty.
Instead of using the list's size to control the populating loop, extract the magic 10 into its own variable, and loop while i < tenVariable.
public class NewTest {
public static void main(String[] args)
{
String [][] table;
table = new String [4][4];
for(int y=0; y<4; y++){
for(int x=0; x<4; x++){
table[y][x] = " ~ " ;
}
}
int y, x;
for(y=0; y<4; y++)
{
System.out.print(y+": ");
for(x=0; x<4; x++)
System.out.print(table[y][x]+" ");
System.out.println();
}
}
public void table ()
{
System.out.println(table[2][2]);
}
}
//this is the line where I have problems !
System.out.println(table[2][2]);
The problem is that String [][] table is local to the method where it is declared, and is, therefore, invisible to other methods of the class.
There are two ways of making it visible:
Make String [][] table a static member in the enclosing class (because main is static), or
Pass String [][] table to the function as a parameter.
The second solution is usually better:
// Here is the declaration of a method taking 2D table
public static void showTableCell(String [][] table) ...
...
// Here is a call of that method from main():
showTableCell(table);
Very basic java knowledge at the moment, in need of some assistance in trying to create a game of Pacman.
Currently I have three classes, the player class, the dot class and the game class, all interacting to create a basic game of Pacman.
The issue I am having is this:
I need the 'initialX and initialY fields as show below (these will be user inputted coordinates);
public class Player
{
private int x, y, collectedDots;
public Player(int initialX, int initialY)
{
x = initialX;
y = initialY;
collectedDots = 0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
to pass through as my parameters within the new 'player' object within the Game Class.
public class Game
{
public Game()
{
Player player = new Player();
Dot dot1 = new Dot();
Dot dot2 = new Dot();
Dot dot3 = new Dot();
}
}
It has me stumped, and I'm assuming I've either gone about this the wrong way, or I'm completely missing something.
Your declared constructor take two int parameters, and you call it with out sending any parameters.
When use the below line, the compiler will look for a default constructor that takes no parameters, but it will fail since you haven't declared a default one, but you declared a constructor with two int parameters.
Player player = new Player();
With this line:
Player player = new Player(1, 2);// pass two int parameters t your defined constructor.
You can have variables defined in your Player class and then assign those variables to other variables in the constructor of the same class like so:
public class Player
{
private int x, y, collectedDots;
int initialX = 15;
int initialY = 20;
public Player()
{
x = initialX;
y = initialY;
collectedDots = 0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
Now your x is equal to 15 and y is equal to 20. But these values are all part of the Player class. However, you create an object of the Player class in the Game class and through that object you can access x and y like so:
public class Game
{
public Game()
{
Player player = new Player();
System.out.println(player.getX()); // prints out 15 in the console
System.out.println(player.getY()); // prints out 20 in the console
Dot dot1 = new Dot();
Dot dot2 = new Dot();
Dot dot3 = new Dot();
}
}
You can of course do whatever you want with these values (like assign them to new variables in the Game class and manipulate them there). I am just printing them out so you can see that its the values from the Player class.
UPDATE
You can take user input before you create the Player object and then pass those values to the constructor of the Player class like so:
public class Game
{
public Game()
{
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
Player player = new Player(i,j);
System.out.println(player.getX()); // prints out 15 in the console
System.out.println(player.getY()); // prints out 20 in the console
Dot dot1 = new Dot();
Dot dot2 = new Dot();
Dot dot3 = new Dot();
}
}
This is, of course, provided you keep your Player class how you posted it originally. But if you want to continue being able to change the values of x and y you can always provide Setter methods. Your class will then become:
public class Player
{
private int x, y, collectedDots;
public Player(int initialX, int initialY)
{
x = initialX;
y = initialY;
collectedDots = 0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
}
Whenever you want to then change the values of x and y from the Game class then you'd just have to do the following (just an example):
public class Game
{
public Game()
{
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
Player player = new Player(i,j);
player.setX(35);
player.setY(48);
}
}
Again, this is just an example. I wouldn't really be doing all of this in the constructor but just using this to explain how you can do what you want.
I am new to Java and I'm grateful if anyone could help with the below. I am trying to make a scorekeeper for my chessboard. At the moment, the score will go back to zero everytime. How would I be able to save the previous score and add it every move? Thanks!
public static int scoreKeeper(Chessmen[][] chessboard, int X, int Y, int X1, int Y1, int currentNumber, int totalNumber){
AbstractPiece knight = new Knight();
AbstractPiece bishop = new Bishop();
AbstractPiece pawn = new Pawn();
AbstractPiece king = new King();
AbstractPiece queen = new Queen();
AbstractPiece rook = new Rook();
if ((chessboard[Y][X] == Chessmen.WHITE_KNIGHT) ||
(chessboard[Y][X] == Chessmen.BLACK_KNIGHT)){
currentNumber = currentNumber+totalNumber+knight.relativeValue();
return currentNumber;
}else return totalNumber;
}
The main problem you have is that you are passing the value of currentNumber as a parameter
that means it will not change outside this method
this Example will illustrate my point
public class Test{
public static void main (String[] args){
int a = 0 ;
changeValue(a);
System.out.print(a);
}
public static void changeValue(int a){
a=20;
}
}
the output will be always 0 .
you can solve it by writing the methods getValueOfCurrentNumber() and getValueOfTotalNumbe()
to get the values [currentNumber and totalNumbe] instead of taking them as parameters .
The easiest solution is to store your score as a class data member:
class Game {
static int score;
public static int updateScore(... some inputs...) {
if(some condition is true) {
score = score + whatever you want to add;
}
}
}
The class retains the value of "score" between method calls.
I suspect that you have a bad abstraction. I think you want a Chessboard to hide the 2D array of Chessmen. Let it keep the current score as a data member. Provide methods to select and move pieces appropriately.
I can see its constructor instantiating a Chessboard. It would set each of the pieces at their appropriate starting positions. Then each Player would take turns moving.
Not a trivial problem.