class Screen(Observer): def __init__(self,parent,bg="white"): self.canvas=Canvas(parent,bg=bg) print("parent",parent.cget("width"),parent.cget("height")) parent.bind("<Configure>", self.resize) self.parent=parent self.width=int(self.canvas.cget("width")) self.height=int(self.canvas.cget("height")) self.models=[] def update(self,model): if model not in self.models: self.models.append(model) print("View update") signal=model.get_signal() self.plot_signal(signal,model.get_color(),model.get_name()) def plot_signal(self,signal,color,name): w,h=self.canvas.winfo_width(),self.canvas.winfo_height() width,height=int(w),int(h) print(self.canvas.find_withtag("signal"+name)) if self.canvas.find_withtag("signal"+name) : self.canvas.delete("signal"+name) if signal and len(signal) > 1: if name=="X-Y" : plot = [((x+2)*width/4, (2*y/self.m+1)*height/2) for (x, y) in signal] else : plot = [(x*width, y*height/self.m + height/2) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal"+name) return def packing(self) : self.canvas.pack(fill="both", expand=1) def grid(self,n,m): self.n=n self.m=m w,h=self.canvas.winfo_width(),self.canvas.winfo_height() self.width,self.height=int(w),int(h) self.canvas.create_line(0,self.height/2.0,self.width-4,self.height/2,arrow="last",tags="line",fill="blue") self.canvas.create_line(self.width/2,self.height,self.width/2,5,arrow="last",tags="line",fill="blue") step1=self.width/n for t in range(1,n): x =t*step1 self.canvas.create_line(x,0,x,self.height,tags="line") step=self.height/m for t in range(1,m): y =t*step self.canvas.create_line(0,y,self.width,y,tags="line") def resize(self,event): self.canvas.delete("line") self.grid(self.n,self.m) for model in self.models : self.plot_signal(model.get_signal(), model.get_color(), model.get_name())
class Screen(Observer): def __init__(self,parent,bg="white"): self.canvas=Canvas(parent,bg=bg) print("parent",parent.cget("width"),parent.cget("height")) self.magnitude=Scale(parent,length=250,orient="horizontal", label="Magnitude", sliderlength=20, showvalue=0,from_=0,to=5, tickinterval=25) def update(self,model): print("View update") signal=model.get_signal() self.plot_signal(signal) def get_magnitude(self): return self.magnitude def plot_signal(self,signal,color="red"): w,h=self.canvas.cget("width"),self.canvas.cget("height") width,height=int(w),int(h) # print(self.canvas.find_withtag("signal")) if self.canvas.find_withtag("signal") : self.canvas.delete("signal") if signal and len(signal) > 1: plot = [(x*width, height/2.0*(y+1)) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal") return def grid(self, steps): w,h=self.canvas.cget("width"),self.canvas.cget("height") width,height=int(w),int(h) self.canvas.create_line(10,height/2,width,height/2,arrow="last") self.canvas.create_line(10,height-5,10,5,arrow="last") step=(width-10)/steps*1. for t in range(1,steps+2): x =t*step self.canvas.create_line(x,height/2-4,x,height/2+4) def packing(self) : self.canvas.pack() self.magnitude.pack()
class Screen(Observer): def __init__(self, parent, bg="white"): self.menu_bar = MenuBar(parent) self.canvas = Canvas(parent, bg=bg, name="screen") self.frameControl = Frame(parent) self.frameLabelSignals = LabelFrame(self.frameControl, text="Signaux", padx=20, pady=20) self.frameLabelMode = LabelFrame(self.frameControl, text="Mode", padx=20, pady=20) self.panelControl = ttk.Notebook(self.frameLabelSignals) self.checkbox_signalX = Checkbutton(self.frameLabelMode, text="Signal X") self.checkbox_signalY = Checkbutton(self.frameLabelMode, text="Signal Y") self.checkbox_XY = Checkbutton(self.frameLabelMode, text="XY") self.panel_control_page = [] # contient les références de mes curseurs for p in parent.get_models(): self.addPage(p.get_name()) def addPage(self, name): page = ttk.Frame(self.panelControl) self.panelControl.add(page, text='signal ' + name) visible_checkbox = Checkbutton(page, text="Afficher") magnitude = Scale(page, length=250, orient="horizontal", label="Amplitude", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=1, name="magnitudeScale") frequency = Scale(page, length=250, orient="horizontal", label="Frequency", sliderlength=20, showvalue=0, from_=0, to=25, tickinterval=5, name="frequencyScale") phase = Scale(page, length=250, orient="horizontal", label="Phase", sliderlength=20, showvalue=0, from_=0, to=20, tickinterval=5, name="phaseScale") visible_checkbox.pack(fill="x", pady=6) magnitude.pack(expand=1, fill="both", pady=6) frequency.pack(expand=1, fill="both", pady=6) phase.pack(expand=1, fill="both", pady=6) self.panel_control_page.append({ 'visible': visible_checkbox, 'magnitude': magnitude, 'frequency': frequency, 'phase': phase }) def update(self, model): if type(model) == list: for i, m in enumerate(model): signal = m.get_signal() #self.plot_signal(signal, m.get_color()) self.plot_signal(m) else: signal = model.get_signal() self.plot_signal(model) self.grid(6, 8) def get_panel_control_index(self): return self.panelControl.index('current') def get_canvas(self): return self.canvas def get_panel_control_page(self): return self.panel_control_page def get_magnitude(self, index): return self.panel_control_page[index]['magnitude'] def get_frequency(self, index): return self.panel_control_page[index]['frequency'] def get_phase(self, index): return self.panel_control_page[index]['phase'] def get_visible(self, index): return self.panel_control_page[index]['visible'] def get_checkbox_signalX(self): return self.checkbox_signalX def get_checkbox_signalY(self): return self.checkbox_signalY def get_checkbox_XY(self): return self.checkbox_XY def plot_signal(self, model): w, h = self.canvas.winfo_width(), self.canvas.winfo_height() width, height = int(w), int(h) signal = model.get_signal() name = model.get_name() color = model.get_color() if self.canvas.find_withtag("signal" + name): self.canvas.delete("signal" + name) if signal and len(signal) > 1 and model.is_visible(): plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal] self.canvas.create_line(plot, fill=color, smooth=1, width=3, tags="signal" + name) self.canvas.scale("signal" + name, width / 2, height / 2, 1.0, 0.25) def grid(self, row, col): w, h = self.canvas.winfo_width(), self.canvas.winfo_height() width, height = int(w), int(h) if self.canvas.find_withtag("grid"): self.canvas.delete("grid") # dessin des axes X et Y self.canvas.create_line(5, height / 2, width, height / 2, arrow="last", tags=('grid', 'axe-x')) self.canvas.create_line(width / 2, height - 5, width / 2, 5, arrow="last", tags=('grid', 'axe-y')) # dessin des lignes verticales for c in range(1, int(row / 2) + 1): stepW = width / row xd = width / 2 + c * stepW xg = width / 2 - c * stepW #Creation des lignes verticales self.canvas.create_line(xd, height - 5, xd, 5, dash=1, tags=('grid', 'vertical-line'), fill='grey') #cote droit self.canvas.create_line(xg, height - 5, xg, 5, dash=1, tags=('grid', 'vertical-line'), fill='grey') #cote gauche #Creation des tirets sur x self.canvas.create_line(xd, height / 2 - 4, xd, height / 2 + 4, tags=('grid', 'horizontal-line'), fill='grey') self.canvas.create_line(xg, height / 2 - 4, xg, height / 2 + 4, tags=('grid', 'horizontal-line'), fill='grey') # dessin des lignes horizontales for r in range(1, int(col / 2) + 1): stepH = height / col yB = height / 2 + r * stepH yH = height / 2 - r * stepH #Creation des lignes horizontales self.canvas.create_line(5, yB, width, yB, dash=1, tags=('grid', 'horizontal-line'), fill='grey') self.canvas.create_line(5, yH, width, yH, dash=1, tags=('grid', 'horizontal-line'), fill='grey') #Creation des tirets sur y self.canvas.create_line(width / 2 - 4, yB, width / 2 + 4, yB, tags=('grid', 'vertical-line'), fill='grey') self.canvas.create_line(width / 2 - 4, yH, width / 2 + 4, yH, tags=('grid', 'vertical-line'), fill='grey') def packing(self): self.menu_bar.pack(fill='x') self.canvas.pack(side=LEFT, expand=1, fill="both", padx=6, pady=6) self.panelControl.pack(side=RIGHT, expand=1, fill="both", pady=6) self.frameLabelSignals.pack(expand=1, fill="both") self.frameLabelMode.pack(expand=1, fill="both") self.checkbox_signalX.pack(side=LEFT) self.checkbox_signalY.pack(side=LEFT) self.checkbox_XY.pack(side=RIGHT) self.frameControl.pack(side=RIGHT, expand=1, fill="both", pady=6)
class Screen(Observer): def __init__(self, parent, model_x, model_y, bg="white"): self.canvas = Canvas(parent, bg=bg) self.model_x = model_x self.model_y = model_y print("parent", parent.cget("width"), parent.cget("height")) self.showX = True self.showY = True self.frame = Frame(parent) # Signal X self.magnitude_x = Scale(self.frame, length=250, orient="horizontal", name="m_x", label="Magnitude X", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=25) self.frequency_x = Scale(self.frame, length=250, orient="horizontal", name="f_x", label="Frequency X", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=25) self.phase_x = Scale(self.frame, length=250, orient="horizontal", name="p_x", label="Phase X", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=25) # Signal Y self.magnitude_y = Scale(self.frame, length=250, orient="horizontal", name="m_y", label="Magnitude Y", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=25) self.frequency_y = Scale(self.frame, length=250, orient="horizontal", name="f_y", label="Frequency Y", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=25) self.phase_y = Scale(self.frame, length=250, orient="horizontal", name="p_y", label="Phase Y", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=25) self.frame2 = Frame(parent, bg="black") self.varX = IntVar() self.varY = IntVar() self.varXY = IntVar() self.lbl = Label(self.frame2, text="Courbes", fg="black") # Boutons de sélection (X, Y ou X-Y) self.caseX = Checkbutton(self.frame2, text="X", variable=self.varX, command=self.getX) self.caseY = Checkbutton(self.frame2, text="Y", variable=self.varY, command=self.getY) self.caseXY = Checkbutton(self.frame2, text="XY", variable=self.varXY, command=self.getXY) self.caseXY.select() self.wi = self.canvas.cget("width") self.hi = self.canvas.cget("height") self.stepx = 0 self.stepy = 0 # Step x self.step_x = Entry(parent, name="x") # Step y self.step_y = Entry(parent, name="y") def update(self, model): print("View update") if model.getId() == 0: signal = model.get_signal() self.plot_signal(signal) elif model.getId() == 1: signal = model.get_signal() self.plot_signal(signal, "blue") else: raise ("Error") # Signal X def get_magnitude(self, whichOne): if whichOne == 0: return self.magnitude_x elif whichOne == 1: return self.magnitude_y else: raise ("Error") def get_frequency(self, whichOne): if whichOne == 0: return self.frequency_x elif whichOne == 1: return self.frequency_y else: raise ("Error") def get_phase(self, whichOne): if whichOne == 0: return self.phase_x elif whichOne == 1: return self.phase_y else: raise ("Error") def get_step_x(self): return self.step_x def get_step_y(self): return self.step_y def getX(self): print("update_X(self,event)") self.caseY.deselect() self.caseXY.deselect() self.showX = True self.showY = False self.update(self.model_x) if self.canvas.find_withtag("signal_y"): self.canvas.delete("signal_y") def getY(self): print("update_Y(self,event)") self.caseX.deselect() self.caseXY.deselect() self.showX = False self.showY = True self.update(self.model_y) if self.canvas.find_withtag("signal_x"): self.canvas.delete("signal_x") def getXY(self): print("update_XY(self,event)") self.caseX.deselect() self.caseY.deselect() self.showX = True self.showY = True self.update(self.model_x) self.update(self.model_y) def plot_signal(self, signal, color="red"): w, h = self.wi, self.hi width, height = int(w), int(h) if color == "red" and self.showX == True: if self.canvas.find_withtag("signal_x"): self.canvas.delete("signal_x") if signal and len(signal) > 1: plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3, tags="signal_x") elif color == "blue" and self.showY == True: if self.canvas.find_withtag("signal_y"): self.canvas.delete("signal_y") if signal and len(signal) > 1: plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3, tags="signal_y") def grid(self, step_x, step_y): w, h = self.wi, self.hi width, height = int(w), int(h) self.stepx = (width - 10) / step_x * 1. self.stepy = (height - 10) / step_y * 1. for t in range(1, step_x + 2): x = t * self.stepx self.canvas.create_line(x, 0, x, height, tags="grid") #self.canvas.create_line(x,height/2-4,x,height/2+4) for t in range(1, step_y + 2): y = t * self.stepy self.canvas.create_line(0, y, width, y, tags="grid") #self.canvas.create_line(width/2-4,y,width/2+4,y) def resize(self, event): if event: self.wi = event.width self.hi = event.height self.canvas.delete("grid") self.plot_signal(self.model_x.get_signal()) self.plot_signal(self.model_y.get_signal(), "blue") self.grid(25, 25) def packing(self): self.canvas.pack(fill="both", expand=1) self.step_x.pack(expand=1, fill="both") self.step_y.pack(expand=1, fill="both") self.frame.pack(expand=1, fill="both") self.magnitude_x.grid(row=0, column=0) self.magnitude_y.grid(row=0, column=1) self.frequency_x.grid(row=1, column=0) self.frequency_y.grid(row=1, column=1) self.phase_x.grid(row=2, column=0) self.phase_y.grid(row=2, column=1) self.frame2.pack(side="bottom", expand=1) self.lbl.grid(row=0, column=0) self.caseX.grid(row=0, column=1) self.caseY.grid(row=0, column=2) self.caseXY.grid(row=0, column=3)
class Window(Frame): def __init__(self,game,canvas_hw,master=None): Frame.__init__(self,master) #call superclass constructor self.master.title("BadukPy Game") self.pack(expand=True,fill='both') self.menubar = Menu(self) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=menu) menu.add_command(label="Load SGF File") menu.add_command(label="Save SGF File") menu.add_command(label="Quit",command=self.quit_window) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Play", menu=menu) menu.add_command(label="New Game", command=self.new_game) menu.add_command(label="Pass", command=self.pass_move) menu.add_command(label="Undo Move") menu.add_command(label="Options") menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Window", menu=menu) menu.add_command(label="Game Tree Viewer") menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Help", menu=menu) menu.add_command(label="Help",command=self.help_go) menu.add_command(label="About",command=self.about) self.master.config(menu=self.menubar) self.game = game self.size = self.game.size self.canvas_hw = canvas_hw self.cir_d = self.canvas_hw/(self.size+1) #circle diameter self.line_xy = [self.cir_d] #for drawing lines for i in range(self.size): self.line_xy.append(self.line_xy[i]+self.cir_d) self.stones = {} self.frame = Frame(padx=15,pady=15) self.canvas = Canvas(self.frame,width=self.canvas_hw,height=self.canvas_hw) #draw lines for i in range(self.size): #vertical self.canvas.create_line(self.line_xy[i],self.cir_d,self.line_xy[i],self.canvas_hw-self.cir_d,width=3) #horizontal self.canvas.create_line(self.cir_d,self.line_xy[i],self.canvas_hw-self.cir_d,self.line_xy[i],width=3) self.canvas.grid(row=0,column=0,sticky='w') self.frame.pack() move = self.game.generate_move() self.make_move(move) self.canvas.bind('<Button-1>', self.mousepress) def new_game(self,evt=None): self.game = Game(self.size) self.__redraw_board(self,self.game.current_board) def pass_move(self,evt=None): self.make_move(PASS_MOVE) move = self.game.generate_move() self.make_move(move) def quit_window(self,evt=None): print "quit" def help_go(self,evt=None): print "help" def about(self,evt=None): print "about" def mousepress(self, event): move = self.coordinateToMove(event.x, event.y) #test if move is valid if ((0 < move[0] < (1 + self.size)) and (0 < move[1] < (1 + self.size)) and self.game.legal_move(move)): self.make_move(move) move = self.game.generate_move() self.make_move(move) print "(black,white): ", g.score() def coordinateToMove(self, x, y): x1 = ((x - self.cir_d / 2) / self.cir_d) + 1 y1 = ((y - self.cir_d / 2) / self.cir_d) + 1 return (x1, y1) def moveToCooridate(self,move): ''' method for finding the x,y pos to draw a move at x,y(board coords)''' return ((self.cir_d/2) + (move[0]-1)*self.cir_d,(self.cir_d/2) + (move[1]-1)*self.cir_d) def __draw_stone(self,move,color): ''' draws a stone ''' if color == EMPTY: #remove self.canvas.delete(str(move)) else: if not self.canvas.find_withtag(str(move)): (x,y) = self.moveToCooridate(move) self.canvas.create_oval(x,y,x+self.cir_d,y+self.cir_d,fill=draw_color[color], tags=(str(move),draw_color[color])) def __redraw_board(self,board): ''' redraw the board ''' # check for differences between board.goban and self.stones for move,color in board.goban.items(): self.__draw_stone(move,color) def make_move(self,move): board = self.game.make_move(move) if board: # will be None if non-legal move self.__redraw_board(board) def random_game(self): if self.moves_remaining == 0: return else: self.moves_remaining -= 1 move = self.game.generate_move() self.make_move(move) self.after(100,self.random_game)
class Breakout(Tk): def __init__(self): Tk.__init__(self) #self.canvas.delete('all') self.geometry('790x600') self.resizable( 0, 0 ) #set both parameters to false and to check whether window is resizable in x and y directions self.func() # game screen def func(self): self.canvas = Canvas(self, bg='skyblue', width=990, height=600, highlightcolor='green') self.canvas.pack( expand=1, fill=BOTH ) #when it is true and widget expands to fill any space # ball self._initiate_new_ball() #self.level=choice([1]) # paddle self.canvas.create_rectangle(375, 975, 525, 585, fill='red', tags='paddle') self.bind('<Key>', self._move_paddle) # bricks self.bricks = {} brick_coords = [15, 12, 60, 45] for i in range(56): self.canvas.create_rectangle(brick_coords, outline='green', fill=('yellow'), tags='brick' + str(i)) self.bricks['brick' + str(i)] = None brick_coords[0] += 55 brick_coords[2] += 55 if brick_coords[2] > 790: brick_coords[0] = 15 brick_coords[2] = 60 brick_coords[1] += 55 brick_coords[3] += 55 def _initiate_new_ball(self): if self.canvas.find_withtag('ball'): self.canvas.delete('ball') self.x = 300 self.y = 350 self.angle = 240 self.speed = 10 self.level = 0 self.score = 0 self.canvas.create_oval(self.x, self.y, self.x + 10, self.y + 10, fill='orange', outline='red', tags='ball') self.after(2000, self._move_ball) def _move_paddle(self, event): if event.keysym == 'Left': if self.canvas.coords('paddle')[0] > 0: self.canvas.move('paddle', -20, 0) elif event.keysym == 'Right': if self.canvas.coords('paddle')[2] < 990: self.canvas.move('paddle', +20, 0) #def _move_ball1(self): # call1() #self._initiate_new_ball1() def _move_ball(self): # variables to determine where ball is in relation to other objects ball = self.canvas.find_withtag('ball')[0] bounds = self.canvas.find_overlapping(0, 0, 790, 600) paddle = self.canvas.find_overlapping( *self.canvas.coords('paddle')) for brick in self.bricks.iterkeys(): self.bricks[brick] = self.canvas.find_overlapping( *self.canvas.bbox(brick)) # calculate change in x,y values of ball angle = self.angle - 120 # correct for quadrant IV increment_x = cos(radians(angle)) * self.speed increment_y = sin(radians(angle)) * self.speed #self.level += choice([1]) #score=self.score #score=0 # finite state machine to set ball state if ball in bounds: self.ball_state = 'moving' for brick, hit in self.bricks.iteritems(): if ball in hit: self.ball_state = 'hit_brick' delete_brick = brick elif ball in paddle: self.ball_state = 'hit_wall' elif (self.score) // 3 == 56: self.canvas.create_text( WIDTH / 4, HEIGHT / 2.3, text="CONGRATS!! GAME COMPLETED!", font=("Helvetica", 20), fill="orange") self.canvas.create_text(WIDTH / 4, HEIGHT / 2, text=(self.score // 3), font=("Helvetica", 20), fill="red") self.canvas.create_text(WIDTH / 4, HEIGHT / 1.7, text="YOUR SCORE ", font=("Helvetica", 20), fill="darkorange") #image() quit_to_exit() call() elif ball not in bounds: if self.canvas.coords('ball')[1] < 600: self.ball_state = 'hit_wall' else: self.ball_state = 'out_of_bounds' #self.level += choice([1]) self.canvas.create_text( WIDTH / 2.5, HEIGHT / 2.3, text="GAME OVER !!PLEASE CLOSE THE WINDOW TO RESTART!", tag="cr2", font=("Helvetica", 20), fill="orange") self.canvas.create_text(WIDTH / 4, HEIGHT / 2, text="YOUR SCORE IS", tag="cr1", font=("Helvetica", 20), fill="orange") self.canvas.create_text(WIDTH / 4, HEIGHT / 1.7, text=(self.score // 3) + 1, tag="cr", font=("Helvetica", 20), fill="red") quit_to_exit() call() self._initiate_new_ball() #self.bind('<key>',self.game_over) #game = Breakout() #game.mainloop() # handler for ball state if self.ball_state is 'moving': self.canvas.move('ball', increment_x, increment_y) self.after(35, self._move_ball) # self.level +=choice([1]) elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall': if self.ball_state == 'hit_brick': self.canvas.delete(delete_brick) del self.bricks[delete_brick] self.canvas.move('ball', -increment_x, -increment_y) # self.level += choice([1]) self.score += choice([1]) self.angle += choice([135]) self.canvas.delete("cr") self.canvas.delete("cr1") self.canvas.delete("cr2") #canvas.create_text(WIDTH/4,HEIGHT/5,text="GAME OVER!") self._move_ball()
class Window(Frame): def __init__(self, game, canvas_hw, master=None): Frame.__init__(self, master) #call superclass constructor self.master.title("BadukPy Game") self.pack(expand=True, fill='both') self.menubar = Menu(self) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=menu) menu.add_command(label="Load SGF File") menu.add_command(label="Save SGF File") menu.add_command(label="Quit", command=self.quit_window) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Play", menu=menu) menu.add_command(label="New Game", command=self.new_game) menu.add_command(label="Pass", command=self.pass_move) menu.add_command(label="Undo Move") menu.add_command(label="Options") menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Window", menu=menu) menu.add_command(label="Game Tree Viewer") menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Help", menu=menu) menu.add_command(label="Help", command=self.help_go) menu.add_command(label="About", command=self.about) self.master.config(menu=self.menubar) self.game = game self.size = self.game.size self.canvas_hw = canvas_hw self.cir_d = self.canvas_hw / (self.size + 1) #circle diameter self.line_xy = [self.cir_d] #for drawing lines for i in range(self.size): self.line_xy.append(self.line_xy[i] + self.cir_d) self.stones = {} self.frame = Frame(padx=15, pady=15) self.canvas = Canvas(self.frame, width=self.canvas_hw, height=self.canvas_hw) #draw lines for i in range(self.size): #vertical self.canvas.create_line(self.line_xy[i], self.cir_d, self.line_xy[i], self.canvas_hw - self.cir_d, width=3) #horizontal self.canvas.create_line(self.cir_d, self.line_xy[i], self.canvas_hw - self.cir_d, self.line_xy[i], width=3) self.canvas.grid(row=0, column=0, sticky='w') self.frame.pack() move = self.game.generate_move() self.make_move(move) self.canvas.bind('<Button-1>', self.mousepress) def new_game(self, evt=None): self.game = Game(self.size) self.__redraw_board(self, self.game.current_board) def pass_move(self, evt=None): self.make_move(PASS_MOVE) move = self.game.generate_move() self.make_move(move) def quit_window(self, evt=None): print "quit" def help_go(self, evt=None): print "help" def about(self, evt=None): print "about" def mousepress(self, event): move = self.coordinateToMove(event.x, event.y) #test if move is valid if ((0 < move[0] < (1 + self.size)) and (0 < move[1] < (1 + self.size)) and self.game.legal_move(move)): self.make_move(move) move = self.game.generate_move() self.make_move(move) print "(black,white): ", g.score() def coordinateToMove(self, x, y): x1 = ((x - self.cir_d / 2) / self.cir_d) + 1 y1 = ((y - self.cir_d / 2) / self.cir_d) + 1 return (x1, y1) def moveToCooridate(self, move): ''' method for finding the x,y pos to draw a move at x,y(board coords)''' return ((self.cir_d / 2) + (move[0] - 1) * self.cir_d, (self.cir_d / 2) + (move[1] - 1) * self.cir_d) def __draw_stone(self, move, color): ''' draws a stone ''' if color == EMPTY: #remove self.canvas.delete(str(move)) else: if not self.canvas.find_withtag(str(move)): (x, y) = self.moveToCooridate(move) self.canvas.create_oval(x, y, x + self.cir_d, y + self.cir_d, fill=draw_color[color], tags=(str(move), draw_color[color])) def __redraw_board(self, board): ''' redraw the board ''' # check for differences between board.goban and self.stones for move, color in board.goban.items(): self.__draw_stone(move, color) def make_move(self, move): board = self.game.make_move(move) if board: # will be None if non-legal move self.__redraw_board(board) def random_game(self): if self.moves_remaining == 0: return else: self.moves_remaining -= 1 move = self.game.generate_move() self.make_move(move) self.after(100, self.random_game)
class Screen(Observer): def __init__(self, parent, bg="white"): self.canvas = Canvas(parent, bg=bg) self.canvas.bind("<Configure>", self.resize) self.width = int(self.canvas.cget("width")) self.height = int(self.canvas.cget("height")) print("parent", parent.cget("width"), parent.cget("height")) self.magnitude = Scale(parent, length=250, orient="horizontal", label="Magnitude", sliderlength=20, showvalue=0, from_=0, to=10, tickinterval=1, relief="sunken") self.frequency = Scale(parent, length=250, orient="horizontal", label="Frequency", sliderlength=20, showvalue=0, from_=0, to=10, tickinterval=1, relief="sunken") self.phase = Scale(parent, length=250, orient="horizontal", label="Phase", sliderlength=20, showvalue=0, from_=0, to=10, tickinterval=1, relief="sunken") def update(self, model): print("View update") signal = model.get_signal() self.plot_signal(signal) def get_magnitude(self): return self.magnitude def get_frequency(self): return self.frequency def get_phase(self): return self.phase def plot_signal(self, signal, color="red"): w, h = self.canvas.winfo_width(), self.canvas.winfo_height() width, height = int(w), int(h) print(self.canvas.find_withtag("signal")) if self.canvas.find_withtag("signal"): self.canvas.delete("signal") if signal and len(signal) > 1: plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3, tags="signal") return def grid(self, steps): w, h = self.canvas.cget("width"), self.canvas.cget("height") width, height = int(w), int(h) # self.canvas.create_line(10,height/2,width,height/2,arrow="last") # self.canvas.create_line(10,height-5,10,5,arrow="last") step = (width - 10) / steps * 1. for t in range(1, steps + 2): x = t * step self.canvas.create_line(x, 0, x, height) self.canvas.create_line(0, x, width, x) def packing(self): self.canvas.pack() self.magnitude.pack() self.frequency.pack() self.phase.pack() self.canvas.pack(expand=1, fill="both", padx=6) self.magnitude.pack(expand=1, fill="x", padx=2) self.frequency.pack(expand=1, fill="x", padx=2) self.phase.pack(expand=1, fill="x", padx=2) def resize(self, event): wscale = float(event.width) / self.width hscale = float(event.height) / self.height self.width = event.width self.height = event.height print("resize", wscale, hscale) # resize the canvas #self.config(width=self.width, height=self.height) scale_xy = self.width * 1.0 / self.height # rescale all the objects tagged with the "all" tag self.canvas.scale("all", 0, 0, wscale, hscale)
class Breakout(Tk): def __init__(self): Tk.__init__(self) self.geometry('400x400') self.resizable(0, 0) # game screen self.canvas = Canvas(self, bg='black', width=400, height=400) self.canvas.pack(expand=1, fill=BOTH) # ball self._initiate_new_ball() # paddle self.canvas.create_rectangle(175, 375, 225, 385, fill='black', outline='white', tags='paddle') self.bind('<Key>', self._move_paddle) # bricks self.bricks = {} brick_coords = [5, 5, 35, 15] for i in range(39): self.canvas.create_rectangle(*brick_coords, outline='white', fill=('#{}'.format( randint(100000, 999999))), tags='brick' + str(i)) self.bricks['brick' + str(i)] = None brick_coords[0] += 30 brick_coords[2] += 30 if brick_coords[2] > 395: brick_coords[0] = 5 brick_coords[2] = 35 brick_coords[1] += 10 brick_coords[3] += 10 def _initiate_new_ball(self): if self.canvas.find_withtag('ball'): self.canvas.delete('ball') self.x = 60 self.y = 100 self.angle = 140 self.speed = 5 self.canvas.create_oval(self.x, self.y, self.x + 10, self.y + 10, fill='lawn green', outline='white', tags='ball') self.after(1000, self._move_ball) def _move_paddle(self, event): if event.keysym == 'Left': if self.canvas.coords('paddle')[0] > 0: self.canvas.move('paddle', -10, 0) elif event.keysym == 'Right': if self.canvas.coords('paddle')[2] < 400: self.canvas.move('paddle', +10, 0) def _move_ball(self): # variables to determine where ball is in relation to other objects ball = self.canvas.find_withtag('ball')[0] bounds = self.canvas.find_overlapping(0, 0, 400, 400) paddle = self.canvas.find_overlapping(*self.canvas.coords('paddle')) for brick in self.bricks.iterkeys(): self.bricks[brick] = self.canvas.find_overlapping( *self.canvas.bbox(brick)) # calculate change in x,y values of ball angle = self.angle - 90 # correct for quadrant IV increment_x = cos(radians(angle)) * self.speed increment_y = sin(radians(angle)) * self.speed # finite state machine to set ball state if ball in bounds: self.ball_state = 'moving' for brick, hit in self.bricks.iteritems(): if ball in hit: self.ball_state = 'hit_brick' delete_brick = brick elif ball in paddle: self.ball_state = 'hit_wall' elif ball not in bounds: if self.canvas.coords('ball')[1] < 400: self.ball_state = 'hit_wall' else: self.ball_state = 'out_of_bounds' self._initiate_new_ball() # handler for ball state if self.ball_state is 'moving': self.canvas.move('ball', increment_x, increment_y) self.after(15, self._move_ball) elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall': if self.ball_state == 'hit_brick': self.canvas.delete(delete_brick) del self.bricks[delete_brick] self.canvas.move('ball', -increment_x, -increment_y) self.angle += choice([119, 120, 121]) self._move_ball()
class Breakout(Tk): def __init__(self): Tk.__init__(self) self.geometry('400x400') self.resizable(0,0) # game screen self.canvas = Canvas(self, bg='black', width=400, height=400) self.canvas.pack(expand=1, fill=BOTH) # ball self._initiate_new_ball() # paddle self.canvas.create_rectangle(175,375,225,385, fill='black', outline='white', tags='paddle') self.bind('<Key>', self._move_paddle) # bricks self.bricks = {} brick_coords = [5,5,35,15] for i in range(39): self.canvas.create_rectangle(*brick_coords, outline='white', fill=('#{}'.format(randint(100000,999999))), tags='brick' + str(i)) self.bricks['brick' + str(i)] = None brick_coords[0] += 30; brick_coords[2] += 30 if brick_coords[2] > 395: brick_coords[0] = 5; brick_coords[2] = 35 brick_coords[1] += 10; brick_coords[3] += 10 def _initiate_new_ball(self): if self.canvas.find_withtag('ball'): self.canvas.delete('ball') self.x = 60; self.y = 100 self.angle = 140; self.speed = 5 self.canvas.create_oval(self.x,self.y,self.x+10,self.y+10, fill='lawn green', outline='white', tags='ball') self.after(1000, self._move_ball) def _move_paddle(self, event): if event.keysym == 'Left': if self.canvas.coords('paddle')[0] > 0: self.canvas.move('paddle', -10, 0) elif event.keysym == 'Right': if self.canvas.coords('paddle')[2] < 400: self.canvas.move('paddle', +10, 0) def _move_ball(self): # variables to determine where ball is in relation to other objects ball = self.canvas.find_withtag('ball')[0] bounds = self.canvas.find_overlapping(0,0,400,400) paddle = self.canvas.find_overlapping(*self.canvas.coords('paddle')) for brick in self.bricks.iterkeys(): self.bricks[brick] = self.canvas.find_overlapping(*self.canvas.bbox(brick)) # calculate change in x,y values of ball angle = self.angle - 90 # correct for quadrant IV increment_x = cos(radians(angle)) * self.speed increment_y = sin(radians(angle)) * self.speed # finite state machine to set ball state if ball in bounds: self.ball_state = 'moving' for brick, hit in self.bricks.iteritems(): if ball in hit: self.ball_state = 'hit_brick' delete_brick = brick elif ball in paddle: self.ball_state = 'hit_wall' elif ball not in bounds: if self.canvas.coords('ball')[1] < 400: self.ball_state = 'hit_wall' else: self.ball_state = 'out_of_bounds' self._initiate_new_ball() # handler for ball state if self.ball_state is 'moving': self.canvas.move('ball', increment_x, increment_y) self.after(15, self._move_ball) elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall': if self.ball_state == 'hit_brick': self.canvas.delete(delete_brick) del self.bricks[delete_brick] self.canvas.move('ball', -increment_x, -increment_y) self.angle += choice([119, 120, 121]) self._move_ball()