我如何更改create_initial_grid函数,以便单元格的第一个位置由坐标列表而不是随机函数确定

问题描述

坐标文件katt.txt内容

3 4
3 7
4 4
4 5
4 6
4 7
5 3
5 8
6 3
6 5
6 6
6 8
7 3
7 8
8 4
8 5
8 6
8 7

代码

import time
import random
    
  
with open('katt.txt') as f:
    numbers = [int(elem) for elem in f.read().split()]

coordinates = zip(numbers[::2],numbers[1::2])

def create_initial_grid(rows,cols,coordinates):
    return [[1 if (x,y) in coordinates else 0 for y in range(cols)]
            for x in range(cols)]

  

def print_grid(rows,grid,generation):

    #Prints to console the Game of Life grid


    # A single output string is used to help reduce the flickering caused by printing multiple lines
    output_str = ""

    # Compile the output string together and then print it to console
    output_str += "Generation {0} - To exit the program early press <Ctrl-C>\n\r".format(generation)
    for row in range(rows):
        for col in range(cols):
            if grid[row][col] == 0:
                output_str += "-"
            else:
                output_str += "*"
        output_str += "\n\r"
    print(output_str,end=" ")


def create_next_grid(rows,next_grid):
    
    #Analyzes the current generation of the Game of Life grid and determines what 
    #cells live and die in the next generation of the Game of Life grid.
  

    for row in range(rows):
        for col in range(cols):
            # Get the number of live cells adjacent to the cell at grid[row][col]
            live_neighbors = get_live_neighbors(row,col,rows,grid)

            # If the number of surrounding live cells is < 2 or > 3 then we make the cell at grid[row][col] a dead cell
            if live_neighbors < 2 or live_neighbors > 3:
                next_grid[row][col] = 0
            # If the number of surrounding live cells is 3 and the cell at grid[row][col] was prevIoUsly dead then make
            # the cell into a live cell
            elif live_neighbors == 3 and grid[row][col] == 0:
                next_grid[row][col] = 1
            # If the number of surrounding live cells is 3 and the cell at grid[row][col] is alive keep it alive
            else:
                next_grid[row][col] = grid[row][col]


def get_live_neighbors(row,grid):
   
    #Counts the number of live cells surrounding a center cell at grid[row][cell].


    life_sum = 0
    for i in range(-1,2):
        for j in range(-1,2):
            # Make sure to count the center cell located at grid[row][col]
            if not (i == 0 and j == 0):
                # Using the modulo operator (%) the grid wraps around
                life_sum += grid[((row + i) % rows)][((col + j) % cols)]
    return life_sum


def grid_changing(rows,next_grid):
  
    #Checks to see if the current generation Game of Life grid is the same as the next generation Game of Life grid.
 

    for row in range(rows):
        for col in range(cols):
            # If the cell at grid[row][col] is not equal to next_grid[row][col]
            if not grid[row][col] == next_grid[row][col]:
                return True
    return False


def get_integer_value(prompt,low,high):
   
    #Asks the user for integer input and between given bounds low and high.
  

    while True:
        try:
            value = int(input(prompt))
        except ValueError:
            print("Input was not a valid integer value.")
            continue
        if value < low or value > high:
            print("Input was not inside the bounds (value <= {0} or value >= {1}).".format(low,high))
        else:
            break
    return value


def run_game():
   
    #Asks the user for input to setup the Game of Life to run for a given number of generations.
    

    # Get the number of rows and columns for the Game of Life grid
    rows = get_integer_value("Enter the number of rows (10-30): ",10,30)
    cols = get_integer_value("Enter the number of cols (10-30): ",30)

    # Get the number of generations that the Game of Life should run for
    generations = get_integer_value("Enter the number of generations (1-100000): ",1,100000)
    

    # Create the initial Game of Life grids
    current_generation = create_initial_grid(rows,coordinates)
    next_generation = create_initial_grid(rows,coordinates)

    # Run Game of Life sequence
    gen = 1
    for gen in range(1,generations + 1):
        if not grid_changing(rows,current_generation,next_generation):
            break
        print_grid(rows,gen)
        create_next_grid(rows,next_generation)
        time.sleep(1 / 5.0)
        current_generation,next_generation = next_generation,current_generation

    print_grid(rows,gen)
    input("Press <Enter> to exit.")


# Start the Game of Life
run_game()

解决方法

coordinates(x,y)元组的可迭代对象,指示您的网格应位于1的位置(否则为0),只需编写如下内容:

def create_initial_grid(rows,cols,coordinates):
    return [[1 if (x,y) in coordinates else 0 for y in range(cols)]
            for x in range(rows)]

create_initial_grid(2,3,[(0,0),(1,2),(2,1)])
# [[1,0],[0,1],1,0]]

假设您的文本文件由活细胞的xy交替组成,您可以通过以下方式读取坐标:

with open('coordinates.txt') as f:
    numbers = [int(elem) for elem in f.read().split()]

coordinates = list(zip(numbers[::2],numbers[1::2]))

或更短:

with open('coordinates.txt') as f:
    coordinates = [tuple(map(int,line.split()))
                   for line in f.readlines()]