It's small, nothing special, but for only knowing C for a few hours, im proud
There is no AI, so either get a friend or play by yourself
Tic-Tac-Toe (18.6Kb)
Tic-Tac-Toe Source
This post has been edited by fubz: 15 March 2006 - 07:58 PM
Posted 14 March 2006 - 08:46 PM
This post has been edited by fubz: 15 March 2006 - 07:58 PM
Posted 14 March 2006 - 09:49 PM
#!/usr/bin/env python
# this is the game tic-tac-toe
# it was fully programmed by shane lindberg
# instructions.py
#
# this function gives instuctions to
# the user for playing the game
def instructions():
print """\n\tWelcome to the game of tic-tac-toe\n
\t --a game of man against machine--\n
you first need to choose to go first or second. If you
choose to go first you will be X's. If you choose to
go second you will be O's.\n
you will choose your 'move' on the board by using the
following key.
DO NOT FORGET THE ORDER OF THE NUMBERS IN THE KEY BELOW"""
instruc_list = [ '1','2','3','4','5','6','7','8','9' ]
print_board(instruc_list)
print ' '
# print_board.py
#
# this function prints the board, it takes
# its parameter in the form of a list, the
# list must have at least 9 elments
def print_board(order):
print " "
print " "
print " ",order[0], "|", order[1], "|", order[2]
print " -----------"
print " ",order[3], "|", order[4], "|", order[5]
print " -----------"
print " ",order[6], "|", order[7], "|", order[8]
# x_or_o.py
#
# this function asks the user if he or
# she wants to go first, if they choose
# to go first, they will be X's, if they
# choose to go second, they will be O's
def x_or_o():
print "\nWould you like to go first or second?\n"
answer = ""
choices = ('first', 'second')
while answer not in choices:
answer = raw_input("please enter 'first' or 'second'(enter here)")
if answer == "first":
print "\nyou chose to go first, so that will make you X's"
if answer == "second":
print "\nyou chose to go second, you must feel brave to give"
print "the computer the advantage. You will be O's"
return answer
# answer.py
#
# this function asks for a move and checks to see
# if it is a legal place to choose.
def answer():
guess = raw_input("please enter your move(enter here)")
while guess not in ('1','2','3','4','5','6','7','8','9'):
guess = raw_input("please enter a number chosen from 1-9(enter here)")
guess = int(guess)
while True:
if position[guess -1] in ('X', 'O'):
guess = raw_input("that space is already occupied, please make another move(enter here)")
guess = int(guess)
else:
break
return guess -1
# test comp_answer
def comp_answer():
raw_input("enter return to let the computer take its turn")
BEST_MOVES = ( 4,0,2,6,8,1,3,7,5 )
# the most favorable move
#
# the following for statment determines if the
# computer has a move that will win the game,
# if so it returns that value as its move
for i in WINNER:
winns = []
if i[0] in comp_moves:
winns.append(i[0])
if i[1] in comp_moves:
winns.append(i[1])
if i[2] in comp_moves:
winns.append(i[2])
if len(winns) == 2:
for k in i:
if k not in winns and k not in moves and k not in comp_moves:
return k
# the second most favorable move
#
# the following for statment determines if the
# user has two in a row and needs to be blocked
# if so the computer returns that value as its move
for i in WINNER:
winns = []
if i[0] in moves:
winns.append(i[0])
if i[1] in moves:
winns.append(i[1])
if i[2] in moves:
winns.append(i[2])
if len(winns) == 2:
for k in i:
if k not in winns and k not in moves and k not in comp_moves:
return k
# the final part of the stratagie is to choose moves
# in order of importance from the local tuple called
# best moves. This tuple starts with the middle position
# then the corners, then the 4 final sides
for i in BEST_MOVES:
if i not in moves and i not in comp_moves:
return i
# update_moves.py
#
# this function takes user input from the function answer.py
# and appends the list called position. This provides stdin
# for the print_board and the winner function
def update_moves(answer):
if who_first == 'first':
position[answer] = 'X'
else:
position[answer] = 'O'
moves.append(answer)
# comp_update_moves.py
#
# this function updates the computers
# moves. it gets stdin from comp_answer
def comp_update_moves(comp_answer):
if who_first == 'first':
position[comp_answer] = 'O'
else:
position[comp_answer] = 'X'
comp_moves.append(comp_answer)
# winner.py
# this function checks to see if anyone has one the game
# it takes its data from update_moves
def winner(moves,comp_moves):
won = ""
for i in WINNER:
if i[0] in moves and i[1] in moves and i[2] in moves:
won = 0
for i in WINNER:
if i[0] in comp_moves and i[1] in comp_moves and i[2] in comp_moves:
won = 0
return won
# congrat_winner.py
#
# this function allows you to decide who won
# so you are able to congrat the winner, or
# make fun at the loser
def congrat(moves):
WINNER = ( (0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7),
(2,5,8), (0,4,8), (2,4,6) )
won = 1
for i in WINNER:
if i[0] in moves and i[1] in moves and i[2] in moves:
won = 0
return won
# here is where the actual program starts to run
WINNER = ( (0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7),
(2,5,8), (0,4,8), (2,4,6) )
position = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
moves = []
comp_moves = []
who_first = ""
who_won = 1
instructions()
raw_input('press return to continue')
while winner(moves,comp_moves) != 0:
# if the game is a tie this break statement is used
if len(moves) + len(comp_moves) == 9:
who_won = 0
break
# these first two 'if' statements only run
# once during this while loop. their just used
# to start either 'X's or 'O's. They also take
# the first answer from the user or the computer
if who_first == "":
who_first = x_or_o()
if who_first == 'first':
print_board(position)
update_moves(answer())
next_turn = 0
else:
print_board(position)
comp_update_moves(comp_answer())
next_turn = 1
# the following if-else statment alternate the computer and
# users turns, while also collecting data and updating data
print_board(position)
if next_turn == 0:
comp_update_moves(comp_answer())
next_turn = 1
else:
update_moves(answer())
next_turn = 0
print_board(position)
if who_won == 0:
print "\nit was a tie, maybe you will win next time"
elif congrat(moves) == 0:
print "\nyou beat the computer, man is still triumphant"
else:
print "\nthe computer beat you, you let mankind down :-("
This post has been edited by shanenin: 14 March 2006 - 09:53 PM
Posted 14 March 2006 - 10:36 PM
Quote
This post has been edited by shanenin: 14 March 2006 - 10:41 PM
Posted 15 March 2006 - 12:03 AM
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
def display_instruct():
"""Display game instructions."""
print \
"""
Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a number, 0 - 8. The number
will correspond to the board position as illustrated:
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
Prepare yourself, human. The ultimate battle is about to begin. \n
"""
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(raw_input(question))
return response
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print "\nThen take the first move. You will need it."
human = X
computer = O
else:
print "\nYour bravery will be your undoing... I will go first."
computer = X
human = O
return computer, human
def new_board():
"""Create new game board."""
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
def display_board(board):
"""Display game board on screen."""
print "\n\t", board[0], "|", board[1], "|", board[2]
print "\t", "---------"
print "\t", board[3], "|", board[4], "|", board[5]
print "\t", "---------"
print "\t", board[6], "|", board[7], "|", board[8], "\n"
def legal_moves(board):
"""Create list of legal moves."""
moves = []
for square in range(NUM_SQUARES):
if board[square] == EMPTY:
moves.append(square)
return moves
def winner(board):
"""Determine the game winner."""
WAYS_TO_WIN = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
if EMPTY not in board:
return TIE
return None
def human_move(board, human):
"""Get human move."""
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
if move not in legal:
print "\nThat square is already occupied, foolish human. Choose another.\n"
print "Fine.."
return move
def computer_move(board, computer, human):
"""Make computer move."""
# make a copy to work with since function will be changing list
board = board[:]
# the best positions to have, in order
BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
print "I shall take square number",
# if computer can win, take that move
for move in legal_moves(board):
board[move] = computer
if winner(board) == computer:
print move
return move
# done checking this move, undo it
board[move] = EMPTY
# if human can win, block that move
for move in legal_moves(board):
board[move] = human
if winner(board) == human:
print move
return move
# done checkin this move, undo it
board[move] = EMPTY
# since no one can win on next move, pick best open square
for move in BEST_MOVES:
if move in legal_moves(board):
print move
return move
def next_turn(turn):
"""Switch turns."""
if turn == X:
return O
else:
return X
def congrat_winner(the_winner, computer, human):
"""Congratulate the winner."""
if the_winner != TIE:
print the_winner, "won!\n"
else:
print "It's a tie!\n"
if the_winner == computer:
print "As I predicted, human, I am triumphant once more. \n" \
"Proof that computers are superior to humans in all regards."
elif the_winner == human:
print "No, no! It cannot be! Somehow you tricked me, human. \n" \
"But never again! I, the computer, so swears it!"
elif the_winner == TIE:
print "You were most lucky, human, and somehow managed to tie me. \n" \
"Celebrate today... for this is the best you will ever achieve."
def main():
display_instruct()
computer, human = pieces()
turn = X
board = new_board()
display_board(board)
while not winner(board):
if turn == human:
move = human_move(board, human)
board[move] = human
else:
move = computer_move(board, computer, human)
board[move] = computer
display_board(board)
turn = next_turn(turn)
the_winner = winner(board)
congrat_winner(the_winner, computer, human)
# start the program
main()
raw_input("\n\nPress the enter key to quit.")
This post has been edited by Naming is hard: 15 March 2006 - 12:04 AM
Posted 15 March 2006 - 07:58 PM
Posted 16 March 2006 - 09:25 AM