Skip to content

Instantly share code, notes, and snippets.

@SebastianJarsve
Created November 4, 2014 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SebastianJarsve/b17fa851853361011ba9 to your computer and use it in GitHub Desktop.
Save SebastianJarsve/b17fa851853361011ba9 to your computer and use it in GitHub Desktop.
TicTacToe.py
# coding: utf-8
import ui, console
class Grid (object):
def __init__(self):
self.cells = [0 for i in range(9)]
self.current_player = 1
def add_brick(self, pos):
if self.cells[pos] == 0 and not self.has_won():
self.cells[pos] = self.current_player
self.current_player = (self.current_player%2)+1
def has_won(self):
wins = ((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 win in wins:
if all(self.cells[i] == 1 for i in win) or all(self.cells[i] == 2 for i in win):
return True
return False
def game_draw(self):
return not any(i == 0 for i in self.cells) and not self.has_won()
def restart(self):
self.current_player = 1
for i in range(9):
self.cells[i] = 0
class GameView (ui.View):
def __init__(self):
self.width, self.height = ui.get_screen_size()
self.cells = self.create_cells()
self.game = Grid()
def create_cells(self):
width = self.width/3.0
height = self.height/3.0
cells = []
for i in range(9):
frame = ((i%3)*width, (i/3)*height, width, height)
cell = ui.Button()
cell.action = self.button_action
cell.frame = frame
cell.background_color = '#CCCCCC'
cell.border_color = '#000000'
cell.border_width = 5
cells.append(cell)
self.add_subview(cell)
return cells
@ui.in_background
def button_action(self, cell):
if not self.game.has_won() and not self.game.game_draw():
self.game.add_brick(self.cells.index(cell))
self.update_cells()
if self.game.has_won():
self.name = 'Player {} won!'.format((self.game.current_player%2)+1)
console.hud_alert(self.name, 'success', 2)
elif self.game.game_draw():
self.name = 'Game draw!'
console.hud_alert(self.name, 'error', 2)
else:
self.restart()
def restart(self):
self.name = 'Playing'
self.game.restart()
self.update_cells()
def update_cells(self):
images = {1:ui.Image.named('ionicons-close-round-256'), 2:ui.Image.named('ionicons-ios7-circle-outline-256')}
for i, cell in enumerate(self.game.cells):
if cell > 0:
self.cells[i].image = images[cell]
else:
self.cells[i].image = None
game_view = GameView()
game_view.present(hide_title_bar=True, orientations=['portrait'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment