Sign InNuggetsTutorials CodePadCheatsheet



The task of this unit is to design and implement the game of tic tac toe.

You should enable two players to play. Whoever gets three pieces in a row first wins.

Have fun!

import turtle import time canvas = turtle.Screen() canvas.setup(600, 600) canvas.bgcolor("white") size = 600 pen = turtle.Turtle() pen.hideturtle() pen.pensize(4) pen.speed(0) squares = [['a','b','c'],['d','e','f'],['g','h','i']] turn = 'X' exit = 0 x_index = 0 y_index = 0 num_clicks = 0 def drawGrid(color): pen.color(color) pen.up() pen.goto(-size/2, size/6) pen.down() pen.forward(size) pen.up() pen.goto(-size/2, -size/6) pen.down() pen.forward(size) pen.up() pen.goto(-size/6, size/2) pen.right(90) pen.down() pen.forward(size) pen.up() pen.goto(size/6, size/2) pen.down() pen.forward(size) def drawX(color, x, y): pen.color(color) pen.up() pen.goto(x, y) pen.down() pen.write('X', font=('Ariel', 100, 'normal')) def drawO(color, x, y): pen.color(color) pen.up() pen.goto(x, y) pen.down() pen.write('O', font=('Ariel', 100, 'normal')) def getIndex(raw): if raw >= -size/2 and raw <= -size/6: return 0 elif raw <= size/6: return 1 else: return 2 def indexToCoordinate(index): if index == 0: return -size/3 - 40 if index == 1: return -40 if index == 2: return size/3 - 40 def play(x, y): global turn global x_index global y_index global num_clicks global exit x_index = getIndex(x) y_index = getIndex(y) if exit == 0: if squares[x_index][y_index] != 'X' and squares[x_index][y_index] != 'O': num_clicks += 1 if turn == 'X': squares[x_index][y_index] = 'X' drawX('red', indexToCoordinate(x_index), indexToCoordinate(y_index)) turn = 'O' else: squares[x_index][y_index] = 'O' drawO('blue', indexToCoordinate(x_index), indexToCoordinate(y_index)) turn = 'X' exit = game_over() if exit == 1: game_msg("X wins!") elif exit == 2: game_msg("O wins!") elif exit == 3: game_msg("It is a tie!") def game_msg(msg): msg_pen = turtle.Turtle() msg_pen.hideturtle() msg_pen.up() msg_pen.goto(0, -80) msg_pen.down() msg_pen.color("purple") msg_pen.speed(1) msg_pen.write(msg, align="center", font=("Helvetica", 30, "bold italic")) def game_over(): global num_clicks if (squares[0][0] == squares[0][1] and squares[0][1] == squares[0][2]) or \ (squares[1][0] == squares[1][1] and squares[1][1] == squares[1][2]) or \ (squares[2][0] == squares[2][1] and squares[2][1] == squares[2][2]) or \ (squares[0][0] == squares[1][0] and squares[1][0] == squares[2][0]) or \ (squares[0][1] == squares[1][1] and squares[1][1] == squares[2][1]) or \ (squares[0][2] == squares[1][2] and squares[1][2] == squares[2][2]) or \ (squares[0][0] == squares[1][1] and squares[1][1] == squares[2][2]) or \ (squares[0][2] == squares[1][1] and squares[1][1] == squares[2][0]): if turn == 'X': return 2 else: return 1 elif num_clicks >= 9: return 3 else: return 0 drawGrid("black") canvas.onclick(play) canvas.mainloop()

© CS Wonders·Home·About·Contact·Classes·Gallery·Glossary·Fun Facts