I looked a little into HTML a year ago but decided to try python yesterday and came up with this for tic-tac-toe. I have no programming experience and I haven't yet looked at other peoples versions of tic-tac-toe as I wanted to see if I could do it myself, there's definitely a lot of ways I could have been more efficient that I notice but in terms of general bad code writing habits that you might see input would be very welcome.
turn = 2
winner = 0
gamestate = 0
row1 =[]
row2 =[]
row3 =[]
rowlist =[row1,row2,row3]
gamestate = 1
#arbitraryvalues
xrow1alt = [3,6,9]
xrow2alt = [2,5,8]
xrow3alt = [1,4,7]
orow1alt = [3,6,9]
orow2alt = [2,5,8]
orow3alt = [1,4,7]
xaltrows = [xrow1alt,xrow2alt,xrow3alt]
oaltrows = [orow1alt,orow2alt,orow3alt]
def printboard():
print(*row1, sep="")
print(*row2, sep="")
print(*row3, sep="")
def drawboard():
for i in range(3):
row1.append('-')
row2.append('-')
row3.append('-')
#fix turn and consolidate inputs
def controls():
global turn
if turn == 2:
playerturn = 'x'
playernum = 1
if turn == 1:
playerturn = 'o'
playernum = 2
if playernum == 1:
rownum = int(input("player 1's turn, select row "))
columnnum = int(input("player 1's turn, select clumn "))
if playernum == 2:
rownum = int(input("player 2's turn, select row "))
columnnum = int(input("player 2's turn, select clumn "))
if rownum == 1:
row1.pop(columnnum-1)
row1.insert(columnnum-1,playerturn)
if playernum == 1:
xrow1alt.pop(columnnum-1)
xrow1alt.insert(columnnum-1,playerturn)
else:
orow1alt.pop(columnnum-1)
orow1alt.insert(columnnum-1,playerturn)
if rownum == 2:
row2.pop(columnnum-1)
row2.insert(columnnum-1,playerturn)
if playernum == 1:
xrow2alt.pop(columnnum-1)
xrow2alt.insert(columnnum-1,playerturn)
else:
orow2alt.pop(columnnum-1)
orow2alt.insert(columnnum-1,playerturn)
if rownum == 3:
row3.pop(columnnum-1)
row3.insert(columnnum-1,playerturn)
if playernum == 1:
xrow3alt.pop(columnnum-1)
xrow3alt.insert(columnnum-1,playerturn)
else:
orow3alt.pop(columnnum-1)
orow3alt.insert(columnnum-1,playerturn)
if playerturn =='x':
turn = 1
if playerturn =='o':
turn = 2
def wincheck():
global winner
xtotal = 0
ototal = 0
global gamestate
y = 0
for i in xaltrows:
xvalues = [159,150,141,147,153]
for x in range(len(i)):
if i[x] == 'x':
i[x] = 40
xtotal = sum(xrow1alt) + sum(xrow2alt) + sum(xrow3alt)
print(xtotal)
if xtotal in xvalues:
winner = 1
gamestate +=1
for i in oaltrows:
ovalues = [276,279,282,288,270]
for x in range(len(i)):
if i[x] == 'o':
i[x] = 83
ototal = sum(orow1alt) + sum(orow2alt) + sum(orow3alt)
if ototal in ovalues:
winner +=2
gamestate +=1
drawboard()
printboard()
while gamestate == 1:
controls()
printboard()
wincheck()
print("winner is player ",winner)
def
. Next: allglobal
at the beginning of function - it helps to see what external variables function will use. Next: all functions put at the beginning - beforeturn = 2
\$\endgroup\$