python - 如何查看网格和单元格 Python 中的内容

标签 python list class

我知道这已经过去一天了,但用户输入了一组坐标以将线“放置”在他们选择的任何单元格中,“*”将被放置在网格中。

我的两个主要问题是让网格显示在 CarpetSea __str__ 方法中,以及让线也放置在网格中。

这是我当前的代码

import random
import time

class Coordinate:
    '''
    '''
    def __init__(self, row, col):
        ''' 

        '''
        self.row = row 
        self.col = col

    def __str__(self):
        '''

        '''
        return "(%d, %d)" %(self.row, self.col)

class Cell:
    '''

    '''

    def __init__(self, row, col):
        '''

        '''
        self.coords = Coordinate(row, col)
        self.fish = ""
        self.contains_line = False

    def __str__(self):
        '''
        '''

        if self.fish:
            if self.contains_line:
                result = 'F*'
            else:
                result = 'F'
        else:
            if self.contains_line:
                result = '*'
            else:
                result = ' '

        return result


class CarpetSea:
    '''

    '''

    fish_caught = 0 
    def __init__(self, N):
        '''

        '''

        self.N = N
        self.grid = []
        for i in range(self.N):
            row = []
            for j in range(self.N):
                cell = Cell(i, j)
                row.append(cell)
            self.grid.append(row)


        self.available_fish = ["Salmon", "Marlin", "Tuna", "Halibut"]


    def __str__(self):
        '''
        returns a string representation of a CarpetSea, i.e. display the organized contents of each cell. 
        Rows and columns should be labeled with indices.

        Example (see "Example Run" in the PA8 specs for more):
          0  1  
        --------
        0|M |  |
        --------
        1|  |* |
        --------

        Note: call Cell's __str__() to get a string representation of each Cell in grid
        i.e. "M " for Cell at (0,0) in the example above
        '''        

        return " 0  1  \n -------- \n 0| %s  | %s  | \n -------- \n 1| %s  | %s  | \n -------- "%(self.grid[x,y].fish for x in range(self.N) for y in range(self.N))


    def randomly_place_fish(self):
        '''
        randomly selects coordinates of a cell and randomly selects a fish from the available_fish list attribute. 
        Marks the cell as containing the fish.
        '''

        cell = random.choice(random.choice(self.grid))
        cell.fish = random.choice(self.available_fish)
        fish_name = cell.fish[0]
        return(fish_name)


    def drop_fishing_line(self, line_coords):
        '''
        accepts the location of the user's fishing line (a Coordinate object). 
        Marks the cell as containing the line.
        '''        

        #somehow I'm supposed to get something like this
        line_cell = self.grid[users_coords.row][users_coords.col]


        self.contains_line = True


    def check_fish_caught(self):
        '''
        If the cell containing the fishing line also contains a fish, returns the fish. 
        Otherwise, return False.

        '''

        if str(self.grid) == "F*":
            print("The fish was caught!")

        else:
            print("The fish was not caught!")

    def display(self):
        '''
        to see the grid and check to see if everything is working


        # header
        #for i in range(len(self.grid[0])): # to get numbers of columns
            #print('{:3d}'.format(i), end='') #prints the top 0 and 1
        print("  0   1")
        # grid
        print('-'*8)
        for i, row in enumerate(self.grid):

            print('0|'.format(i), end='') #prints the 0 and 1 on the lefrt

            for cell in row: 
                print('{:2s}|'.format(str(cell)), end="")

            print()
            print('-'*8)

        #return "0    1 \n -------- \n" for i, row in enumerate(self.grid)       
            '''
class GameStats:
    hour = 0
    fish = CarpetSea.fish_caught
    fish = 0
    def __init__(self):
        self.time = time

    def __str__(self):
        average = CarpetSea.fish_caught / GameStats.hour
        return "Total amount of hours played: %d \nTotal amound of fish caught: %d\n On aveage you caught %.2f fish her hour"%(self.hour, CarpetSea.fish_caught, average)        

    def total_time_passed(self):
        '''
        calcuate the total time played in the game 
        '''
        print("One hour has passed...")
        self.time = time.sleep(1)
        GameStats.hour += 1

    def Total_num_of_fish():
        '''
        seeing the total number of fish caught
        '''
        if str(CarpetSea.grid) == "F*":
            GameStats.fish += 1 

    def Average_amount_of_fish(self):
        '''
        average amount of fish caught in the time played
        '''
        self.average_fish = self.fish / self.hour


def main():

    '''

    '''
    print("Welcome to Dilbert's Carpet Fishing Game!")
    print("To play, you will cast your fishing line into a location in Carpet Sea")
    print("After a certain amount of time, you will reel in your line adn find out if you caught a fish!")
    print("You can keep re-casting and re-reeling until you want to quit")

    print("\n")

    #user_row = str(input("Please enter a row: "))
    #user_col = str(input("Please enter a column: "))
    user_row = 2
    user_col = 2
    line_coords = Coordinate(user_row, user_col)

    while True:

        print(line_coords)
        Coordinate(2,2)
        info = CarpetSea(2)
        game = GameStats()

        info.randomly_place_fish()
        info.drop_fishing_line(line_coords)
        #print(info)
        game.total_time_passed()
        info.check_fish_caught()

        info.display()

        answer = str(input("Please enter 'y' to continue or 'n' to end: "))

        if answer == "n":
            break


    gameinfo = GameStats()
    print(gameinfo)


main()

最佳答案

要显示网格,您可以在 main()

中执行
for y in range(2): 
    for x in range(2): 
       print( info.grid[y][x].fish )
       print( info.grid[y][x].contains_line )

或者如果您在 Cell 中创建正确的 __str__

for y in range(2): 
    for x in range(2): 
       print( info.grid[y][x] )

或节省 - 没有 range()

for row in info.grid: 
    for cell in row: 
       print( cell )

您还可以在 CarpetSea 中创建函数 - 然后您使用 self 而不是 info

def display(self):

    for row in self.grid: 
        for cell in row: 
           print( cell )

Cell 中的__str__ 需要if/elif/else 才能正确显示值

def __str__(self):
    '''
    '''

    if self.fish: # the same as: if self.fish == ''
        if self.contains_line: # the same as: if self.contains_line == True"
            result = 'F*'
        else:
            result = 'F'
    else:
        if self.contains_line:
            result = '*'
        else:
            result = ' '

    return result

编辑:现在代码看起来像这样(但它仍然需要工作)

import random

class Coordinate:
    '''
    '''
    def __init__(self, row, col):
        ''' 

        '''
        self.row = row 
        self.col = col

    def __str__(self):
        '''

        '''
        return "(%d, %d)" %(self.row, self.col)

class Cell:
    '''

    '''

    def __init__(self, row, col):
        '''

        '''
        self.coords = Coordinate(row, col)
        self.fish = ""
        self.contains_line = False

    def __str__(self):
        '''
        '''

        if self.fish:
            if self.contains_line:
                result = 'F*'
            else:
                result = 'F'
        else:
            if self.contains_line:
                result = '*'
            else:
                result = ' '

        return result


class CarpetSea:
    '''

    '''
    num_of_fish = 0 
    total_time = 0 

    def __init__(self, N):
        '''

        '''
        self.N = N
        self.grid = []
        for i in range(self.N):
            row = []
            for j in range(self.N):
                cell = Cell(i, j)
                row.append(cell)
            self.grid.append(row)


        self.available_fish = ["Salmon", "Marlin", "Tuna", "Halibut"]


    def __str__(self):
        '''
        returns a string representation of a CarpetSea, i.e. display the organized contents of each cell. 
        Rows and columns should be labeled with indices.

        Example (see "Example Run" in the PA8 specs for more):
          0  1  
        --------
        0|M |  |
        --------
        1|  |* |
        --------

        Note: call Cell's __str__() to get a string representation of each Cell in grid
        i.e. "M " for Cell at (0,0) in the example above
        '''
        return " 0  1  \n -------- \n 0| %s  | %s  | \n -------- \n 1| %s  | %s  | \n -------- "%(self.grid[x,y].fish for x in range(self.N) for y in range(self.N))


    def randomly_place_fish(self):
        '''
        randomly selects coordinates of a cell and randomly selects a fish from the available_fish list attribute. 
        Marks the cell as containing the fish.
        '''

        cell = random.choice(random.choice(self.grid))
        cell.fish = random.choice(self.available_fish)

    def drop_fishing_line(self, users_coords):
        '''
        accepts the location of the user's fishing line (a Coordinate object). 
        Marks the cell as containing the line.
        '''

        #this sould put the two numbers in a list
        users_coords = users_coords.split(" ")

        x = users_coords[0]
        y = users_coords[1]

        x,y = [], []
        for l in self.grid:
            x.append(self.grid[0])
            y.append(self.grid[1])

    def check_fish_caught(self):
        '''
        If the cell containing the fishing line also contains a fish, returns the fish. 
        Otherwise, return False.


        if Cell.fish in #appended value of users_coords
            return True
        else:
            return False
         pass

        '''

    def display(self):
        '''
        to see the grid and check to see if everything is working
        '''

        # header

        for idx in range(len(self.grid[0])): # to get numbers of columns
            print('{:3d}'.format(idx), end='')
        print()

        # grid

        print('-'*8)

        for idx, row in enumerate(self.grid):

            print('{}|'.format(idx), end='')

            for cell in row: 
                print('{:2s}|'.format(str(cell)), end="")

            print()
            print('-'*8)

class GameStats:
    def __init__(self, ):
        pass

    def __str__(self):
        pass        


def main():

    '''

    '''
    #user_coords = input("Please enter the coordnate that you wihsh to place your line: ")
    users_coords = ("0 0")

    print(users_coords)

    Coordinate(2,2)
    info = CarpetSea(2)
    info.randomly_place_fish()
    info.randomly_place_fish()
    info.randomly_place_fish()
    info.drop_fishing_line(users_coords)
    info.check_fish_caught()

    info.display()

main()

关于python - 如何查看网格和单元格 Python 中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41110406/

相关文章:

python - 为什么加法和乘法比比较快?

python - 过滤通用外键

Python - 可选列表值 - 更Pythonic的方式?

c++ - 从队列中显示二维数组后程序崩溃

python - 在ipython qtconsole中控制LaTeX表达式颜色

python - 查找最不常出现的模糊字符串

android - 我们可以检查列表中是否存在重复的图像吗?

c# - 为相同类型的一对(循环列表)在轮播列表中查找不同类型的邻居

java - 创建 "new object"和 "Class objectname"之间的区别

java - 如何从数组中打印出对象?