Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter
- import random
- class Game(object):
- '''
- Enter the class docstring here
- '''
- tile_size = 100
- wins = [
- {1, 2, 3}, {4, 5, 6}, {7, 8, 9},
- {1, 4, 7}, {2, 5, 8}, {3, 6, 9},
- {1, 5, 9}, {3, 5, 7},
- ]
- board = [[None, None, None],
- [None, None, None],
- [None, None, None]]
- def __init__(self, parent):
- parent.title('Tic Tac Toe')
- self.parent = parent
- restart_button = tkinter.Button(self.parent, text='RESTART',width=20,command=self.restart)
- restart_button.grid()
- self.canvas = tkinter.Canvas(self.parent,width=self.tile_size * 3,height=self.tile_size * 3)
- self.canvas.grid()
- for row in range(3):
- for column in range(3):
- self.canvas.create_rectangle(self.tile_size * column,self.tile_size * row,self.tile_size * (column + 1),
- self.tile_size * (row + 1),fill='white')
- self.canvas.bind("<Button-1>", self.play)
- def restart(self):
- for shape in self.canvas.find_all():
- self.canvas.itemconfigure(shape, fill='white')# This method is invoked when the user clicks on the RESTART
- self.board =[[None, None, None],
- [None, None, None],
- [None, None, None]]
- def play(self, event):
- x,y = event.x, event.y
- shape = self.canvas.find_closest(x, y)
- self.canvas.itemconfigure(shape, fill='red')
- new_x = x // self.tile_size
- new_y = y // self.tile_size
- if new_x == 0 and new_y == 0:
- self.board [0][0] = 'user'
- elif new_x == 1 and new_y == 0:
- self.board[0][1] = 'user'
- elif new_x == 2 and new_y == 0:
- self.board [0][2] = 'user'
- elif new_x == 0 and new_y == 1:
- self.board [1][0] = 'user'
- elif new_x == 1 and new_y == 1:
- self.board [1][1] = 'user'
- elif new_x == 2 and new_y == 1:
- self.board [1][2] = 'user'
- elif new_x == 2 and new_y == 2:
- self.board [2][2] = 'user'
- elif new_x == 1 and new_y == 2:
- self.board [2][1] = 'user'
- elif new_x == 0 and new_y == 2:
- self.board [2][0] = 'user'
- counter = 1
- i = 1
- while i == 1:
- first_value = random.randint(0, 2)
- second_value = random.randint(0, 2)
- if counter == 4:
- break
- elif self.board[second_value][first_value] == None:
- first_val = first_value * 100
- second_val = second_value * 100
- self.board[second_value][first_value] = 'comp'
- shape = self.canvas.find_closest(first_val,second_val)
- self.canvas.itemconfigure(shape, fill='blue')
- i = 0
- counter += 1
- else:
- i = 1
- print(self.board)
- def main():
- root = tkinter.Tk()# Instantiate a root window
- my_game = Game(root)# Instantiate a Game object
- root.mainloop()# Enter the main event loop
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment