Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- '''
- TicTacToe v1.0 by Benni1000
- '''
- import os
- import platform
- import random
- class Player():
- def __init__(self,name,cc):
- self.name = name
- self.cc = cc
- def isNumber(s):
- try:
- fl = int(s)
- except ValueError, TypeError:
- return False
- else:
- return True
- def setupPlayers():
- players = []
- for i in range(0,2):
- n = raw_input("Please enter the name of Player %d: "%(i+1))
- cc = raw_input("Should Player %d be ComputerControlled? (Y/N): "%(i+1))
- computerControlled = False
- if cc != "Y" and cc != "y" and cc != "N" and cc != "n":
- print "Invalid Choice Player %d is not ComputerControlled!"%(i+1)
- elif cc == "Y" or cc == "y":
- print "Player %d is ComputerControlled!"%(i+1)
- computerControlled = True
- elif cc == "N" or cc == "n":
- print "Player %d is not ComputerControlled!"%(i+1)
- players.append(Player(n,computerControlled))
- return players
- def drawField(f):
- print "[%s][%s][%s]"%(f[0],f[1],f[2])
- print "[%s][%s][%s]"%(f[3],f[4],f[5])
- print "[%s][%s][%s]"%(f[6],f[7],f[8])
- def cls():
- if platform.system().lower == "windows": os.system("cls")
- else: os.system("clear")
- def computerTurn(field):
- while True:
- r = random.randrange(1,10)
- if field[r-1] == r:
- return r
- def getGameState(f):
- z = "X"
- for i in range(1,3):
- if i == 2:
- z = "O"
- if f[0] == z and f[1] == z and f[2] == z: return i
- if f[3] == z and f[4] == z and f[5] == z: return i
- if f[6] == z and f[7] == z and f[8] == z: return i
- if f[0] == z and f[3] == z and f[6] == z: return i
- if f[1] == z and f[4] == z and f[7] == z: return i
- if f[2] == z and f[5] == z and f[8] == z: return i
- if f[0] == z and f[4] == z and f[8] == z: return i
- if f[2] == z and f[4] == z and f[6] == z: return i
- return 0
- while True:
- field = [1,2,3,4,5,6,7,8,9]
- players = setupPlayers()
- turn = 1
- count = 1
- cls()
- while True:
- st = getGameState(field)
- if st != 0:
- drawField(field)
- print "%s won!\nPress [ENTER] to continue..."%(players[st-1].name)
- raw_input()
- cls()
- break
- if count > 9:
- drawField(field)
- print "DRAW! Nobody won.\nPress [ENTER] to continue..."
- raw_input()
- cls()
- break
- drawField(field)
- print "%s's turn!"%(players[turn-1].name)
- if players[turn-1].cc:
- ch = computerTurn(field)
- else:
- ch = raw_input("Please enter a number between 1 and 9: ")
- cls()
- if isNumber(ch):
- ch = int(ch)
- if ch < 10 and ch > 0:
- if field[ch-1] != ch:
- print "Error: Field alredy taken!"
- else:
- if turn == 1:
- field[ch-1] = "X"
- turn = 2
- else:
- field[ch-1] = "O"
- turn = 1
- count += 1
- else:
- print "Error: The number is not between 1 and 9!"
- else:
- print "Error: That is NOT a number!"
Advertisement
Add Comment
Please, Sign In to add comment