Why is this code running twice? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am writing a Neural Net program to play connect four in python, and training it using existing minimax algorithms. I have written some basic code to establish communication between two algorithms. Following lines should result in one game between the two programs :-
game = ConnectFour()
game.start_new()
However, the game is played twice. ("IA is the winner" is printed twice.)
I added some debug print lines. There's a lot of code, but I cannot figure out the point where the problem is. So I am posting all of it. I suspect import statements, but do not know what is the problem exactly.
ConnectFourAIb.py:
from minimax2b import ConnectFour
def get_AI_move(grid):
i = 0
while grid[0][i]!=' ':
i += 1
return i
game = ConnectFour()
game.start_new()
minimax2b.py:
import os
import random
import time
from abc import ABCMeta, abstractmethod
CONNECT_FOUR_GRID_WIDTH = 7
CONNECT_FOUR_GRID_HEIGHT = 6
CONNECT_FOUR_COLORS = ["x","o"]
class ConnectFour(object):
_GRID_WIDTH = CONNECT_FOUR_GRID_WIDTH
_GRID_HEIGHT = CONNECT_FOUR_GRID_HEIGHT
_grid = None
_round = None
_finished = False
_winner = None
_current_player = None
_players = [None, None]
_COLORS = CONNECT_FOUR_COLORS
def __init__(self):
print("__init__")
self._round = 1
self._finished = False
self._winner = None
self._players[0] = _HumanPlayer(self._COLORS[0])
self._players[1] = _ComputerPlayer(self._COLORS[1])
for i in xrange(2):
print('%s play with %s ' % (self._players[i]._type, self._COLORS[i]))
self._current_player = self._players[random.randint(0, 1)]
self._grid = []
for i in xrange(self._GRID_HEIGHT):
self._grid.append([])
for j in xrange(self._GRID_WIDTH):
self._grid[i].append(' ')
def start(self):
print("start")
while not self._finished:
self._next_move()
def start_new(self):
print("start_new")
self._round = 1
self._finished = False
self._winner = None
self._current_player = self._players[random.randint(0, 1)]
self._grid = []
for i in xrange(self._GRID_HEIGHT):
self._grid.append([])
for j in xrange(self._GRID_WIDTH):
self._grid[i].append(' ')
self.start()
def _switch_player(self):
print("_switch_player")
if self._current_player == self._players[0]:
self._current_player = self._players[1]
else:
self._current_player = self._players[0]
def _next_move(self):
print("_next_move")
column = self._current_player.get_move(self._grid)
for i in xrange(self._GRID_HEIGHT - 1, -1, -1):
if self._grid[i][column] == ' ':
self._grid[i][column] = self._current_player._color
self._check_status()
if self._finished:
self._print_state()
return 1
self._switch_player()
self._round += 1
return 1
print("This column is full. Please choose an other column")
return
def _check_status(self):
print("_check_status")
if self._is_full():
self._finished = True
elif self._is_connect_four():
self._finished = True
self._winner = self._current_player
def _is_full(self):
print("_is_full")
return self._round > self._GRID_WIDTH * self._GRID_HEIGHT
def _is_connect_four(self):
print("_is_connect_four")
for i in xrange(self._GRID_HEIGHT - 1, -1, -1):
for j in xrange(self._GRID_WIDTH):
if self._grid[i][j] != ' ':
# check for vertical connect four
if self._find_vertical_four(i, j):
return True
return False
def _find_vertical_four(self, row, col):
print("_find_vertical_four")
consecutive_count = 0
if row + 3 < self._GRID_HEIGHT:
for i in xrange(4):
if self._grid[row][col] == self._grid[row + i][col]:
consecutive_count += 1
else:
break
if consecutive_count == 4:
if self._players[0]._color == self._grid[row][col]:
self._winner = self._players[0]
else:
self._winner = self._players[1]
return True
return False
def _print_state(self):
print("_print_state")
if self._finished:
print("Game Over!")
if self._winner != None:
print(str(self._winner._type) + " is the winner!")
else:
print("Game is a draw")
class _Player(object):
__metaclass__ = ABCMeta
_type = None
_color = None
def __init__(self, color):
self._color = color
#abstractmethod
def get_move(self, grid):
pass
class _HumanPlayer(_Player):
def __init__(self, color):
super(_HumanPlayer, self).__init__(color)
self._type = "Human"
def get_move(self, grid):
from ConnectFourAIb import get_AI_move
return get_AI_move(grid)
class _ComputerPlayer(_Player):
_DIFFICULTY = 5
def __init__(self, color,_DIFFICULTY=5):
super(_ComputerPlayer, self).__init__(color)
self._DIFFICULTY = _DIFFICULTY
self._type = "IA"
def get_move(self, grid):
return 4

There's still too much code to go all the way through, but at least one thing is suspicious. You start the game with a module-level call to ConnectFour in ConnectFourAIb.py. But your _HumanPlayer.get_move method imports ConnectFourAIb again; this will re-trigger the two lines at the end of that file.
To fix this, use the if __name__ == '__main__' trick:
if __name__ == '__main__':
game = ConnectFour()
game.start_new()
This ensures that those lines are only called when the file is run from the command line, not when it is imported.
(As an aside, please drop all those leading underscores. They don't add anything and just make your code harder to read.)

Related

python OOP functions into classes/method

I am coding a huffman coding tree in python, I have used one class for tree nodes, but I want the whole program to be object oriented. I just cant seem to be able to turn my functions into classes and run the whole thing as OOP. Is it possible to convert functions into classes/methods or does it involve rewriting the entire code in OOP style. The code works ok, im just trying to get my head around OOP and how to implement it. Any help would be great! Code below.
'''
import heapq
class TreeNode(object):
def __init__(self, freq, char=None, left=None, right=None):
self.char = char
self.freq = freq
self.left = left
self.right = right
def __lt__(self, other):
return self.freq < other.freq
def isLeaf(self):
return (self.left == None and self.right == None)
def createTree(freqData):
huffmanNodes = []
for char in freqData:
huffmanNodes.append(TreeNode(freqData[char], char))
heapq.heapify(huffmanNodes)
while (len(huffmanNodes) > 1):
# obtain the two minimum-frequency Huffman nodes
child1 = heapq.heappop(huffmanNodes)
child2 = heapq.heappop(huffmanNodes)
parent = TreeNode(child1.freq + child2.freq, left=child1, right=child2)
heapq.heappush(huffmanNodes, parent)
return None if huffmanNodes == [] else heapq.heappop(huffmanNodes)
def hTreeToHCode(hTree):
code = dict()
def getCode(hNode, curCode=""):
if (hNode == None): return
if (hNode.left == None and hNode.right == None):
code[hNode.char] = curCode
getCode(hNode.left, curCode + "0")
getCode(hNode.right, curCode + "1")
if hNode.char == None:
print("")
else:
print('Character = {} : Freq = {} --- Encoded into {}'.format(hNode.char, hNode.freq, curCode))
getCode(hTree)
return code
def encode(s, freqData):
hTree = createTree(freqData)
hCode = hTreeToHCode(hTree)
hEncoded = ""
for char in s:
hEncoded += hCode[char]
return hEncoded.strip()
def decode(s, freqData):
hTree = createTree(freqData)
decodedStr = ""
curTreeNode = hTree
for charCode in s:
if (charCode == "0"):
curTreeNode = curTreeNode.left
else:
curTreeNode = curTreeNode.right
if (curTreeNode.isLeaf()):
decodedStr += curTreeNode.char
curTreeNode = hTree
return decodedStr
words = "hello welcome to my huffman algorithm code"
charlst = {}
for char in words:
charlst[char] = charlst.get(char,0) + 1
freqData = charlst
encodedStr = encode(words, freqData)
print("encodedStr", encodedStr)
decodedStr = decode(encodedStr, freqData)
print("decodedStr", decodedStr)
'''
you can put function outside the NodeTree class in a Main class and add a run method with var initialisation etc and put at the end of your program a
if __name__=='__main__':
Main.run()

Why inputbox is cleaning when i write something?

I have a curses program on python and i have this fragment of class. I am running def control_chat(self, sel_chat) from another class. When messages (self.messages is list like ["message", id_of_msg]) are updating, inputbox's window cleans itself. But i clear all screen by entering emptu lines, not touching last 3 lines (in this last 3 lines my input box).
def input_validator(self, key):
if key == 10 or self.new_msg:
return 7
else:
return key
def get_msg(self):
while self.chatting:
win = curses.newwin(2, self.cols, self.lines-2, 0)
inp = curses.textpad.Textbox(win)
text = inp.edit(validate=self.input_validator)
if text != "":
self.vk.send_message(self.peer_id, text)
def chat_clear(self):
lines = self.lines - 3
for y in range(lines):
self.wprint(self.empity_line, y=y, x=0)
def control_chat(self, sel_chat):
self.sel_chat = sel_chat
self.peer_id = self.vk.id_to_peer_id(self.sel_chat)
self.input_thread = Thread(target=self.get_msg)
self.input_thread.start()
while self.chatting:
self.messages = self.vk.list_chat(self.peer_id)
self.draw_chat()
def draw_chat(self):
self.chat_clear()
self.top_bar_draw()
for message in self.messages:
name_line = str(message[1])
self.stdscr.attron(color_pair(1))
self.stdscr.addstr(name_line)
self.stdscr.attroff(color_pair(1))
self.stdscr.addstr(": "+message[0]+"\n")
self.wprint(self.screen_line, y=self.lines-3, x=0)
self.messages = []
# time.sleep()
def wprint(self, str, y=-1, x=-1):
if (y == -1) and (x == -1):
self.stdscr.addstr(str+"\n")
else:
self.stdscr.addstr(y, x, str+"\n")
self.stdscr.refresh()

Utalization of classes in python

I'm trying to teach myself about OOP in python and am really struggling.
I have the following:
def __init__(self, quantity):
''' '''
self.switchboard = []
self.state = False
self.quantity = quantity
for i in range(quantity):
self.switchboard.append(i)
def __str__(self):
self.on_list = []
for i in range(self.quantity):
if i == True:
self.on_list.append(i)
return("The following switches are on " + str(self.on_list))
def which_switch(self):
for i in range(len(self.switchboard)):
self.on_list = []
if self.switchboard[i] == True:
on_list.append(i)
print(on_list)
def flip(self, n):
if self.switchboard[n] == True:
self.switchboard[n] = False
else:
self.switchboard[n] = True
When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.
In __str__ modify the line:
if i == True:
to:
if self.switchboard[i]:
Remember: i is just an index, what you want is to access the i-th item in switchboard!
There is also another bug, in method which_switch():
on_list.append(i)
should be:
self.on_list.append(i)
and same goes to the print line below it.
Output after the change:
The following switches are on [1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, I can only guess that what you actually wanted to do in the constructor is:
def __init__(self, quantity):
''' '''
self.switchboard = []
self.state = False
self.quantity = quantity
for i in range(quantity):
self.switchboard.append(LightSwitch('off')) # create light-switch and set it to 'off'
and then, when you print them - print only the ones that are on:
def __str__(self):
self.on_list = []
for i in range(self.quantity):
if self.switchboard[i].state: # check state
self.on_list.append(i)
return("The following switches are on " + str(self.on_list))
Also the reason it's printing 1 as true, is because out of all the elements in list, it's just seeing everything as false and 1 as true (as in 0 == False, 1 == True).
You can shorten
def flip(self):
''' Sets switch to opposite position.'''
if self.state == True:
self.state = False
elif self.state == False:
self.state = True
to
def flip(self):
''' Sets switch to opposite position.'''
self.state = not self.state
and on your switchboard for
def flip_every(self, n):
for i in range(0, len(self.switchboard), n):
if self.switchboard[n] == True:
self.switchboard[n] = False
else:
self.switchboard[n] = True
to
def flip_every(self, n):
for i in range(0, self.quantity, n):
self.switchboard[n] = not self.switchboard[n]
# you could also just use self.flip(n) instead
and
def flip(self, n):
self.switchboard[n] = not self.switchboard[n]
As a nice touch: you use kind-of the same iteration in which_switch(self) and __str__(self): that operates on the indexes of switches that are on. I built a small def getOnIndexes(self): ... that returns you an int list of those indexes, and call this in both methods (DRY - dont repeat yourself principle) using a shorthand to create indexes based on a list comprehension.
def getOnIndexes(self):
return [i for i in range(self.quantity) if self.switchboard[i] == True]
In total a really nice small OOP example.
What had me stumped though, is why a Switchboard IS_A LightSwitch - I would model it slightly different, saying a SwitchBoard HAS LightSwitch'es, coming to this:
Your base class
class LightSwitch():
def __init__(self, default_state):
'''
default_state can only be 'on' or 'off'.
'''
if default_state == 'on':
self.state = True
elif default_state == 'off':
self.state = False
def turn_on(self):
self.state = True
def turn_off(self):
self.state = False
def flip(self):
self.state = not self.state
def __str__(self):
if self.state == True:
return 'I am on'
if self.state == False:
return 'I am off'
def isOn(self):
return self.state
def isOff(self):
return not self.isOn()
My alternative switch board:
class AlternateSwitchBoard():
''' '''
def __init__(self, quantity, default_state):
''' '''
self.default_state = default_state
self.switchboard = [LightSwitch(default_state) for x in range(quantity)]
self.state = False
self.quantity = quantity
def __str__(self):
retVal = ""
for i in range(self.quantity):
if self.switchboard[i].isOn():
retVal += ", On"
else:
retVal += ", Off"
return "Switchboard: " + retVal[1:].strip()
def which_switch(self):
print(self.getOnIndexes())
def flip(self, n):
self.switchboard[n].flip()
def flip_every(self,stride):
for i in range(0, self.quantity, stride):
self.switchboard[i].flip()
def reset(self):
self.switchboard = [LightSwitch(default_state) for x in range(quantity)]
def getOnIndexes(self):
return [i for i in range(self.quantity) if self.switchboard[i].isOn()]
s2 = AlternateSwitchBoard(10, "off")
s2.flip(2)
s2.flip(7)
print(str(s2))
s2.flip_every(2)
print(str(s2))
s2.which_switch()
Output:
Switchboard: Off, Off, On, Off, Off, Off, Off, On, Off, Off
Switchboard: On, Off, Off, Off, On, Off, On, On, On, Off
[0, 4, 6, 7, 8]

Python - Classes - Self Not Defined

Below I'm attempting to make a simple Keygen as a first project. Somewhere I'm getting the error the Self has not been defined.
I'm guessing it's probably something easy
import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def KeyGen4(self):
while self.counter != self.length:
a = random.choice(self.Letters)
print a #test
r = (random.randint(0,1))
print r #test
if r == True:
a = a.upper()
else:
pass
self.key.append(a)
self.counter += 1
s = ''
self.key = s.join(key)
print self.key
return self.key
def start(self):
selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >')
if selection == 'K' or 'k':
length = 4
keyGen4(self)
elif selection == 'N' or 'n':
KeyGenN(self)
elif selection == 'C' or 'c':
length = int(raw_input("Key Length: "))
#KeyGen4(self) # Change later after creating method with more options
start(self)
Your indention is wrong, but I assume this is only a copy-pasting issue.
That start(self) at the bottom doesn't make sense,
and indeed self is not defined there. You should create an instance of the class, and then call its start method:
KeyGenerator().start()
# or
key_gen = KeyGenerator()
key_gen.start()
You have two problems:
you miss indentation on every class-function
you must create an object of the class before you can call any of its functions
Your class should look like this
import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b','c','d','e']
def KeyGen4(self):
while self.counter != self.length:
a = random.choice(self.Letters)
print a #test
r = (random.randint(0,1))
print r #test
if r == True:
a = a.upper()
else:
pass
self.key.append(a)
self.counter += 1
s = ''
self.key = s.join(key)
print self.key
return self.key
def start(self):
selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >')
if selection == 'K' or 'k':
length = 4
self.keyGen4()
elif selection == 'N' or 'n':
self.KeyGenN()
elif selection == 'C' or 'c':
length = int(raw_input("Key Length: "))
#KeyGen4(self) # Change later after creating method with more options
#now make an instance of your class
my_key_gen = KeyGenerator()
my_key_gen.start()
Please note that when calling class functions inside the class, you need to use self.FUNCNAME. All class functions should take "self" as argument. If that is their only argument then you simply call them with self.func(). If they take arguments you still ommit the self, as self.func(arg1, arg2)

Calling a method from the same class

I'm writing a class for a simple game of 4 in a row, but I'm running into a problem calling a method in the same class. Here's the whole class for the sake of completeness:
class Grid:
grid = None
# creates a new empty 10 x 10 grid
def reset():
Grid.grid = [[0] * 10 for i in range(10)]
# places an X or O
def place(player,x,y):
Grid.grid[x][y] = player
# returns the element in the grid
def getAt(x,y):
return Grid.grid[x][y]
# checks for wins in a certain direction
def checkLine(player,v,count,x,y):
x = x+v[0]
y = y+v[1]
if x < 0 or x > 9:
return
if y < 0 or y > 9:
return
if Grid.grid[x][y] == p:
count = count+1
if count == 4:
return True
checkLine(player,v,count,x,y)
return False
# returns the number of the player that won
def check():
i = 'i'
for x in range(0,10):
for y in range(0,10):
if Grid.grid[x][y] > 0:
p = Grid.grid[x][y]
f = checkLine(p,0,array(i,[1,0]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[0,1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[1,1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[-1,0]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[0,-1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[-1,-1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[1,-1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[-1,1]),x,y)
if f:
return p
return 0
reset = staticmethod(reset)
place = staticmethod(place)
getAt = staticmethod(getAt)
check = staticmethod(check)
checkLine = staticmethod(checkLine)
I'm trying to call checkLine() from check(), but I get the error "NameError: global name 'checkLine' is not defined". When I call Grid.checkLine() instead, I get "TypeError: 'module' object is not callable"
How do I call checkLine()?
EDIT:
#beer_monk
class Grid(object):
grid = None
# creates a new empty 10 x 10 grid
def reset(self):
Grid.grid = [[0] * 10 for i in range(10)]
# places an X or O
def place(self,player,x,y):
Grid.grid[x][y] = player
# returns the element in the grid
def getAt(self,x,y):
return Grid.grid[x][y]
# checks for wins in a certain direction
def checkLine(self,player,v,count,x,y):
x = x+v[0]
y = y+v[1]
if x < 0 or x > 9:
return
if y < 0 or y > 9:
return
if Grid.grid[x][y] == p:
count = count+1
if count == 4:
return True
checkLine(self,player,v,count,x,y)
return False
# returns the number of the player that won
def check(self):
i = 'i'
for x in range(0,10):
for y in range(0,10):
if Grid.grid[x][y] > 0:
p = Grid.grid[x][y]
for vx in range(-1,2):
for vy in range(-1,2):
f = self.checkLine(p,0,array(i,[vx,vy]),x,y)
if f:
return p
return 0
reset = staticmethod(reset)
place = staticmethod(place)
getAt = staticmethod(getAt)
check = staticmethod(check)
checkLine = staticmethod(checkLine)
Get rid of the class. Use plain functions and module level variable for grid.
The class is not helping you in any way.
PS. If you really want to call checkline from within the class, you'd call Grid.checkline. For example:
class Foo:
#staticmethod
def test():
print('Hi')
#staticmethod
def test2():
Foo.test()
Foo.test2()
prints
Hi
Syntax:
class_Name.function_Name(self)
Example:
Turn.checkHoriz(self)
A reworked example (hopefully showing a better use of classes!)
import itertools
try:
rng = xrange # Python 2.x
except NameError:
rng = range # Python 3.x
class Turn(object):
def __init__(self, players):
self.players = itertools.cycle(players)
self.next()
def __call__(self):
return self.now
def next(self):
self.now = self.players.next()
class Grid(object):
EMPTY = ' '
WIDTH = 10
HEIGHT = 10
WINLENGTH = 4
def __init__(self, debug=False):
self.debug = debug
self.grid = [Grid.EMPTY*Grid.WIDTH for i in rng(Grid.HEIGHT)]
self.player = Turn(['X','O'])
def set(self, x, y):
if self.grid[y][x]==Grid.EMPTY:
t = self.grid[y]
self.grid[y] = t[:x] + self.player() + t[x+1:]
self.player.next()
else:
raise ValueError('({0},{1}) is already taken'.format(x,y))
def get(self, x, y):
return self.grid[y][x]
def __str__(self):
corner = '+'
hor = '='
ver = '|'
res = [corner + hor*Grid.WIDTH + corner]
for row in self.grid[::-1]:
res.append(ver + row + ver)
res.append(corner + hor*Grid.WIDTH + corner)
return '\n'.join(res)
def _check(self, s):
if self.debug: print("Check '{0}'".format(s))
# Exercise left to you!
# See if a winning string exists in s
# If so, return winning player char; else False
return False
def _checkVert(self):
if self.debug: print("Check verticals")
for x in rng(Grid.WIDTH):
winner = self._check([self.get(x,y) for y in rng(Grid.HEIGHT)])
if winner:
return winner
return False
def _checkHoriz(self):
if self.debug: print("Check horizontals")
for y in rng(Grid.HEIGHT):
winner = self._check([self.get(x,y) for x in rng(Grid.WIDTH)])
if winner:
return winner
return False
def _checkUpdiag(self):
if self.debug: print("Check up-diagonals")
for y in rng(Grid.HEIGHT-Grid.WINLENGTH+1):
winner = self._check([self.get(d,y+d) for d in rng(min(Grid.HEIGHT-y, Grid.WIDTH))])
if winner:
return winner
for x in rng(1, Grid.WIDTH-Grid.WINLENGTH+1):
winner = self._check([self.get(x+d,d) for d in rng(min(Grid.WIDTH-x, Grid.HEIGHT))])
if winner:
return winner
return False
def _checkDowndiag(self):
if self.debug: print("Check down-diagonals")
for y in rng(Grid.WINLENGTH-1, Grid.HEIGHT):
winner = self._check([self.get(d,y-d) for d in rng(min(y+1, Grid.WIDTH))])
if winner:
return winner
for x in rng(1, Grid.WIDTH-Grid.WINLENGTH+1):
winner = self._check([self.get(x+d,d) for d in rng(min(Grid.WIDTH-x, Grid.HEIGHT))])
if winner:
return winner
return False
def isWin(self):
"Return winning player or False"
return self._checkVert() or self._checkHoriz() or self._checkUpdiag() or self._checkDowndiag()
def test():
g = Grid()
for o in rng(Grid.WIDTH-1):
g.set(0,o)
g.set(Grid.WIDTH-1-o,0)
g.set(Grid.WIDTH-1,Grid.HEIGHT-1-o)
g.set(o,Grid.HEIGHT-1)
print(g)
return g
g = test()
print g.isWin()
Unlike java or c++, in python all class methods must accept the class instance as the first variable. In pretty much every single python code ive seen, the object is referred to as self. For example:
def reset(self):
self.grid = [[0] * 10 for i in range(10)]
See http://docs.python.org/tutorial/classes.html
Note that in other languages, the translation is made automatically
There are multiple problems in your class definition. You have not defined array which you are using in your code. Also in the checkLine call you are sending a int, and in its definition you are trying to subscript it. Leaving those aside, I hope you realize that you are using staticmethods for all your class methods here. In that case, whenever you are caling your methods within your class, you still need to call them via your class's class object. So, within your class, when you are calling checkLine, call it is as Grid.checkLine That should resolve your NameError problem.
Also, it looks like there is some problem with your module imports. You might have imported a Module by name Grid and you have having a class called Grid here too. That Python is thinking that you are calling your imported modules Grid method,which is not callable. (I think,there is not a full-picture available here to see why the TypeError is resulting)
The best way to resolve the problem, use Classes as they are best used, namely create objects and call methods on those objects. Also use proper namespaces. And for all these you may start with some good introductory material, like Python tutorial.
Instead of operating on an object, you are actually modifying the class itself. Python lets you do that, but it's not really what classes are for. So you run into a couple problems
-You will never be able to make multiple Grids this way
the Grid can't refer back to itself and e.g. call checkLine
After your grid definition, try instantiating your grid and calling methods on it like this
aGrid = Grid()
...
aGrid.checkLine()
To do that you, you first need to modify all of the method definitions to take "self" as your first variable and in check, call self.checkLine()
def check(self):
...
self.checkLine()
...
Also, your repeated checking cries out for a FOR loop. You don't need to write out the cases.
Java programmer as well here, here is how I got it to call an internal method:
class Foo:
variable = 0
def test(self):
self.variable = 'Hi'
print(self.variable)
def test2(self):
Foo.test(self)
tmp = Foo()
tmp.test2()

Categories