Basic PYTHON: Conway\'s Game of Life In this game, you have a grid where pixels
ID: 3759915 • Letter: B
Question
Basic PYTHON: Conway's Game of Life
In this game, you have a grid where pixels can either be on or off, and simple rules that govern whether those pixels will be on or off (dead or alive) at the next timestep. The rules are as follows:
Any live cell with fewer than two live neighbors dies
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies.
Any dead cell with exactly three live neighbors becomes a live cell.
Ask the user for the size of the game board (rows first, then columns), and any cells they'd like alive when the game begins. Then ask the user how many iterations they'd like to run, and display each one of those.
Live cells are to be represented with the character "A" and dead cells are to be represented with the character "."
This code must also include input validation. Assume the user will enter the right type on input (int), but an incorrect/invalid value. Validate when the user is entering rows and columns, rows and columns must be greater than 1. Validate when getting the cells to make alive, the row must be either "q" for quit or a valid index for the number of rows/columns your board has. Validate when getting iterations, must be 0 or greater.
Store your board in a 2D list, and have a function called nextIteration() that takes the current board in as a parameter and returns a new board with the next iteration, and a function called printBoard() that takes in the current board as a parameter and prints the board's contents.
Here is an example of the input validation:
Please use Python and use simple beginner codes w/out using the already existing functions in Python. This shouldn't be hard for programmers who have seen Conway's before and know beginner Python. Comments would also be appreciated since this code is very long and difficult! Thank you!
Explanation / Answer
class Cell
{
public Point Position { get; private set; }
public Rectangle Bounds { get; private set; }
public bool IsAlive { get; set; }
public Cell(Point position)
{
Position = position;
Bounds = new Rectangle(Position.X * Game1.CellSize, Position.Y * Game1.CellSize, Game1.CellSize, Game1.CellSize);
IsAlive = false;
}
public void Update(MouseState mouseState)
{
if (Bounds.Contains(new Point(mouseState.X, mouseState.Y)))
{
// Make cells come alive with left-click, or kill them with right-click.
if (mouseState.LeftButton == ButtonState.Pressed)
IsAlive = true;
else if (mouseState.RightButton == ButtonState.Pressed)
IsAlive = false;
}
}
public void Draw(SpriteBatch spriteBatch)
{
if (IsAlive)
spriteBatch.Draw(Game1.Pixel, Bounds, Color.Black);
// Don't draw anything if it's dead, since the default background color is white.
}
}