Skip to content

Instantly share code, notes, and snippets.

@escherize
Created November 16, 2013 10:10
Show Gist options
  • Save escherize/7498404 to your computer and use it in GitHub Desktop.
Save escherize/7498404 to your computer and use it in GitHub Desktop.
import random
class BigBoard():
def __init__(self):
_ = range(1,33);random.shuffle(_)
self.board = _[:32]
self.previous_number = 0
self.P1_MARK = " X"
self.P2_MARK = " O"
self.mark = self.P1_MARK
self.cpu_tries = 5
def get_item(self, x, y):
return self.board[x * 4 + y]
def set_item(self, x, y, item):
self.board[x * 4 + y] = item
def __str__(self):
s = ""
for x in range(4):
for y in range(4):
s += str(self.get_item(x,y)).zfill(2) + " | "
s += "\n"
return s
def index_of_item(self, item):
for idx, _ in enumerate(self.board):
if item == self.board[idx]:
return idx
def real_move(self, move):
new_move = (self.previous_number + move) % 32
self.previous_number = new_move
return new_move
def process_move(self, move):
new_move = self.real_move(move)
if move in self.board:
if new_move in self.board:
self.board[self.index_of_item(new_move)] = self.mark
def get_my_move(self):
my_move = int(raw_input("Enter your move: "))
self.process_move(my_move)
self.mark = self.P2_MARK
def get_cpu_move(self):
counter = self.cpu_tries
move = random.randint(1,33)
his_move = self.real_move(move)
while counter > 0:
move = random.randint(1,33)
his_move = self.real_move(move)
if not his_move in self.board:
counter -= 1
else:
counter = 0
self.process_move(his_move)
self.mark = self.P1_MARK
def someone_won(self):
for m in [self.P1_MARK, self.P2_MARK]:
#check horizontal
for x in range(4):
if self.get_item(x, 0) == m and \
self.get_item(x, 1) == m and \
self.get_item(x, 2) == m and \
self.get_item(x, 3) == m:
return m
if self.get_item(0, x) == m and \
self.get_item(1, x) == m and \
self.get_item(2, x) == m and \
self.get_item(3, x) == m:
return m
if self.get_item(0, 0) == m and \
self.get_item(1, 1) == m and \
self.get_item(2, 2) == m and \
self.get_item(3, 3) == m:
return m
if self.get_item(0, 3) == m and \
self.get_item(1, 2) == m and \
self.get_item(2, 1) == m and \
self.get_item(3, 0) == m:
return m
return False
b = BigBoard()
my_turn = "player" # player goes first
a_player_won = False
while not a_player_won:
print b
if my_turn == "player":
b.get_my_move()
a_player_won = b.someone_won()
my_turn = "cpu"
else: # his turn
b.get_cpu_move()
a_player_won = b.someone_won()
my_turn = "player"
print "{} wins!!!".format(a_player_won)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment