开发者

How do I get this program to read files instead of making a 2d list randomly?

Basically, I'm trying to make a variation of the Conway Game of life in python. Now, because of some miscommunication on how it was supposed to be done, I ended up making the program run the game on random instead of taking the player input for the initial start position. I tried making a function that takes file inputs, and while that works on its own isolated instance, I keep getting errors (AttributeError: 'Life' object has no attribute 'CurrentWorld') when I try to integrate it with the rest of the code. Can anyone point me in the right direction? Any help is appreciated.

import random
from time import sleep


class Life:


    LIVE_CELL = '#'
    DEAD_CELL = ' '
    DELAY = 1

    def __init__(self, width=10, height=10):
        self.width = width
        self.height = height
        self.cells = [[random.choice([True, False]) for _ in range(self.width)] for _ in range(self.height)]

    def NewWorld(self):
        '''
        Updates the cell grid according to Conway's rules
        '''
        next_cells = [[False for _ in range(self.width)] for _ in range(self.height)]
        for j in range(self.width):
            for i in range(self.height):
                neighbor_count = self.AliveNeigbours(i, j)
                if ((self.cells[i][j] and neighbor_count in (2, 3))
                        or (not self.cells[i][j] and neighbor_count == 3)):
                    next_cells[i][j] = True
        self.cells = next_cells

    def AliveNeigbours(self, i, j):
        count = 0
        for di, dj in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]:
            if self.cells[(i + di) % self.height][(j + dj) % self.width]:
                count += 1
        return count

    def FileReader(self):
        # get the file to read
        filename = input("Name of input file: ")

        # open, read, and close the file
        with open(filename, "r") as f:
            world = [list(line[:-1]) for line in f]

        # get derived information
        rows = len(world)
        columns = max([len(i) for i in world[0]])
        world_printable = '\n'.join([''.join(i) for i in world])

        return world, rows, columns, world_printable

    def Display(self):
        try:
            while (True):
                self.CurrentWorld()
                self.NewWorld()
                sleep(self.DELAY)
        except KeyboardInterrupt:
            pass

def start():
    if __name__ == '__main__':
        life = Life()
        life.Display()

start()
开发者_JS百科


Your code lacks the CurrentWorld method, which is responsible for the error you get.

Just add it to your Life class. For instance, it could be something like this:

    def CurrentWorld(self):
        for row in self.cells:
            print(" ".join("#" if cell else "." for cell in row))
        print()

To get the input from a file, your FileReader method should assign the instance attributes (cells, width, height). You didn't specify which format the input file is expected to use, but here is an example. Let's say the input file should have lines like this:

#.....
.##...
##....
......
......

Then the FileReader method could load that file as follows:

    def FileReader(self):
        filename = input("Name of input file: ")

        with open(filename, "r") as f:
            self.cells = [[ch == "#" for ch in line.rstrip()] for line in f]

        self.height = len(self.cells)
        self.width = len(self.cells[0])

And call it from the main program:

        life = Life()
        life.FileReader()
        life.Display()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜