SHOW:
|
|
- or go back to the newest paste.
1 | def switch_turn(turn): | |
2 | if turn == "X": | |
3 | return "O" | |
4 | else: | |
5 | return "X" | |
6 | ||
7 | def printboard(board): | |
8 | print() | |
9 | print(board[1] + " | " + board[2] + " | " +board[3]) | |
10 | print("- + - + -") | |
11 | print(board[4] + " | " + board[5] + " | " +board[6]) | |
12 | print("- + - + -") | |
13 | print(board[7] + " | " + board[8] + " | " +board[9]) | |
14 | print() | |
15 | ||
16 | def get_input(turn, board): | |
17 | while True: | |
18 | print(turn + "'s turn") | |
19 | position = input("Enter the position you want to play: ") | |
20 | ||
21 | if not position.isdigit(): # what if user enters something that is not a number? | |
22 | print("Please enter a number. ") | |
23 | elif not 1 <= int(position) <= 9: | |
24 | print("Enter a number in the valid range.") | |
25 | elif not board[int(position)].isdigit(): | |
26 | print("Position already taken, please try another position.") | |
27 | else: | |
28 | ||
29 | return int(position) | |
30 | ||
31 | def checkwin(board): | |
32 | if board[1] == board[2] == board[3]: | |
33 | return True, board[3] | |
34 | elif board[4] == board[5] == board[6]: | |
35 | return True, board[6] | |
36 | elif board[7] == board[8] == board[9]: | |
37 | return True, board[9] | |
38 | elif board[1] == board[4] == board[7]: | |
39 | return True, board[7] | |
40 | elif board[2] == board[5] == board[8]: | |
41 | return True, board[5] | |
42 | elif board[3] == board[6] == board[9]: | |
43 | return True, board[9] | |
44 | elif board[1] == board[5] == board[9]: | |
45 | return True, board[9] | |
46 | elif board[3] == board[5] == board[7]: | |
47 | return True, board[7] | |
48 | else: | |
49 | return False, None | |
50 | ||
51 | ||
52 | ||
53 | def main(): | |
54 | turn = "X" | |
55 | board = ["0", "1","2", "3","4", "5","6", "7","8", "9"] | |
56 | printboard(board) | |
57 | game_over = False | |
58 | count = 0 | |
59 | while not game_over and count < 9: | |
60 | position = get_input(turn, board) | |
61 | count += 1 | |
62 | board[position] = turn | |
63 | printboard(board) | |
64 | game_over, winner = checkwin(board) | |
65 | turn = switch_turn(turn) | |
66 | ||
67 | print(winner, "won the game") | |
68 | ||
69 | main() |