Text Size
Text Size
Exit Full Screen
Python3 Editor
Show
Source Code
View Source Code in Full Screen
# FOR CS 110 Students: If you use this code as your base # for the Tic Tac Toe challenge, make sure you add comments # explaining how the code works. import random ttt = [ [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '] ] def print_board(): for row in range(len(ttt)): for col in range(len(ttt[row])): if col < 2: print(' ' + ttt[row][col] + ' |', end='') else: print(' ' + ttt[row][col] + ' ') if row < 2: print('-----------') def isValid(row, col): if not row.isdigit(): return False, 'Row is not a number.' if not col.isdigit(): return False, 'Column is not a number.' if not (0 <= int(row) <= 2): return False, 'Row is out of range.' if not (0 <= int(col) <= 2): return False, 'Column is out of range.' if ttt[int(row)][int(col)] != ' ': return False, 'Already Taken.' return True, None def player_input(): row = input("Enter a row number 0-2: ") col = input("Enter a column number 0-2: ") valid, reason = isValid(row, col) while not valid: print('Invalid choice:', reason) row = input("Enter a row number 0-2: ") col = input("Enter a column number 0-2: ") valid, reason = isValid(row, col) ttt[int(row)][int(col)] = 'X' def computer_turn(): row = random.randint(0, 2) col = random.randint(0, 2) while ttt[row][col] != ' ': row = random.randint(0, 2) col = random.randint(0, 2) ttt[row][col] = 'O' def checkWin(): pass turns = 0 print_board() while turns < 9: print("\nYour Turn:") player_input() turns += 1 print_board() checkWin() if turns == 9: break print("\nComputer Turn:") computer_turn() turns += 1 print_board() checkWin()
CS110_Lesson10_TicTacToe.py
( around 64 lines Python3 code )
Published By:
Mentor Sabrina
Created on
2020-12-14T18:50:58Z
Python3 Editor
- an
OYOclass
application,
own your own class today
.
Run
Result
Status:
Program is not running