How do I go about making this Conways Life program in java - java

I am making a Conway's Game of Life program in java, and am trying to change it from the command line version to a GUI. From the command line I just printed an array which showed the generations (the objects such as blocks and blinkers are shown as a series of 1's and 0's where it is blank, and in the GUI I'm showing it as squares (white squares as blank and blue squares where it isn't). But where I'm getting stuck is when I make another method (which replaces the method which prints the array) which checks the grid array, if there is a zero then the square changes from white to blue, and vice-versa. The Conway's Life rules are dealt with in a separate class which is independent, and all this method does is after the rules have changed the array this method checks it.
The rules are done in methods in one class and the GUI components are done in another. But since I need instance of both how would I go about doing it?, merge the two classes (all the GUI classes into the Life one, embed them some how, I am completely stuck on what to do
public void runGUI() {
int x = getX(), y = getY();
x /= squareSize;
y /= squareSize;
for (int i = 0; i < LifeData.grid.length; i++) {
for (int j = 0; j < LifeData.grid[i].length; j++) {
if (LifeData.grid[i][j] == 0)
l.setCell(x, y, l.getCell(x, y) + 1);
else
l.setCell(x, y, l.getCell(x, y) - 1);
this.repaint();
}
}
}
That is what I have changed it to now but when compiling it is saying "non-static variable grid cannot be referenced from a static context" and "non-static method runGUI() cannot be referenced from a static context". When trying to run the method.

Make a separate thread that will execute the game of life and update the GUI.
Something like this
public class GameExecutor implements Runnable {
private static final int DELAY = 1000;
private GameOfLife game;
private boolean stop = false;
private Gui gui;
public GameExecutor(Gui gui, GameOfLife game) {
this.gui = gui;
this.game = game;
};
public void run(){
game.start();
while (!stop) {
game.step(); //execute a step
gui.update(game.getState());
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {}
}
}
}
Launch this in a thread at startup and pass it your gui. Don't forget to update the gui in the correct Swing thread.
Obviously you'll need to add some code to stop it, too :)

Related

Need help for java chess program

I have a project to do and I am completely stuck at this point and have no idea and inspiration on how to continue my code. I have certain tasks and specifications on how to write my code.
This means the code should have a minumum of these classes and methods:
2 enums, one for Color with WHITE and BLACK, and one called ClassPieceType which means KING, QUEEN...
ChessPiece, which is an abstract class and all classes for the types like King, queen which inherit from ChessPiece..
a Board which represents the board with all his figures on it. But I somehow cannot progress on the board and I have no idea on how to implement the methods.
package chess;
public class Board {
public static String[][] chessBoard2() {
String[][] board = new String[8][8];
char letter = 'a';
int number;
for (int row = 0; row < board.length; row++) {
number = 8;
for (int column = 0; column < board[0].length; column++) {
board[row][column] = Character.toString(letter) + number;
number--;
}
letter++;
}
return board;
}
}
This is my idea of a create board method. But the task says
Method has to be public Board() which creates the board in his normal state, and with unicode you have to add the pieces.
But I have no idea on how to implement the unicode, either. And how is it called just public Board? There isn't a return type. I just don't know any more.
I hope someone with HUGE patience can help me. I am just too incompetent to program and we have to hand our task in in several days.
"1. Method has to be public Board() which creates the board in his normal state [...]"
The confusion comes from the fact that such thing is not called a "method" but instead is called a "constructor". It initialize the object you want to create. The goal is that when you write new Board() it does initialize the board with the starting position of chess, something similar to what you are trying with the chessBoard2() method. The Board class can look like this:
public class Board {
private final String[][] board;
public Board() {
this.board = new String[8][8];
Board.fillFirstLine(this.board, 8, Color.BLACK);
Board.fillPawnLine(this.board, 7, Color.BLACK);
Board.fillPawnLine(this.board, 2, Color.WHITE);
Board.fillFirstLine(this.board, 1, Color.WHITE);
}
private static void fillFirstLine(String[][] board, int rowNumber, Color color) {
// ...
}
private static void fillPawnLine(String[][] board, int rowNumber, Color color) {
// ...
}
}
Then somewhere else you write
Board board = new Board();
and you have a fully initialized board ready to use.
"[...] and with unicode you have to add the pieces."
The chess piece icons are present in the unicode charset, see Chess symbols in Unicode. This means you can save the string "\u2654" or the string "♔" inside the array to have this piece at the given position.

Java: Animated Sprites on GridLayout Part 2

This is a continuation from my last post Java: Animated Sprites on GridLayout. Thanks to a reply, it gave me an idea in where I just had to insert a loop in the trigger condition and call pi[i].repaint() in it. So far it works. Though I tried to integrate it to my game which composed of multiple sprites, it had no improvement in it. Without the animation, the sprites show on the grid with no problems. I inserted the animation loop in the GridFile class and it didn't show. I also tried to insert the animation loop in the MainFile, it showed irregular animations, kinda like a glitch. Can someone tell me where did I went wrong? Ideas are welcome.
MainFile class
public class MainFile {
JFrame mainWindow = new JFrame();
public JPanel gridPanel;
public MainFile() {
gridPanel= new GridFile();
mainWindow.add(gridPanel,BorderLayout.CENTER);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(700,700);
mainWindow.setResizable(false);
mainWindow.setVisible(true);
}
public static void main(String[]args){
new MainFile();
}
}
GridFile class
public class GridFile extends JPanel{
ImageIcon gameBackground = new ImageIcon(getClass().getResource("Assets\\GridBackground.png"));
Image gameImage;
int[] pkmArray = new int[12];
int random = 0;
Pokemon[] pkm = new Pokemon[36];
JPanel[] pokeball = new JPanel[36];
int j = 0;
public GridFile(){
setLayout(new GridLayout(6,6,6,6));
setBorder(BorderFactory.createEmptyBorder(12,12,12,12));
gameImage = gameBackground.getImage();
for(int i = 0;i < 36;i++){
do{
random = (int)(Math.random() * 12 + 0);
if(pkmArray[random] <= 3){
pokeball[i] = new Pokemon(random);
pokeball[i].setOpaque(false);
pokeball[i].setLayout(new BorderLayout());
pkmArray[random]++;
}
}while(pkmArray[random] >= 4);
add(pokeball[i],BorderLayout.CENTER);
}
while(true){
for(int i = 0; i < 36; i++){
pokeball[i].repaint();
}
}
}
public void paintComponent(Graphics g){
if(gameImage != null){
g.drawImage(gameImage,0,0,getWidth(),getHeight(),this);
}
}
}
Use a swing Timer for the repainting, and give a bit time between the frames for swing to do the painting work. There's no point trying to draw faster than what could be displayed anyway. If you have the animation loop in main(), the repaint manager will try to drop some of the repaint requests that appear close to each other, which can be the cause of the irregular animation you see.
You should create and access swing components only in the event dispatch thread. You current approach is breaking the threading rules.
Addition: When the animation loop is where you have it now, the GridFile constructor never returns, which explains that you'll see nothing because the code never gets far enough to show the window.

Setting a value, then changing it one second later

Right now I'm working on a sort of space-invaders style game. You move the character to the y coordinate where the enemy is, and shoot.
There is four windows that the player will shoot at. There will ALWAYS be an enemy in one of them.
So here is how the code would work:
enemylocation = 1;
*CHANGE VALUE EVERY X SECONDS
if(enemylocation==1){
enemy.draw(x, y, size);
}
if(enemylocation==2){
enemy.draw(x, y, size);
}
if(enemylocation==3){
enemy.draw(x, y, size);
}
if(enemylocation==4){
enemy.draw(x, y, size);
}
What would the timing code/method be?
Thanks
You would want to use something like this:
public static void main(String[] args) throws InterruptedException
{
while(true) //Makes the code run forever
{
enemylocation++; // increments 1
Thread.sleep(1000); // Waits one second
}
}
Most people would use a Swing timer to update code over a given time interval. I would use the java.Math.Random Class to change the number to 1-4.
public class game implements ActionListener{
Timer enemyUpdate;
int enemylocation;
public game(){
enemyUpdate = new Timer(1000, this); //1000ms = 1s
enemyUpdate.start();
}
public void actionPerformed(){
//utilize math.random to change enemylocation every second
}
}

Java Swing Frame crashes upon opening?

I am programming a chess game in java, and at the moment I am building a basic interface. It is simply an 8x8 array of buttons that will display in a window. I have coded for these buttons, and have gotten the board to display properly. However, when I connect this with the rest of the game, the game window crashes upon running and I have to force quit the java application. This is my code:
package Chess_Game;
import javax.swing.SwingUtilities;
import Chess_Interface.Iboard;
public class Game_Tester
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Game G = new Game();
Iboard I = new Iboard(G.getBoard().getArray(), G.getSides());
I.setVisible(true);
while(!(G.isGameOver()))
{
boolean redo = true;
while(redo)
{
int row = 0;
int col = 0;
int nRow = 0;
int nCol = 0;
System.out.println("Click the piece you want to move.");
while(!(I.getBool())){}
if(I.getBool())
{
row = I.getRow();
col = I.getCol();
I.setBool(false);
}
System.out.println("Click the place you want to move to.");
while(!(I.getBool())){}
if(I.getBool())
{
nRow = I.getRow();
nCol = I.getCol();
I.setBool(false);
}
if(G.canMove(row, col, nRow, nCol))
{
G.move(row, col, nRow, nCol, I);
redo = false;
}
else
{
System.out.println("You cant move there! Try again!");
}
}
I.updateBoard(G.getBoard().getArray(), G.getSides());
}
}
});
}
}
The board displays properly when I comment out the main while loop (and everything inside of it), and I assume the problem lies somewhere inside there, but I have been unable to find it. I have also looked online for similar game loop problems, but all of those have been for games involving frame rates and movement across a java swing frame, something that is not present in my code.
Any help would be greatly appreciated.
You have several loops such as
while(!(I.getBool())){}
which could potentially run forever if I does not respond as expected. You could start by printing something out within these loops, and within the following blocks if(I.getBool()){...} to see at what point your application gets stuck.
Checking the user interface in a loop like this is not good practice. It is better to use Listeners to respond to the user interface.
Nor is running the main application on the Swing thread using SwingUtilities.invokeLater(new Runnable(), even though it avoids potential problems of updating the GUI from another thread.
In fact, this may be your root problem, as running the main application loop on the Swing thread (the thread used to run the GUI) like this probably prevents the GUI from ever responding properly. You are putting a task (the entire game) onto the GUI's queue, but that task never completes while(!(G.isGameOver())).

Shooting sprite android

I am developing an Android game in java where I will have a sprite that follows the user's finger and is supposed to fire a bullet every second. In other words, I am trying to attach a bitmap that moves up every second. The bitmap starts at the x and y coordinates of the main character sprite. I can't get it to draw more than one missile at a time, and I have run out of ideas of how to do so. I have tried so many things, and I really could use some help.
By the way, my Main Game Panel class extends a surfaceView and implements a SurfaceHolder.Callback:
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback{
Thanks!
As far as I understand you want to have the ability to shoot more than 1 bullet at a time? You can use a Vector or Array to do this. With an Array you can set a default amount of visible bullets and in a Vector you could have as mant bullets that your finger is capable of producing.
Here's my code that I use to generate lasers (I store the values in an Array).
public void updatePlayerLaser(boolean shootLaser) {
// Check if a new Laser should be created
if(shootLaser == true) {
if(timeLastCreatedLaser + 100 < System.currentTimeMillis()) {
timeLastCreatedLaser = System.currentTimeMillis();
boolean createdNewLaser = false;
for(int i = 0; i < this.amountOfVisibleLasers; i++) {
if(createdNewLaser == false) {
if(holderLaser[i].isDisposed()) {
this.generateNewLaser(i);
createdNewLaser = true;
}
}
}
}
}
// Update all the other Lasers
for(int i = 0; i < this.amountOfVisibleLasers; i++) {
if(holderLaser[i].isDisposed() == false) {
holderLaser[i].update();
}
}
}
Disposed in this contexts means that the laser is dead, thus making space for a new laser to take the old lasers spot.

Categories