摆脱全局变量和创建函数

时间:2015-09-24 00:39:31

标签: python function console globals

import subprocess as sp

plyr_x, plyr_y = (9,5)
plyr_char = 'o'

def create_board():
    ''' Creates a 10x10 grid of cells'''
    board = []
    for _ in range(10):
        board.append(['-']*10)
    board[plyr_x][plyr_y] = plyr_char
    return board

def print_board(board):
    '''Clears the screen prints or re-print all changes'''
    tmp = sp.call('clear')
    for row in board:
        print ' '.join(row)

board = create_board()
print_board(board)

while True:
    '''Main loop'''
    choice = raw_input('What do you want to do? ')
    print_board(board)
    if choice == 'move':
        '''Moves the player. Empties the cell previously occupid,
            adds/subtracts 1 from the player location,
            and then reprints the board'''
        direction = raw_input('Which way do you want to move? ')
        if direction == 'up':
            board[plyr_x][plyr_y] = ' '
            plyr_x += -1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
        elif direction == 'down':
            board[plyr_x][plyr_y] = ' '
            plyr_x += 1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
        elif direction == 'right':
            board[plyr_x][plyr_y] = ' '
            plyr_y += 1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
        elif direction == 'left':
            board[plyr_x][plyr_y] = ' '
            plyr_y += -1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
    elif choice == 'attack':
        print 'There is no one to attack right now.'
    elif choice == 'die':
        plyr_char = '%'
        print_board(board)
        quit()

一切正常但我想摆脱顶部的全局变量,如果可能的话,并将所有的移动代码写入它自己的move()函数中,这样我就可以摆脱巨大的if if the main环。你怎么能这样做?

2 个答案:

答案 0 :(得分:0)

这应该可行。我认为可能令你困惑的概念是将事物传递给函数,因为这基本上就是我所做的一切。

import subprocess as sp



def move(plyr_x, plyr_y, board):
    '''Moves the player. Empties the cell previously occupid,
            adds/subtracts 1 from the player location,
            and then reprints the board'''
    direction = raw_input('Which way do you want to move? ')
    if direction == 'up':
            board[plyr_x][plyr_y] = ' '
            plyr_x += -1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
    elif direction == 'down':
            board[plyr_x][plyr_y] = ' '
            plyr_x += 1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
    elif direction == 'right':
            board[plyr_x][plyr_y] = ' '
            plyr_y += 1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
    elif direction == 'left':
            board[plyr_x][plyr_y] = ' '
            plyr_y += -1
            board[plyr_x][plyr_y] = 'o'
            print_board(board)
    return (plyr_x, plyr_y, board)

def create_board(plyr_x, plyr_y, plyr_char):
    ''' Creates a 10x10 grid of cells'''
    board = []
    for _ in range(10):
        board.append(['-']*10)
    board[plyr_x][plyr_y] = plyr_char
    return board

def print_board(board):
    '''Clears the screen prints or re-print all changes'''
    tmp = sp.call('clear')
    for row in board:
        print ' '.join(row)

def main():
    plyr_x, plyr_y = (9,5)
    plyr_char = 'o'
    board = create_board(plyr_x, plyr_y, plyr_char)
    print_board(board)

    while True:
        '''Main loop'''
        choice = raw_input('What do you want to do? ')
        print_board(board)
        if choice == 'move':
            plyr_x, plyr_y, board = move(plyr_x, plyr_y, board)
        elif choice == 'attack':
            print 'There is no one to attack right now.'
        elif choice == 'die':
            plyr_char = '%'
            print_board(board)
            quit()

答案 1 :(得分:0)

以下是我将如何继续:

  • 使用main功能
  • 移动全局args
  • 现在你必须将你的args传递给函数,而不是依赖于全局
  • 开始添加可包含行为和状态的类!

我只实现了一个Player()类,但我也会创建一个类。我会把那个留给你!

例如,更新玩家位置(以及他最后的已知位置)中的字符可以是Board类的方法。同样,您可以使用显示电路板的方法def print(self)。当然,create_board()函数会变成def __init__(self, player, size)

我想你会发现这段代码很容易理解:

import subprocess as sp

class Player(object):
    def __init__(self, x, y, char):
        self.x = x
        self.y = y
        self.char = char

    def move(self, direction):
        """ update our position. """
        if direction.lower() == 'left':
            self.y -= 1
        elif direction.lower() == 'right':
            self.y += 1
        elif direction.lower() == 'up':
            self.x -= 1
        elif direction.lower() == 'down':
            self.x += 1


def create_board(player):
    ''' Creates a 10x10 grid of cells'''
    board = []
    for _ in range(10):
        board.append(['-']*10)
    board[player.x][player.y] = player.char
    return board

def print_board(board):
    '''Clears the screen prints or re-print all changes'''
    tmp = sp.call('clear')
    for row in board:
        print ' '.join(row)


def main():
    player = Player(9, 5, 'o')
    board = create_board(player)
    print_board(board)

    while True:
        '''Main loop'''
        choice = raw_input('What do you want to do? ')
        print_board(board)
        if choice == 'move':
            '''Moves the player. Empties the cell previously occupid,
                adds/subtracts 1 from the player location,
                and then reprints the board'''
            direction = raw_input('Which way do you want to move? ')
            if direction in ('up', 'down', 'left', 'right'):
                board[player.x][player.y] = ' '  # Erase
                player.move(direction)
                board[player.x][player.y] = player.char
                print_board(board)
        elif choice == 'attack':
            print 'There is no one to attack right now.'
        elif choice == 'die':
            player.char = '%'
            print_board(board)
            quit()

if __name__ == '__main__':
    main()

我希望能给你一些想法!