# othello game sketch from graphics import * from random import random class Board: """ Othello board class """ def __init__(self,window): self.window = window self.board = [] # board of two-color disks self.color = [] for row in range(8): for column in range(8): # slot is the green slot of the board, not mutable slot = Rectangle(Point(3+column,2+row),Point(4+column,3+row)) slot.setFill("green") # fill color of the slot slot.setOutline("black") # color of the outline slot.setWidth(2) # width of the outline slot.draw(self.window) # adding the slot to the board # disk's color can be changed disk = Circle(Point(3.5+column,2.5+row),1/4) if random() >= 0.5: disk.setFill("black") self.color.append(0) # 0 for black color of the disk else: disk.setFill("white") self.color.append(1) # 1 for white color of the disk self.board.append(disk) disk.draw(self.window) def changeDisk(self,point): """ flips the disk (changes color to opposite), point is the coordinate of the click """ x = int(point.getX()) - 3 y = int(point.getY()) - 2 index = x+8*y if self.color[index] == 0: # if the disk is black self.color[index] = 1 # change to white self.board[index].setFill("white") else: #if the disk is white self.color[index] = 0 # change to black self.board[index].setFill("black") class Button: """ button class """ def __init__(self,window,point,width,height,message): self.window = window #self.anchor = point #self.w = width #self.h = height self.text = Text(point,message) self.box = Rectangle(Point(point.getX() - width/2,point.getY()-height/2),\ Point(point.getX() + width/2,point.getY()+height/2)) self.box.setFill("yellow") self.box.setOutline("black") def draw(self): self.box.draw(self.window) self.text.draw(self.window) def undraw(self): self.box.undraw() self.text.undraw() def setText(self,newMessage): self.text = newMessage def move(self,dx,dy): self.box.move(dx,dy) self.text.move(dx,dy) def main(): width = 800 height = 600 win = GraphWin("Othello sketch",width,height) win.setCoords(0,0,14,12) # set the coordinate system to 0,0 - left lower corner # and (14,12) - the upper right corner w = 14 h = 12 # the board is 3 units padded on the left and right, and # 2 units padded at the top and at the bottom b = Board(win) # put the exit button in the middle at the bottom exitButton = Button(win,Point(w/2,1),2,1,"EXIT") exitButton.draw() answer = False while not answer: click = win.getMouse() print("coordinates of the click:",int(click.getX()),int(click.getY())) if w/2 - 1 <= click.getX() <= w/2 + 1 and 0.5 <= click.getY() <= 1.5: answer = True # exit the program elif 3 <= click.getX() <= 11 and 2 <= click.getY() <= 10: # clicked inside the board # checking each slot print("clicked on the board!") b.changeDisk(click) else: pass win.close() main()