So I made a little game that prints everything to the console which consists of some functions, a couple of lists and two extra text files with stats. The standalone game works fine, however, when I stick all the functions in a class and then call the class (so it works with the layout I made using Kivy), the error "name "getValue" is not defined" comes up.
I am confused because putting the functions into a class were the only change I have made. What did I miss?
I know that this would be very vague and unclear without the full code so here it is:
original working file
import time
import random
import os
import operator
import tkinter
import sys
homeIp = "1.1.1.1"
ipNum = homeIp
workingDir = "home/"
found = []
ports = {"ssh":[True,22],"sql":[True,1433],"http":[True,80],"ftp":[True,21]}
admin = True
def load(text,delay):
print(text, end="")
for x in range(0,delay-1):
time.sleep(0.5)
print(".", end="")
print(".")
def createIpList():
global found
for x in range(0,random.randint(1,3)):
found.append(str(random.randint(0,255))+"."+str(random.randint(0,255))+"."+str(random.randint(0,255))+"."+str(random.randint(0,255)))
def connect(ip):
global ipNum
load("trying to connect",8)
if ip in found:
print("connected to "+ip)
ipNum = ip
setPorts()
createIpList()
admin = False
else:
print("ip not found")
def scan():
load("scanning for devices",6)
for x in found:
print(x)
def setPorts():
ports["ssh"][0] = [random.choice([True,False])]
ports["sql"][0] = [random.choice([True,False])]
ports["http"][0] = [random.choice([True,False])]
ports["ftp"][0] = [random.choice([True,False])]
def probe():
print("SSH\t"+str(ports["ssh"][1])+"\t"+str(ports["ssh"][0]).strip("[").strip("]")+"\n"+
"SQL\t"+str(ports["sql"][1])+"\t"+str(ports["sql"][0]).strip("[").strip("]")+"\n"+
"HTTP\t"+str(ports["http"][1])+"\t"+str(ports["http"][0]).strip("[").strip("]")+"\n"+
"FTP\t"+str(ports["ftp"][1])+"\t"+str(ports["ftp"][0]).strip("[").strip("]")+"\n"+
"ALL PORTS MUST BE FALSE TO PORTHACK")
def shutDown():
load("Shutting down ",4)
quit()
def clearScreen():
os.system('cls')
def giveHelp():
print("COMMANDS :")
for key in commands0:
print(key)
for key in commands1:
print(key+" [ ]")
def openPort(portName,portNum):
if portNum == ports[portName][1]:
load("opening port "+str(portNum),10)
ports[portName][0] = False
print("port "+str(portNum)+" opened")
else:
print("Wrong port number")
def portHack():
shut = False
for port in ports:
if str(ports[port][0])== "[True]":
shut = True
if shut == True:
print("Can not operate port hack - all ports must be open")
else:
admin = True
print("You are now system admin")
def inbox():
file = open("emails.txt","r")
for line in file:
if line.strip()=="###EMAIL"+str(int(getValue("email")))+"###":
ended = False
for line in file:
if line.strip()=="###EMAIL"+str(int(getValue("email"))+1)+"###":
ended = True
if ended == False:
print(line)
file.close()
def editValue(var,val):
originalLines = []
file = open("saveData.txt","r")
for line in file:
if len(line)>1:
originalLines.append(line)
file.close()
for x in range(0,len(originalLines)):
if originalLines[x].split("=")[0].strip()==var:
newVal = (float(originalLines[x].split("=")[1].strip())+val)
originalLines[x] = var+"="+str(newVal)
file = open("saveData.txt","w")
for item in originalLines:
file.write(item+"\n")
file.close
def reply():
load("SENDING",3)
def getValue(var):
file = open("saveData.txt","r")
for line in file:
if line.split("=")[0].strip() == var:
return float(line.split("=")[1].strip())
file.close()
def sysSpecs():
print("CPU\t\t"+str(getValue("cpu"))+"GHz\n"+
"RAM\t\t"+str(getValue("ram"))+"GB\n"+
"PSU\t\t"+str(getValue("psu"))+"W\n"+
"STORAGE\t\t"+str(getValue("storage"))+"GB")
if getValue("gpu") == 0:
print("GPU\t\tNONE")
else:
print("GPU\t\t"+str(getValue("gpu"))+"GHz")
def market():
category = input("WELCOME TO AMAZING\n\nCategories\n->CPU\n->RAM\n->storage\n->PSU\n->GPU\n\n[Press ENTER to leave]\n")
measurement={"CPU":"GHz","RAM":"GB","storage":"GB","PSU":"W","GPU":"GHz"}
sortedParts = (sorted(parts[category].items(), key=operator.itemgetter(1)))
print("ITEM\t\t\t|"+measurement[category]+"\t|PRICE\n==================================")
for item in sortedParts:
if len(item[0])>=8:
print(item[0]+"\t\t|"+str(item[1][0])+"\t|"+str(item[1][1]))
else:
print(item[0]+"\t\t\t|"+str(item[1][0])+"\t|"+str(item[1][1]))
def buy(item):
exist = False
itemCat = ""
for category in parts:
for part in parts[category]:
if part == item:
exist = True
itemCat = category
if exist == False:
print("ITEM NOT IN STOCK")
else:
if parts[itemCat][item][1] <= getValue("money"):
print("PURCHASED")
editValue(itemCat.lower(),float(parts[itemCat][item][0])-getValue(itemCat.lower()))
else:
print("INSUFFICIENT BALANCE")
def balance():
print(getValue("money"))
def eventCheck(command):
if int(getValue("email")) == 0:
inbox()
editValue("email",1)
inbox()
if command[0] == "reply":
if int(getValue("email")) == 1:
editValue("email",1)
inbox()
print("$100 recieved")
editValue("money",100)
elif int(getValue("email")) == 3:
if ipNum != homeIp:
if admin == True:
print("CONGRATS")
if int(getValue("email")) == 2:
if getValue("cpu")>=1.5:
editValue("email",1)
def main():
command = input(ipNum+":"+workingDir+">").split(' ')
try:
if len(command) == 1:
commands0[command[0]]()
elif len(command) == 2:
if command[0] == "sshCrack":
commands1[command[0]]("ssh",int(command[1]))
elif command[0] == "sqlInjection":
commands1[command[0]]("sql",int(command[1]))
elif command[0] == "webServerWorm":
commands1[command[0]]("http",int(command[1]))
elif command[0] == "ftpSpoof":
commands1[command[0]]("ftp",int(command[1]))
else:
commands1[command[0]](command[1])
except:
print("",end="")
eventCheck(command)
parts = {"CPU":{"LEG_1":[1.5,100],"LEG_2":[2,200],"AMP_Mk3":[2.5,300],"Inzel_Pontium":[3,500],"Inzel_Eye7":[3.5,700],"AMP_String_Cutter":[4,999]},
"RAM":{"InsaneX_2":[2,40],"Revenger_4":[4,60],"InsaneX_8":[8,100],"Korsair_16":[16,160],"Z.SKILL_FORK":[32,400]},
"storage":{"Sumsing_10":[10,20],"Queenston_50":[50,50],"EastDigital_100":[100,75],"SinDisk_250":[250,120],"CrazyX_500":[500,200],"Sumsing_TB":[1000,499]},
"PSU":{"Korsair_Feather":[200,50],"Korsair_Beefy":[500,130],"Korsair_Ultra":[800,200]},
"GPU":{"ZTX_1050":[2,100],"ZTX_1060":[4,200],"ZTX_1070":[8,400],"ZTX_1080":[16,800]}}
commands0 = {"scan":scan,"probe":probe,"shutdown":shutDown,"cls":clearScreen,"help":giveHelp,"portHack":portHack,"inbox":inbox,
"reply":reply,"market":market,"sysSpecs":sysSpecs,"balance":balance}
commands1 = {"connect":connect,"sshCrack":openPort,"sqlInjection":openPort,"webServerWorm":openPort,"ftpSpoof":openPort,"buy":buy}
setPorts()
createIpList()
eventCheck([""])
while True:
main()
file where the only change is that all functions are put into a class which is then called:
from kivy.app import App
from kivy.clock import Clock
from kivy.core.text import LabelBase
from kivy.core.window import Window
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.uix.widget import Widget
import time
import random
import os
import operator
import sys
homeIp = "1.1.1.1"
ipNum = homeIp
workingDir = "home/"
found = []
ports = {"ssh":[True,22],"sql":[True,1433],"http":[True,80],"ftp":[True,21]}
admin = True
class MainWindow(BoxLayout):
def load(text,delay):
print(text, end="")
for x in range(0,delay-1):
time.sleep(0.5)
print(".", end="")
print(".")
def createIpList():
global found
for x in range(0,random.randint(1,3)):
found.append(str(random.randint(0,255))+"."+str(random.randint(0,255))+"."+str(random.randint(0,255))+"."+str(random.randint(0,255)))
def connect(ip):
global ipNum
load("trying to connect",8)
if ip in found:
print("connected to "+ip)
ipNum = ip
setPorts()
createIpList()
admin = False
else:
print("ip not found")
def scan():
load("scanning for devices",6)
for x in found:
print(x)
def setPorts():
ports["ssh"][0] = [random.choice([True,False])]
ports["sql"][0] = [random.choice([True,False])]
ports["http"][0] = [random.choice([True,False])]
ports["ftp"][0] = [random.choice([True,False])]
def probe():
print("SSH\t"+str(ports["ssh"][1])+"\t"+str(ports["ssh"][0]).strip("[").strip("]")+"\n"+
"SQL\t"+str(ports["sql"][1])+"\t"+str(ports["sql"][0]).strip("[").strip("]")+"\n"+
"HTTP\t"+str(ports["http"][1])+"\t"+str(ports["http"][0]).strip("[").strip("]")+"\n"+
"FTP\t"+str(ports["ftp"][1])+"\t"+str(ports["ftp"][0]).strip("[").strip("]")+"\n"+
"ALL PORTS MUST BE FALSE TO PORTHACK")
def shutDown():
load("Shutting down ",4)
quit()
def clearScreen():
os.system('cls')
def giveHelp():
print("COMMANDS :")
for key in commands0:
print(key)
for key in commands1:
print(key+" [ ]")
def openPort(portName,portNum):
if portNum == ports[portName][1]:
load("opening port "+str(portNum),10)
ports[portName][0] = False
print("port "+str(portNum)+" opened")
else:
print("Wrong port number")
def portHack():
shut = False
for port in ports:
if str(ports[port][0])== "[True]":
shut = True
if shut == True:
print("Can not operate port hack - all ports must be open")
else:
admin = True
print("You are now system admin")
def inbox():
file = open("emails.txt","r")
for line in file:
if line.strip()=="###EMAIL"+str(int(getValue("email")))+"###":
ended = False
for line in file:
if line.strip()=="###EMAIL"+str(int(getValue("email"))+1)+"###":
ended = True
if ended == False:
print(line)
file.close()
def editValue(var,val):
originalLines = []
file = open("saveData.txt","r")
for line in file:
if len(line)>1:
originalLines.append(line)
file.close()
for x in range(0,len(originalLines)):
if originalLines[x].split("=")[0].strip()==var:
newVal = (float(originalLines[x].split("=")[1].strip())+val)
originalLines[x] = var+"="+str(newVal)
file = open("saveData.txt","w")
for item in originalLines:
file.write(item+"\n")
file.close
def reply():
load("SENDING",3)
def getValue(var):
file = open("saveData.txt","r")
for line in file:
if line.split("=")[0].strip() == var:
return float(line.split("=")[1].strip())
file.close()
def sysSpecs():
print("CPU\t\t"+str(getValue("cpu"))+"GHz\n"+
"RAM\t\t"+str(getValue("ram"))+"GB\n"+
"PSU\t\t"+str(getValue("psu"))+"W\n"+
"STORAGE\t\t"+str(getValue("storage"))+"GB")
if getValue("gpu") == 0:
print("GPU\t\tNONE")
else:
print("GPU\t\t"+str(getValue("gpu"))+"GHz")
def market():
category = input("WELCOME TO AMAZING\n\nCategories\n->CPU\n->RAM\n->storage\n->PSU\n->GPU\n\n[Press ENTER to leave]\n")
measurement={"CPU":"GHz","RAM":"GB","storage":"GB","PSU":"W","GPU":"GHz"}
sortedParts = (sorted(parts[category].items(), key=operator.itemgetter(1)))
print("ITEM\t\t\t|"+measurement[category]+"\t|PRICE\n==================================")
for item in sortedParts:
if len(item[0])>=8:
print(item[0]+"\t\t|"+str(item[1][0])+"\t|"+str(item[1][1]))
else:
print(item[0]+"\t\t\t|"+str(item[1][0])+"\t|"+str(item[1][1]))
def buy(item):
exist = False
itemCat = ""
for category in parts:
for part in parts[category]:
if part == item:
exist = True
itemCat = category
if exist == False:
print("ITEM NOT IN STOCK")
else:
if parts[itemCat][item][1] <= getValue("money"):
print("PURCHASED")
editValue(itemCat.lower(),float(parts[itemCat][item][0])-getValue(itemCat.lower()))
else:
print("INSUFFICIENT BALANCE")
def balance():
print(getValue("money"))
def getValue(var):
file = open("saveData.txt","r")
for line in file:
if line.split("=")[0].strip() == var:
return float(line.split("=")[1].strip())
file.close()
def eventCheck(command):
if int(getValue("email")) == 0:
inbox()
editValue("email",1)
inbox()
if command[0] == "reply":
if int(getValue("email")) == 1:
editValue("email",1)
inbox()
print("$100 recieved")
editValue("money",100)
elif int(getValue("email")) == 3:
if ipNum != homeIp:
if admin == True:
print("CONGRATS")
if int(getValue("email")) == 2:
if getValue("cpu")>=1.5:
editValue("email",1)
def main():
command = input(ipNum+":"+workingDir+">").split(' ')
try:
if len(command) == 1:
commands0[command[0]]()
elif len(command) == 2:
if command[0] == "sshCrack":
commands1[command[0]]("ssh",int(command[1]))
elif command[0] == "sqlInjection":
commands1[command[0]]("sql",int(command[1]))
elif command[0] == "webServerWorm":
commands1[command[0]]("http",int(command[1]))
elif command[0] == "ftpSpoof":
commands1[command[0]]("ftp",int(command[1]))
else:
commands1[command[0]](command[1])
except:
print("",end="")
eventCheck(command)
parts = {"CPU":{"LEG_1":[1.5,100],"LEG_2":[2,200],"AMP_Mk3":[2.5,300],"Inzel_Pontium":[3,500],"Inzel_Eye7":[3.5,700],"AMP_String_Cutter":[4,999]},
"RAM":{"InsaneX_2":[2,40],"Revenger_4":[4,60],"InsaneX_8":[8,100],"Korsair_16":[16,160],"Z.SKILL_FORK":[32,400]},
"storage":{"Sumsing_10":[10,20],"Queenston_50":[50,50],"EastDigital_100":[100,75],"SinDisk_250":[250,120],"CrazyX_500":[500,200],"Sumsing_TB":[1000,499]},
"PSU":{"Korsair_Feather":[200,50],"Korsair_Beefy":[500,130],"Korsair_Ultra":[800,200]},
"GPU":{"ZTX_1050":[2,100],"ZTX_1060":[4,200],"ZTX_1070":[8,400],"ZTX_1080":[16,800]}}
commands0 = {"scan":scan,"probe":probe,"shutdown":shutDown,"cls":clearScreen,"help":giveHelp,"portHack":portHack,"inbox":inbox,
"reply":reply,"market":market,"sysSpecs":sysSpecs,"balance":balance}
commands1 = {"connect":connect,"sshCrack":openPort,"sqlInjection":openPort,"webServerWorm":openPort,"ftpSpoof":openPort,"buy":buy}
setPorts()
createIpList()
eventCheck([""])
class MainApp(App):
def build(self):
Window.clearcolor = (1,1,1,1)
return MainWindow()
if __name__ == '__main__':
MainApp().run()
Just so you know, the whole point of putting it in a class is so I can use the layout I created using the kv design language in a different piece of code. If it is necessary, I can post my .kv file that is opened by the program.
Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.
When I try to run my program in IDLE (the text editor i'm using at the moment, notepad ++ said indentation error and I don't know why) it only does the code in __init__, which shows it's been created into an object. But the line after that I tried to use the main method and it doesn't do anything. I also changed it to a different method but that didn't work either. Here's my program:
import sys
class Main:
def __init__(self):
WinX = False
WinO = False
Turn = 'X'
LastTurn = 'X'
a, b, c, d, e, f, g, h, i = ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
PosList = []
PosList.append(a)
PosList.append(b)
PosList.append(c)
PosList.append(d)
PosList.append(e)
PosList.append(f)
PosList.append(g)
PosList.append(h)
PosList.append(i)
self.board = '+---+---+---+\n| ' + PosList[0] +' | '+ PosList[1] +' | '+ PosList[2] +' |\n+---+---+---+\n| '+ PosList[3] +' | '+ PosList[4] +' | '+ PosList[5] +' |\n+---+---+---+\n| '+ PosList[6] +' | '+ PosList[7] +' | '+ PosList[8] +' |\n+---+---+---+'
print self.board
def UpdateTurn(self):
if LastTurn == 'X':
Turn == 'O'
elif LastTurn == 'O':
Turn == 'X'
LastTurn = Turn
def WinChecker(self):
if a and b and c == 'X' or a and d and g == 'X' or a and e and i == 'X' or g and e and c == 'X' or g and h and i == 'X' or c and f and i == 'X':
WinX = True
if a and b and c == 'O' or a and d and g == 'O' or a and e and i == 'O' or g and e and c == 'O' or g and h and i == 'O' or c and f and i == 'O':
WinO = True
def UpdateBoard(self):
print self.board
def Starter(self):
while True:
try:
i = int(input(''))
except TypeError:
print 'Not a Number, Try Again.'
continue
i -= 1
PosList[i] = Turn
self.UpdateBoard
self.WinChecker
if Winx == True:
print 'X Wins!'
sys.exit()
elif Wino == True:
print 'O Wins!'
sys.exit()
self.UpdateTurn
s = Main()
s.Starter
I just (4 days) finished python's own tutorial.
call Starter function like
s.Starter()
And also there might be an logical error The while loop below will be always true.
def Starter(self):
while True:
try:
i = int(input(''))
except TypeError:
print 'Not a Number, Try Again.'
continue
You haven't called the method.
s.Starter()
You are not actually calling the Starter method in the last line, just referencing it. Do this instead:
s.Starter()
That calls it.
For interest, here is a rewritten version. I've used some more advanced constructs - #classmethod and #property and 'magic methods' like __str__ and __repr__. Hope you find it useful!
def getInt(prompt='', lo=None, hi=None):
"""
Get integer value from user
If lo is given, value must be >= lo
If hi is given, value must be <= hi
"""
while True:
try:
val = int(raw_input(prompt))
if lo is not None and val < lo:
print("Must be at least {}".format(lo))
elif hi is not None and val > hi:
print("Must be no more than {}".format(hi))
else:
return val
except ValueError:
print("Must be an integer!")
class TicTacToe(object):
players = ('X', 'O') # player characters
blank = ' ' # no-player character
wins = ( # lines that give a win
(0,1,2),
(3,4,5),
(6,7,8),
(0,3,6),
(1,4,7),
(2,5,8),
(0,4,8),
(2,4,6)
)
board_string = '\n'.join([ # format string
"",
"+---+---+---+",
"| {} | {} | {} |",
"+---+---+---+",
"| {} | {} | {} |",
"+---+---+---+",
"| {} | {} | {} |",
"+---+---+---+"
])
#classmethod
def ch(cls, state):
"""
Given the state of a board square (None or turn number)
return the output character (blank or corresponding player char)
"""
if state is None:
return cls.blank
else:
return cls.players[state % len(cls.players)]
def __init__(self, bd=None):
"""
Set up a game of TicTacToe
If board is specified, resume playing (assume board state is valid),
otherwise set up a new game
"""
if bd is None:
# default constructor - new game
self.turn = 0
self.board = [None for i in range(9)]
elif hasattr(bd, "board"): # this is 'duck typing'
# copy constructor
self.turn = sum(1 for sq in bd if sq is not None)
self.board = bd.board[:]
else:
# given board state, resume game
self.turn = sum(1 for sq in bd if sq is not None)
self.board = list(bd)
#property
def board_chars(self):
"""
Return the output characters corresponding to the current board state
"""
getch = type(self).ch
return [getch(sq) for sq in self.board]
#property
def winner(self):
"""
If the game has been won, return winner char, else None
"""
bd = self.board_chars
cls = type(self)
for win in cls.wins:
c0, c1, c2 = (bd[sq] for sq in win)
if c0 != cls.blank and c0 == c1 and c0 == c2:
return c0
return None
def __str__(self):
"""
Return a string representation of the board state
"""
cls = type(self)
return cls.board_string.format(*self.board_chars)
def __repr__(self):
"""
Return a string representation of the object
"""
cls = type(self)
return "{}({})".format(cls.__name__, self.board)
def do_move(self):
"""
Get next player's move
"""
cls = type(self)
next_player = cls.ch(self.turn)
while True:
pos = getInt("Player {} next move? ".format(next_player), 1, 9) - 1
if self.board[pos] is None:
self.board[pos] = self.turn
self.turn += 1
break
else:
print("That square is already taken")
def play(self):
print("Welcome to Tic Tac Toe. Board squares are numbered 1-9 left-to-right, top-to-bottom.")
while True:
print(self) # show the board - calls self.__str__
w = self.winner
if w is None:
self.do_move()
else:
print("{} is the winner!".format(w))
break
def main():
TicTacToe().play()
if __name__=="__main__":
main()