我正在尝试编写程序"战列舰"。我有两个游戏板矩阵:一个用于玩家,一个用于计算机。这些是在main
之外定义的,因为我希望它们是全局变量,因为有几个函数操作/读取它们。我使用的是Python 2.6.1。
#create player game board (10x10 matrix filled with zeros)
playerBoard = [[0]*10 for i in range(10)]
#create computer game board (10x10 matrix filled with zeros)
computerBoard = [[0]*10 for i in range(10)]
然后我定义了主要功能。
#define main function
def main():
global playerBoard
global computerBoard
#keepGoing is true
keepGoing = True
#while keepGoing is true
while keepGoing:
#call main menu function. Set to response.
response = mainMenu()
#if response is 1
if response == "1":
#begin new game
#call clearBoards function
clearBoards()
#call resetCounters function
resetCounters()
#call placeShips function (player)
playerBoard = placeShips(playerBoard, "player")
#call placeShips function (computer)
computerBoard = placeShips(computerBoard, "computer")
#call guessCycler function
guessCycler()
#if response is 2
if response == "2":
#keepGoing is false
keepGoing = False
尽管我在main
中声明了global playerboard
和global computerBoard
,PyScripter仍然说它们是局部变量。我不明白。我如何确保它们是全球性的?
我已经看过的文件:
在创建全局变量的函数之外的函数中使用全局变量
更改函数中的全局变量
http://www.python-course.eu/global_vs_local_variables.php
我绝对认为你应该重新考虑是否需要它们是全局的-你不需要。-)
廉价的方法是声明你的东西,并将它们作为参数传递给函数
def MyFunc(board1):
print board1
board1 = "Very weak horse"
MyFunc(board1)
真正的方法是创建一个类,然后使用自身访问它们
class MySuperClass():
def __init__(self):
self.horse = "No way up"
def myRealCoolFunc(self):
print self.horse
uhhh = MySuperClass()
uhhh.myRealCoolFunc()