Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- X = "X"
- O = "O"
- EMPTY = " "
- TIE = "TIE"
- human = X
- computer = O
- grid = 9
- position = 0
- def display_instructions():
- print("The tic tac toe you will be playing on will\n",
- "be a 3 by 3 grid and will look like this\n",
- " 0 | 1 | 2\n",
- " ---------\n",
- " 3 | 4 | 5\n",
- " ---------\n",
- " 6 | 7 | 8\n",
- "You will start off by going first as X's\n",
- "use 0-8 to position where you would like to go")
- def display_board(board):
- print(board[0], "|", board[1], "|", board[2])
- print("---------")
- print(board[3], "|", board[4], "|", board[5])
- print("---------")
- print(board[6], "|", board[7], "|", board[8])
- def new_board():
- board = []
- for position in range(grid):
- board.append(EMPTY)
- return board
- def winner(board):
- winner = "none"
- while winner != X or O:
- if board[0] == board[1] == board[2] != EMPTY:
- winner = board[0]
- return winner
- elif board[3] == board[4] == board[5] != EMPTY:
- winner = board[3]
- return winner
- elif board[5] == board[6] == board[7] != EMPTY:
- winner = board[5]
- return winner
- elif board[0] == board[3] == board[6] != EMPTY:
- winner = board[0]
- return winner
- elif board[1] == board[4] == board[7] != EMPTY:
- winner = board[1]
- return winner
- elif board[2] == board[5] == board[8] != EMPTY:
- winner = board[2]
- return winner
- elif board[0] == board[4] == board[8] != EMPTY:
- winner = board[0]
- return winner
- elif board[2] == board[4] == board[6] != EMPTY:
- winner = board[2]
- return winner
- elif EMPTY not in board:
- return TIE
- return None
- def next_turn(turn):
- if turn == X:
- return 0
- else:
- return X
- def human_move(board):
- print("Where will you move?(0-8): ")
- move=int(input())
- turn = X
- while turn == X:
- if move in range(grid) and board[move] == EMPTY:
- board[move] = X
- turn = next_turn(turn)
- else:
- print("Move not valid, please choose an empty space using 0-8")
- move=int(input())
- return move
- def computer_move(board):
- turn = O
- move = random.randint(0,8)
- while turn == O:
- if move in range(grid) and board[move] == EMPTY:
- board[move] = O
- turn = next_turn(turn)
- else:
- move = random.randint(0,8)
- return move
- def legal_move(board):
- move = []
- if board[move] in range(grid):
- if board[move]== EMPTY:
- move.append(position)
- return move
- def main():
- display_instructions()
- board = new_board()
- while not winner(board):
- human_move(board)
- computer_move(board)
- display_board(board)
- the_winner = winner(board)
- if the_winner == human:
- print("A winner is you!")
- if the_winner == computer:
- print("You Fail it! \n"
- "Your skill is not enough \n"
- "see you next time \n"
- "bye-bye!\n")
- import os
- os.system('pause')
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement