logo
down
shadow

I have started writing the Game of Life in Java and the count of surrounding cells is not correct


I have started writing the Game of Life in Java and the count of surrounding cells is not correct

By : user6064090
Date : November 20 2020, 11:01 PM
I wish this helpful for you I am a beginner at Java programming (1st semester) and I have been writing code for the Game of Life. I am counting the surrounding cells of each cell in a two-dimensional array. I have reached the point where the program compiles well, but when I test it with different sizes of the array, I can see that the count of the cells is not correct, although the consequent swapping of the cells' status is performed correctly, and I cannot figure out how this can be. Please help: , You use
code :
int minRow = i == 0 ? i : i - 1;
int maxRow = i == (around[i].length - 1) ? around[i].length - 1 : i + 1;
int minCol = j == 0 ? j : j - 1; 
int maxCol = j == (around[i].length - 1) ? around[i].length - 1 : j + 1; 
int minRow= Math.max(0,i-1);
int maxRow= Math.min(around.length-1,i+1);
int minCol= Math.max(0,j-1);
int maxCol = Math.min(around[i].length-1,j+1);
int maxCol=Math.min(around.length-1,j+1);


Share : facebook icon twitter icon
Writing a Java program to run with a pre-built interface (the Life game) but I'm having trouble

Writing a Java program to run with a pre-built interface (the Life game) but I'm having trouble


By : Mohammed Al-Muzel
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Here's your problem. In your createMatrix() method you define a local variable matrix when you really want to modify the field matrix.
You may find it useful to access fields with this, e.g. this.matrix. It makes a clear distinction in the code. However, most IDEs will auto highlight fields and local variables so some people find it unnecessary, it's a question of style and not overly important.
code :
   public static void createMatrix() {

    Random seedBool = new Random(rSeed);

    this.matrix = new boolean[r][c];

    for (int i = 0; i < this.matrix.length; i++) {
        for (int j = 0; j < this.matrix[i].length; j++) {
            this.matrix[i][j] = false;
        }
    }

    for (int i = 1; i < this.matrix.length - 1; i++) {
        for (int j = 1; j < this.matrix[i].length - 1; j++) {
            this.matrix[i][j] = seedBool.nextBoolean();
        }
    }

}
JAVA - Conway's Game of Life deletes all alive cells?

JAVA - Conway's Game of Life deletes all alive cells?


By : a83533774
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You just have a couple small issues with your LifeModel class.
In your constructor you set the tempWorld to reference the same array as the actual game world. This will cause any modifications to tempWorld to also affect the gameWorld.
code :
public LifeModel(int rows, int cols)
{
    this.numRows=rows;
    this.numCols=cols;
    world = new boolean[rows][cols];
    initWorld();
    //tempWorld = world;  // You can remove this line.
}
public void nextGeneration()
{
    tempWorld = new boolean[numRows][numCols]; // Keep it the same size

    int rows = world.length;
    int columns = world[0].length;

    for(int i=0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
        {
            toggleCell(i,j);
        }
    }
    world = tempWorld;
}
package gameOfLife;

public class LifeModel
{
private boolean[][] world;
private int numRows;
private int numCols;
private boolean[][] tempWorld;



public LifeModel(int rows, int cols)
{
    this.numRows=rows;
    this.numCols=cols;
    world = new boolean[rows][cols];
    initWorld();
}

private void initWorld()
{

    boolean done = false;

    while(!done)
    {
        int i = (int) (Math.random()*numRows);
        int j = (int) (Math.random()*numCols);
        if(j>0 && i>0 && i<numRows-1 && j<numCols-1)
        {
            /*
             world[i-1][j-1] = true;
             world[i-1][j] = true;
             world[i-1][j+1] = true;
             world[i][j+1] = true;
             world[i+1][j] = true;
             */
             world[i][j]=true;
             world[i+1][j]=true;
             world[i-1][j]=true;
             done = true;
        }
    }


}

public void nextGeneration()
{
    tempWorld = new boolean[numRows][numCols];

    int rows = world.length;
    int columns = world[0].length;

    for(int i=0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
        {
            toggleCell(i,j);
        }
    }
    world = tempWorld;
}

public void toggleCell(int r, int c)
{
    int count = numLivingNeighbors(r,c);
    if(!world[r][c] && count==3)
    {
        tempWorld[r][c] = true;
    }
    else if(world[r][c] && (count>=2 && count<=3))
    {
        tempWorld[r][c] = true;
    }
    else
    {
        tempWorld[r][c] = false;
    }
}

public int numLivingNeighbors(int r, int c)
{
    int count = 0;
    boolean newCells[][] = world;
    for(int i = -1; i<=1; i++)
    {
        for(int j = -1; j<=1; j++)
        {
            if(i!=0 || j!=0)
            {
                int row = r + i;
                int column = c + j;
                if(row>=0 && row < newCells.length && column>=0 && column<newCells[0].length && newCells[row][column])
                {
                    count++;
                }
            }
        }
    }
    return count;
}

public void userChange()
{

}

public boolean[][] getWorld()
{
    return world;
}


}
Conway's Game of Life-Cells Dying When They're Not Supposed to? (Java)

Conway's Game of Life-Cells Dying When They're Not Supposed to? (Java)


By : Spark
Date : March 29 2020, 07:55 AM
I hope this helps . I am trying to code a very basic version of Conway's Game of Life. My program almost works but the 1's (which represent the alive cells) keep dying even when they have two or three live neighbors. It's strange because the blinker works but when I try the beacon pattern it no longer works. , The logic in here:
code :
for(int a=0; a<=2; a++)
{
    for(int b=0; b<=2; b++)
    {
        if(surrounding[a][b]==1)
        {
            counter ++;
        }
    }
}
Game of Life - Java, doesn't work (not showing cells)

Game of Life - Java, doesn't work (not showing cells)


By : Leks12lk
Date : March 29 2020, 07:55 AM
hope this fix your issue I don't see why anything should draw. You've got a Cell class that yes has a paintComponent method, but this method is meaningless since it's not part of a Swing component. Your JPanel, where you should do drawing -- does nothing. You've other problems with the Cell class too in that it appears to be trying to draw the whole grid and not just a single cell.
Get rid of Cell's paintComponent method Instead give it a public void draw(Graphics g) method that allows it to draw itself. Create a JPanel that holds a grid of cells Have this JPanel do the drawing in its paintComponent override. It will call the draw(g) method of all the Cells that it holds within a for loop. Always place an @Override annotation above any overridden method. If you had done this, above your paintComponent, the compiler would have warned you that something was wrong.
code :
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleCellGrid extends JPanel {
    private static final int ROWS = 40;
    private static final int COLS = 40;
    private static final int CELL_WIDTH = 10;
    private static final int PREF_W = CELL_WIDTH * COLS;
    private static final int PREF_H = CELL_WIDTH * ROWS;
    private SimpleCell[][] cellGrid = new SimpleCell[ROWS][COLS];

    public SimpleCellGrid() {
        MyMouse myMouse = new MyMouse();
        addMouseListener(myMouse);
        for (int row = 0; row < cellGrid.length; row++) {
            for (int col = 0; col < cellGrid[row].length; col++) {
                int x = col * CELL_WIDTH;
                int y = row * CELL_WIDTH;
                cellGrid[row][col] = new SimpleCell(x, y, CELL_WIDTH);
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        for (SimpleCell[] cellRow : cellGrid) {
            for (SimpleCell simpleCell : cellRow) {
                simpleCell.draw(g2);
            }
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private class MyMouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            for (SimpleCell[] cellRow : cellGrid) {
                for (SimpleCell simpleCell : cellRow) {
                    if (simpleCell.contains(e.getPoint())) {
                        simpleCell.setAlive(!simpleCell.isAlive());
                    }
                }
            }
            repaint();
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("SimpleCellGrid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new SimpleCellGrid());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;

public class SimpleCell {
    private static final Color CELL_COLOR = Color.RED;
    private boolean alive = false;
    private int x;
    private int y;
    private int width;
    private Rectangle rectangle;

    public SimpleCell(int x, int y, int width) {
        this.x = x;
        this.y = y;
        this.width = width;
        rectangle = new Rectangle(x, y, width, width);
    }

    public boolean isAlive() {
        return alive;
    }

    public void setAlive(boolean alive) {
        this.alive = alive;
    }

    public void draw(Graphics2D g2) {
        if (alive) {
            g2.setColor(CELL_COLOR);
            g2.fill(rectangle);
        }
    }

    public boolean contains(Point p) {
        return rectangle.contains(p);
    }

    @Override
    public String toString() {
        return "SimpleCell [alive=" + alive + ", x=" + x + ", y=" + y + ", width=" + width + ", rectangle=" + rectangle
                + "]";
    }

}
Multithreaded Java Program for Conway's game of life - contention at the border cells

Multithreaded Java Program for Conway's game of life - contention at the border cells


By : user3848991
Date : October 23 2020, 11:12 PM
hope this fix your issue I suggest having 2 int[][] arrays. Let's call them A and B. A will hold the values of all odd numbered "ticks" and B will hold the even numbered ticks.
Initialize A to whatever your initial state looks like. Then let your threads loose to calculate the next state of each cell, and place the results in the corresponding cell in B. Once all your threads are done, you have your new state in B. Now, use B to calculate the next state of each cell, and store the results in A. At any given time, one array will be read only, and the other write only, so there will never be any contention.
Related Posts Related Posts :
  • TACO Java Dependencies
  • Javafx filechooser name filter
  • No rule to make target `external/obpermissionjar/javalib/obpermissionjar-Pro20160628_1.0.9', needed by ..?
  • Spring Data REST: custom methods validation
  • JavaFX MousedMoved event ignored when mouse button is held down
  • ExecutorService and OutOfMemoryError: unable to create new native thread while using Executor
  • Java Security Manager completely disable reflection
  • Placement of Thread Content. How do you know what goes inside of the thread, and what doesn't?
  • can not search for txt files android 6.0
  • Monitor program using semaphore does not work as expected in java
  • A way to define / implement failover ldap servers in java code
  • How to save embedded object in POST call using Spring Data Rest
  • Methods in test in parallel way
  • What would be the best way to implement to check if the Post has been liked by the User using JPA and MySQL?
  • GCM unregister causing the application to crash
  • Test configuration annotations in separate annotation
  • How to catch third party console log using log4j
  • Spring Boot: Conditional on database type
  • Java: Loading data from a file located under project folder fails
  • Epson epos sdk receipt alignment issue
  • Java Comparable: helper methods for isLessThan, isGreaterThan, isEqualTo
  • How to find the native method from the JVM source code?
  • Insert datetime string from java in MySQL
  • Regex look ahead to seperate string into tokens
  • How the java de-compiler get to know the variable or object names?
  • Java generics "capture of ?"
  • Specify the default value of the JSONP callback in spring using jackson?
  • Digital Signature created in C# doesn't match in Java verification
  • How to push down project, filter, aggregation to TableScan in Calcite
  • Java/SQL find duplicates
  • Getting a null error trying to add objects into an arraylist (simple piece of code)
  • JDBC query returning zero when using simple arithmetic operations and alias even though the data in table is not zero
  • incompatible type while adding value to Map
  • Openshift Build Failure - Failed to read artifact descriptor
  • updating neo4j database using java program
  • how to save an image to disk and retrive it with java/jsp
  • How to verify kerberos token?
  • String to byte array conversion varies from windows and ubuntu
  • Custom MavenResourcesFiltering hard to implement?
  • TestNG XML file failed to invoke/create the XSSFWorkbook
  • BigDecimal issue with long and lat
  • I am new to JavaFX. I want help on how to make a TreeView node Draggable and Droppable
  • Microservices and Messaging: Message Content
  • How to move an email service into a thread?
  • Reading a .csv file faster than reading same file compressed as .gz
  • How to change the json response fields to user defined fields in java?
  • Retrofit: Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for CustomClass
  • Basic Authentication failed in Windows server 2012 Using Java
  • Avoid Transaction rollback in Spring
  • Transition between right - up, left - down, down - left etc. (JAVA game LWJGL keylistener)
  • How to setup a common classpath for all dependencies inside a maven project?
  • How is Mockito.mock better that using new while writing Junit tests?
  • In apache http client, how to keep the Content-Type in a StringBody as empty or null?
  • SQuirreL Configure: could not initial class org.apache.phoenix.jdbc.PhoenixDriver
  • ResponseEntity decode UTF-8
  • Time difference gives wrong value
  • How to read in and split a string of numbers separated by whitespace and forward slash
  • InvocationTargetException in javafx
  • method reference vs lambda expression
  • Scaling issue in BigDecimal(java) for exponential notation
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com