|
| 1 | +"""tictactoe game for 2 players |
| 2 | +from blogpost: http://thebillington.co.uk/blog/posts/writing-a-tic-tac-toe-game-in-python by BILLY REBECCHI, |
| 3 | +slightly improved by Horst JENS""" |
| 4 | +from __future__ import print_function |
| 5 | + |
| 6 | +choices = [] |
| 7 | + |
| 8 | +for x in range (0, 9) : |
| 9 | + choices.append(str(x + 1)) |
| 10 | + |
| 11 | +playerOneTurn = True |
| 12 | +winner = False |
| 13 | + |
| 14 | +def printBoard() : |
| 15 | + print( '\n -----') |
| 16 | + print( '|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|') |
| 17 | + print( ' -----') |
| 18 | + print( '|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|') |
| 19 | + print( ' -----') |
| 20 | + print( '|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|') |
| 21 | + print( ' -----\n') |
| 22 | + |
| 23 | +while not winner : |
| 24 | + printBoard() |
| 25 | + |
| 26 | + if playerOneTurn : |
| 27 | + print( "Player 1:") |
| 28 | + else : |
| 29 | + print( "Player 2:") |
| 30 | + |
| 31 | + try: |
| 32 | + choice = int(input(">> ")) |
| 33 | + except: |
| 34 | + print("please enter a valid field") |
| 35 | + continue |
| 36 | + if choices[choice - 1] == 'X' or choices [choice-1] == 'O': |
| 37 | + print("illegal move, plase try again") |
| 38 | + continue |
| 39 | + |
| 40 | + if playerOneTurn : |
| 41 | + choices[choice - 1] = 'X' |
| 42 | + else : |
| 43 | + choices[choice - 1] = 'O' |
| 44 | + |
| 45 | + playerOneTurn = not playerOneTurn |
| 46 | + |
| 47 | + for x in range (0, 3) : |
| 48 | + y = x * 3 |
| 49 | + if (choices[y] == choices[(y + 1)] and choices[y] == choices[(y + 2)]) : |
| 50 | + winner = True |
| 51 | + printBoard() |
| 52 | + if (choices[x] == choices[(x + 3)] and choices[x] == choices[(x + 6)]) : |
| 53 | + winner = True |
| 54 | + printBoard() |
| 55 | + |
| 56 | + if((choices[0] == choices[4] and choices[0] == choices[8]) or |
| 57 | + (choices[2] == choices[4] and choices[4] == choices[6])) : |
| 58 | + winner = True |
| 59 | + printBoard() |
| 60 | + |
| 61 | +print ("Player " + str(int(playerOneTurn + 1)) + " wins!\n") |
0 commit comments