Welcome, guest | Sign In | My Account | Store | Cart

This was my first file that was larger than 100 lines, and ended up being 500. I'm new at coding and would like some feedback as to how i can improve, and what you like. I also made the computer unbeatable, unless i messed up somewhere in my code and never noticed it.

Python, 497 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
print "Welcome to TicTacToe (v.3)"
print "In this version I added a computer"

xwins = 0
owins = 0
tiewins = 0

def xturn():                        #player x's move
    global pc
    global n
    global z
    if z == 0:
        ocheck()
    if n == 9:
        
        global a
        global b
        global c
        global d
        global e
        global f
        global g
        global h
        global i

        x = input ("Player X, type the number you want to place an X: ")
        print "X = ",x

        if x == 1:
            xtest(a)
            a = "X"
        elif x == 2:
            xtest(b)
            b = "X"
        elif x == 3:
            xtest(c)
            c = "X"
        elif x == 4:
            xtest(d)
            d = "X"
        elif x == 5:
            xtest(e)
            e = "X"
        elif x == 6:
            xtest(f)
            f = "X"
        elif x == 7:
            xtest(g)
            g = "X"
        elif x == 8:
            xtest(h)
            h = "X"
        elif x == 9:
            xtest(i)
            i = "X"
        else:
            print "That is not a valid entry, please enter an interger between 1-9"
            xturn()
            
        if pc == 2:
            print
            print a,"|",b,"|",c
            print "---------"
            print d,"|",e,"|",f
            print "---------"
            print g,"|",h,"|",i
            print
            z = 0
            oturn()
        elif pc == 1:
            z = 0
            ocomputer()

def oturn():                                                # player o's move
    global n
    global z
    if z == 0:
        xcheck()
    if n == 9:

        global a
        global b
        global c
        global d
        global e
        global f
        global g
        global h
        global i

        o =  input ("Player O, type the number you want to place an O: ")
        print "O = ",o

        if o == 1:
            otest(a)
            a = "O"
        elif o == 2:
            otest(b)
            b = "O"
        elif o == 3:
            otest(c)
            c = "O"
        elif o == 4:
            otest(d)
            d = "O"
        elif o == 5:
            otest(e)
            e = "O"
        elif o == 6:
            otest(f)
            f = "O"
        elif o == 7:
            otest(g)
            g = "O"
        elif o == 8:
            otest(h)
            h = "O"
        elif o == 9:
            otest(i)
            i = "O"
        else:
            print "That is not a valid entry, please enter an interger between 1-9"
            oturn()
        print
        print
        print a,"|",b,"|",c
        print "---------"
        print d,"|",e,"|",f
        print "---------"
        print g,"|",h,"|",i
        print
        z = 0
        xturn()

def xcheck():                                                   #checks to see if last move made x win                               
    global z
    global pc
    if   a == "X" and b == "X" and c == "X":
        xwin()
    elif b == "X" and e == "X" and h == "X":
        xwin()
    elif d == "X" and e == "X" and f == "X":
        xwin()
    elif a == "X" and d == "X" and g == "X":
        xwin()
    elif g == "X" and h == "X" and i == "X":
        xwin()
    elif c == "X" and f == "X" and i == "X":
        xwin()
    elif a == "X" and e == "X" and i == "X":
        xwin()
    elif c == "X" and e == "X" and g == "X":
        xwin()
    elif a != 1 and b != 2 and c != 3 and d != 4 and e != 5 and f != 6 and g != 7 and h != 8 and i != 9:
        tie()
    else:
        z = 1
        if pc == 2:
            oturn()
        elif pc == 1:
            ocomputer()

def ocheck():                                       #checks to see if last move made o win 
    global z
    if   a == "O" and b == "O" and c == "O":
        owin()
    elif b == "O" and e == "O" and h == "O":
        owin()
    elif d == "O" and e == "O" and f == "O":
        owin()
    elif a == "O" and d == "O" and g == "O":
        owin()
    elif g == "O" and h == "O" and i == "O":
        owin()
    elif c == "O" and f == "O" and i == "O":
        owin()
    elif a == "O" and e == "O" and i == "O":
        owin()
    elif c == "O" and e == "O" and g == "O":
        owin()
    elif a != 1 and b != 2 and c != 3 and d != 4 and e != 5 and f != 6 and g != 7 and h != 8 and i != 9:
        tie()
    else:
        z = 1
        xturn()

def otest(num):                                         #checks to see if spot is taken for o's turn
    if num == "X" or num == "O":
        print "This spot has been taken, enter a different spot"
        oturn()

def xtest(num):                                          #check to see if spot is taken for x's turn
    if num == "X" or num == "O":
        print "This spot has been taken, enter a different spot"
        xturn()

def owin():             #executes if o won (from xheck)
    global pc
    global owins
    print "Congratulations O, you have won!"
    owins = owins + 1
    if pc == 2:
        newgame()
    elif pc == 1:
        print
        print a,"|",b,"|",c
        print "---------"
        print d,"|",e,"|",f
        print "---------"
        print g,"|",h,"|",i
        print
        newgame()
        
def xwin():                                         #executes if x won (from ocheck)
    global n
    global xwins
    if n == 9:
        print "Congratulations X, you have won!"
        xwins = xwins + 1
        if pc == 2:
            newgame()
        elif pc == 1:
            print
            print a,"|",b,"|",c
            print "---------"
            print d,"|",e,"|",f
            print "---------"
            print g,"|",h,"|",i
            print
            newgame()

def newgame():                                  #asks is player wants to play another game
    global xwins
    global owins
    global tiewins
    global n
    if n == 9:
        print "X has won",xwins,"times, O has won",owins,"times, and there has been",tiewins,"ties."
        t = raw_input("Do you want to play again? 'y' yes 'n' no: ")
        if t == "y":
            first()
        elif t == "n":
            n = 0
            end()
        else:
            print "That is not a valid entry"
            newgame()
    
def ocomputer():                                    #ocomputer's choice
    global pc
    global n
    global z
    global a
    global b
    global c
    global d
    global e
    global f
    global g
    global h
    global i
    global x

    if z == 0:
        xcheck()
    if n == 9:
        
        if e == 5:                                  #goes to center if spot open
            e = "O"
            
        elif a == 1 and b == "O" and c == "O":          #checks for open spot for immediate win
            a = "O"
        elif a == 1 and d == "O" and g == "O":
            a = "O"
        elif a == 1 and e == "O" and i == "O":
            a = "O"
        elif b == 2 and e == "O" and h == "O":
            b = "O"
        elif b == 2 and a == "O" and c == "O":
            b = "O"
        elif c == 3 and b == "O" and a == "O":
            c = "O"
        elif c == 3 and f == "O" and i == "O":
            c = "O"
        elif c == 3 and e == "O" and g == "O":
            c = "O"
        elif d == 4 and e == "O" and f == "O":
            d = "O"
        elif d == 4 and a == "O" and g == "O":
            d = "O"
        elif f == 6 and c == "O" and i == "O":
            f = "O"
        elif f == 6 and e == "O" and d == "O":
            f = "O"
        elif g == 7 and d == "O" and a == "O":
            g = "O"
        elif g == 7 and e == "O" and c == "O":
            g = "O"
        elif g == 7 and h == "O" and i == "O":
            g = "O"
        elif h == 8 and e == "O" and b == "O":
            h = "O"
        elif h == 8 and i == "O" and g == "O":
            h = "O"
        elif i == 9 and h == "O" and g == "O":
            i = "O"
        elif i == 9 and e == "O" and a == "O":
            i = "O"
        elif i == 9 and f == "O" and c == "O":
            i = "O"

        elif a == 1 and b == "X" and c == "X":                  # checks for immediate loss
            a = "O"
        elif a == 1 and d == "X" and g == "X":
            a = "O"
        elif a == 1 and e == "X" and i == "X":
            a = "O"
        elif b == 2 and e == "X" and h == "X":
            b = "O"
        elif b == 2 and a == "X" and c == "X":
            b = "O"
        elif c == 3 and b == "X" and a == "X":
            c = "O"
        elif c == 3 and f == "X" and i == "X":
            c = "O"
        elif c == 3 and e == "X" and g == "X":
            c = "O"
        elif d == 4 and e == "X" and f == "X":
            d = "O"
        elif d == 4 and a == "X" and g == "X":
            d = "O"
        elif f == 6 and c == "X" and i == "X":
            f = "O"
        elif f == 6 and e == "X" and d == "X":
            f = "O"
        elif g == 7 and d == "X" and a == "X":
            g = "O"
        elif g == 7 and e == "X" and c == "X":
            g = "O"
        elif g == 7 and h == "X" and i == "X":
            g = "O"
        elif h == 8 and e == "X" and b == "X":
            h = "O"
        elif h == 8 and i == "X" and g == "X":
            h = "O"
        elif i == 9 and h == "X" and g == "X":
            i = "O"
        elif i == 9 and e == "X" and a == "X":
            i = "O"
        elif i == 9 and f == "X" and c == "X":
            i = "O"
        elif e == 5 and a == "X" and i == "X":
            e = "O"
        elif e == 5 and b == "X" and h == "X":
            e = "O"
        elif e == 5 and c == "X" and g == "X":
            e = "O"
        elif e == 5 and f == "X" and d == "X":
            e = "O"

        elif a == "X" and f == "X" and c == 3:
            c = "O"
        elif a == "X" and h == "X" and g == 7:
            g = "O"
        elif a == "X" and i == "X" and b == 2:
            b = "O"
        elif b == "X" and f == "X" and c == 3:
            c = "O"
        elif b == "X" and h == "X" and f == 6:
            f = "O"
        elif b == "X" and d == "X" and a == 1:
            a = "O"
        elif b == "X" and g == "X" and a == 1:
            a = "O"
        elif c == "X" and d == "X" and a == 1:
            a = "O"
        elif c == "X" and g == "X" and b == 2:
            b = "O"
        elif c == "X" and h == "X" and i == 9:
            i = "O"
        elif d == "X" and f == "X" and b == 2:
            b = "O"
        elif d == "X" and i == "X" and g == 7:
            a = "O"
        elif d == "X" and h == "X" and g == 7:
            g = "O"
        elif f == "X" and g == "X" and i == 9:
            i = "O"
        elif f == "X" and h == "X" and i == 9:
            i = "O"

        elif c == 3:
            c = "O"
        elif a == 1:
            a = "O"
        elif g == 7:
            g = "O"
        elif i == 9:
            i = "O"
        elif b == 2:
            b = "O"
        elif d == 4:
            d = "O"
        elif f == 6:
            f = "O"
        elif h == 8:
            h = "O"

        print
        print a,"|",b,"|",c
        print "---------"
        print d,"|",e,"|",f
        print "---------"
        print g,"|",h,"|",i
        print
    
        z = 0
        xturn()

def tie():                                          #executes if tie game(from x/o check)
    global tiewins
    print "Tie game! You are both losers."
    tiewins = tiewins + 1
    newgame()

def end():                                          #executes if player wants to quit(from newgame)
    global n
    n = 0
    print "Good Bye"
    
def first():                #check to see if end game loops back to here
    global z
    global t
    global w
    global pc
    global a
    global b
    global c
    global d
    global e
    global f
    global g
    global h
    global i
    global x
    global o
    global t
    global n

    a = 1
    b = 2
    c = 3
    d = 4
    e = 5
    f = 6
    g = 7
    h = 8
    i = 9
    x = 0
    o = 0
    z = 1
    
    t = 0
    if n != 0:
        pc = input ("Do you want to play a '1' player or '2' player game? ")

        if pc == 1:
            print
            print a,"|",b,"|",c
            print "---------"
            print d,"|",e,"|",f
            print "---------"
            print g,"|",h,"|",i
            print
            n = 9
            xturn()

        if pc == 2:
            n = 9
            w = raw_input ("Who shall go first, 'x' player or 'o' player: ")
            print
            print a,"|",b,"|",c
            print "---------"
            print d,"|",e,"|",f
            print "---------"
            print g,"|",h,"|",i
            print
            if w == "o":
                oturn()
            elif w == "x":
                xturn()
            else:
                print "That is not a valid entry"
                first()

n = 9
first()

I know few commands in python, and that has resulted in a larger code. There is also a bug where when you attempt to quit after you played a couple games, the program will continue.

3 comments

Greg Jorgensen 18 years, 6 months ago  # | flag

Needs more sophisticated data structures. So many similar if...elif... constructs are a sign that you need better data structures. In this case an array to hold the game, instead of 9 globals, would make the code a lot shorter. You have some recursion going on when xturn calls xtest, which then may call xturn again (same for oturn and otest). If the board was represented in a nine-element array your code would get a lot simpler. You should return a result from functions rather than making the functions call the calling function again.

Here's a tic-tac-toe game I developed for a programming class I organized for kids and teens. It shows typical Python data structures and functions. This program follows these rules to choose a square: (1) Win the game if possible; (2) Block opponent if necessary; (3) If playing offense, take a lever square if possible; If playing defense and opponent has an open lever square, make two-in-a-row to force opponent to block into a non-lever square; (4) Take the center; (5) Take a corner; (6)Take a side. A lever square is where two winning lines intersect. Given any two squares, draw lines through them to indicate all winning positions that include those squares. Eliminate lines that go through both squares. Eliminate lines that have an opponent's piece on them. If any intersections are left, those are levers. For any two squares you hold, if you can also occupy one of the levers for those squares you have made two two-in-a-row combinations, so you can win on the next turn.

This code could condensed quite a bit, but it was developed during the course of the class and is verbose in places to illustrate programming concepts.

# tic tac toe - revised version
#
# by Greg Jorgensen with help from Josh Singer

from random import shuffle

# wins contains all possible winning combinations,
# excluding reflections and rotations
allwins = [(1,2,3), (1,4,7), (1,5,9), (2,5,8), (3,5,7), (3,6,9), (4,5,6), (7,8,9)]

# board values
E = '.'
X = 'X'
O = 'O'

# fresh board, note position 0 not used
newgame = [E, E,E,E, E,E,E, E,E,E]

# opponent for each player
opponent = {X:O, O:X}


# helper functions

def display(game):
    ''' print the game '''
    print "%s %s %s\n%s %s %s\n%s %s %s" % tuple(game[1:])

def askHuman(game):
    ''' prompt human player to pick a square, return when they pick an empty square '''
    while 1:
        s = raw_input('\nyour move (1-9)? ')
        try:
            p = int(s.strip())
            if p < 1 or p > 9:
                print 'between 1 and 9'
            elif game[p] == E:
                return p
            else:
                print 'pick an empty square'
        except:
            print 'numbers only'

(comment continued...)

Greg Jorgensen 18 years, 6 months ago  # | flag

(...continued from previous comment)

def possibleWins(wins, player, square):
    ''' return all wins for player that don't include square '''
    w = []
    for a in wins[player]:
        if square not in a:
            w.append(a)

    return w

def winner(game, wins, player):
    ''' return true if player won the game '''
    for p,q,r in wins[player]:
        line = (game[p], game[q], game[r])
        if line == (player, player, player):
            return 1

    return 0

def findWins(game, wins, player):
    ''' find all winning squares for player, list of winning squares or [] if none '''
    squares = []
    for p,q,r in wins[player]:
        line = (game[p], game[q], game[r])
        if line == (player,player,E):
            squares.append(r)
        elif line == (player,E,player):
            squares.append(q)
        elif line == (E,player,player):
            squares.append(p)

    return squares

def findTwos(game, wins, player):
    ''' find all two-in-a-row combinations with a possible win for player '''
    twos = []
    for p,q,r in wins[player]:
        line = (game[p], game[q], game[r])
        if line == (player,E,E):
            twos.append((q,r))
        elif line == (E, player, E):
            twos.append((p,r))
        elif line == (E, E, player):
            twos.append((p,q))

    return twos

def findLevers(game, wins, player):
    ''' find all lever squares for player
    1) find all two-in-a-rows with possible wins
    2) find squares that occur in two or more two-in-a-row combinations '''
    levers = []
    counts = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
    twos = findTwos(game, wins, player)
    for t in twos:
        counts[t[0]] += 1
        counts[t[1]] += 1

    for i in counts:
        if counts[i] > 1:
            levers.append(i)

    return levers

def pickSquare(game, wins, player):
    ''' pick the best square for player '''
    # 1: can player win?
    a = findWins(game, wins, player)
    if a:
        return a[0]

    # 2: does player have to block?
    a = findWins(game, wins, opponent[player])
    if a:
        return a[0]

(comment continued...)

Greg Jorgensen 18 years, 6 months ago  # | flag

(...continued from previous comment)

    # 3: grab or block levers
    if player == X:
        # OFFENSE: can player get a lever square?
        a = findLevers(game, wins, player)
        if a:
            return a[0]
    elif player == O:
        # DEFENSE: prevent opponent getting a lever square,
        # try to make two in a row
        a = findTwos(game, wins, player)
        b = findLevers(game, wins, opponent[player])
        for p,q in a:
            if p not in b:
                return q
            elif q not in b:
                return p

    # 4: take an empty corner, center, side
    a = [1,3,7,9]
    shuffle(a)
    b = [2,4,6,8]
    shuffle(b)
    a = [5] + a + b
    for p in a:
        if game[p] == E:
            return p

    # should never get here
    return 0


# main - play until bored

while 1:
    # init new game
    game = newgame[:]
    wins = {X: allwins[:], O: allwins[:]}

    while 1:
        s = raw_input('do you want to play X or O? ')
        s = s.strip().upper()
        if s == X or s == O:
            break

    human = s
    computer = opponent[human]
    player = X

    print 'square numbers:'
    print '1 2 3\n4 5 6\n7 8 9'
    print

    while 1:
        if player == human:
            display(game)
            p = askHuman(game)
        else:
            p = pickSquare(game, wins, computer)
            print 'computer picks %d\n' % (p)

        game[p] = player
        wins[opponent[player]] = possibleWins(wins, opponent[player], p)

        if winner(game, wins, human):
            print '\nYou Win!\n'
            break
        elif winner(game, wins, computer):
            print '\nComputer Wins\n'
            break
        elif wins[human] == [] and wins[computer] == []:
            print '\nTie Game\n'
            break

        player = opponent[player]

    print '------'
    display(game)
    print '------'

    s = raw_input('\nPlay again (yes or no)? ')
    s = s.strip().upper()
    if s[0] != 'Y':
        break

Greg Jorgensen

PDXperts LLC

Created by acestorage001 on Sun, 25 Sep 2005 (PSF)
Python recipes (4591)
acestorage001's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks