def __init__(self, center, radius): """ Initializes a graphical circle object. The circle is centered at the position specified by the center parameter. The circle's radius is set to the radius parameter. """ # Make a turtle graphics object to do the drawing. Assign it # to an instance variable so other methods can access it. self.turtle = Turtle() self.turtle.speed(0) # Make turtle's actions as fast as possible self.turtle.hideturtle() # Make the turtle invisible # Create a local Screen object to receive user input. screen = Screen() screen.delay(0) # Do not slowly trace drawing screen.listen() # Set focus for keystrokes # Mouse click repositions the circle screen.onclick(self.move) # Set mouse press handler # Up cursor key calls the increase method to expand the circle screen.onkey(self.increase, 'Up') # Set "up" cursor key handler # Down cursor key calls the decrease method to contract the circle screen.onkey(self.decrease, 'Down') # Set "down" cursor key handler # Make a circle object. Assign it to an instance variable so other methods # can access it. self.circle = Circle(center, radius) # Start the graphics environment. The local screen object # will exist until the user quits the program. screen.mainloop()
def __init__(self, center, radius): """ (GraphicalCircle, tuple, int) -> GraphicalCircle Initializes a graphical circle object The circle is centered at the position <center>. The circle radius is set to the <radius> """ # Make a turtle graphics object to do the drawing. # Assign it to an instance variable the_turtle, # so other methods can access it self.the_turtle = Turtle() self.the_turtle.speed(0) # fastest turtle self.the_turtle.hideturtle() # hide turtle the_screen = Screen() # Create local screen object: Receive user input the_screen.delay(0) # trace drawing delay - slow the_screen.listen() # focus on keystrokes # Mouse click re-positions the circle the_screen.onclick(self.move) # Set mouse press handler - # Up cursor key calls the increases method to expand the circle the_screen.onkey(self.increase, 'Up') # Set "up" cursor key handler # Down cursor key calls the deecrease method to contract the circle the_screen.onkey(self.decrease, 'Down') # Set "Down" cursor key handler # Make a circle object # Assign it to an instance variable the_circle, # so other methods can access it self.the_circle = Circle(center, radius) mainloop() # Start event loop
def main(): delay(0) # Do not slowly trace drawing t.speed(0) # Make turtle's actions as fast as possible t.hideturtle() # Make the turtle invisible screen = Screen() # Create Screen object to receive user input screen.listen() # Set focus for keystrokes screen.onclick(do_click) # Set mouse press handler screen.onkey(do_up, 'Up') # Set "up" cursor key handler screen.onkey(do_down, 'Down') # Set "down" cursor key handler mainloop()
class Game(): def __init__(self): self.win = Screen() self.win.bgcolor('pink') # self.win.setup(width=w, height=h, startx=None, starty=None) self.border = Border() width, height = self.win.window_width(), self.win.window_height() print(width, height) self.border.draw_self((width, height)) self.turtle = Arrow() self.win.onkey(self.quit, 'q') self.win.onkey(self.arrow_left, 'Left') self.win.onkey(self.arrow_right, 'Right') self.win.onkey(self.arrow_up, 'Up') self.win.onkey(self.arrow_down, 'Down') self.win.listen() self.win.onclick(self.check_coord) self.increase_speed() self.move_arrow() def check_coord(self, x, y): print(x, y) def quit(self): self.win.bye() def move_arrow(self): self.turtle.move() self.win.ontimer(self.move_arrow, 50) def arrow_left(self): self.turtle.turn_left() def arrow_right(self): self.turtle.turn_right() def arrow_up(self): self.turtle.turn_up() def arrow_down(self): self.turtle.turn_down() def increase_speed(self): self.turtle.speedup() self.win.ontimer(self.increase_speed, 3000) def main(self): self.win.mainloop()
class Game(object): def __init__(self): self.snake = snake.Snake() self.monster = monster.Monster(ri(-24,24) * 10,ri(-24,24) * 10) self.interface = Screen() self.interface.setup(500, 500) self.interface.tracer(0) self.interface.onkey(self.up, "Up") self.interface.onkey(self.down, "Down") self.interface.onkey(self.left, "Left") self.interface.onkey(self.right, "Right") self.interface.listen() def up(self): self.snake.turn(0, 1) def down(self): self.snake.turn(0, -1) def left(self): self.snake.turn(-1, 0) def right(self): self.snake.turn(1, 0) def listen(self): self.snake.move() self.monster.move(self.snake.getx(), self.snake.gety()) grow_len = self.foods.update(self.snake.getx(), self.snake.gety()) if grow_len: self.snake.grow(grow_len) self.interface.update() def show(self): self.interface.ontimer(self.listen(), 100) return self.foods.empty() def tutorial(self): pen = Turtle(visible=False) pen.penup() pen.goto(-200, 100) pen.pendown() pen.write('Welcome to 119010136\'s snake game...\n\nYou are going to use the 4 arrow keys to move\nthe snake around the screen, trying to consume\nall the food items before the monster catches you...', align='left', font=('Arial', 13, 'bold')) self.snake.appear() self.monster.appear() def fun(x, y): pen.clear() self.play() self.interface.onclick(fun) def play(self): self.foods = food.Foods() self.interface.update() self.snake.grow(5) while True: if self.show(): self.snake.win() break elif self.snake.crash(): self.snake.lose() break elif self.snake.die(self.monster.getx(),self.monster.gety()): self.snake.lose() break def refresh(self): self.snake = snake.Snake() def close(self): self.interface.bye() def end(self): self.interface.mainloop()
if boardState[y][x] == 0: return False return True def addMarker(x, y): """Visually put a marker on the moved-to square""" midX = (baseX + (.5 * gridlength)) + (x * gridlength) locY = (baseY + (y * gridlength)) al.up() al.goto(midX, locY) if playerOneTurn: al.down() al.circle(gridlength * .5) else: al.sety(al.ycor() + (gridlength * .5)) al.down() al.stamp() al.up() def whoseTurn(): """Move the turtle to the correct side in the turn marker""" al.goto(gridlength * (-1 if playerOneTurn else 1), baseY - (gridlength * 2.75)) createBoard() screen.onclick(checkClick) screen.mainloop()
) # \n adds a new line screen.bye() return screen = Screen() # Sets up Screen size and grid screen.bgcolor("lightblue") screen.setup(600, 600) screen.screensize(500, 500) screen.title("Turtle Tag!") user_arrow = Turtle() # Arrow shape instead of a Turtle shape turtle = Turtle("turtle") turtle.color("darkgreen") user_arrow.color("blue") turtle.shapesize(7) turtle.pensize(3) # Moves the Chased-Turtle so it and the arrow don't start in the same position turtle.pu() # Pen Up shorthand turtle.left(90) turtle.forward(100) turtle.pd() screen.onclick(chase_move) # Runs the function when the screen is clicked screen.mainloop() window.mainloop()
elif (answer == "number"): #clicked on a number, only show number print(tile.number) tile.drawNumber() #clicked on an empty spot, show island else: # self.showIsland(xIndex, yIndex) #settings boxSize = 40 numberOfBoxes = [10, 10] numberOfMines = 10 screenWidth = numberOfBoxes[0] * (boxSize + 1) - 1 screenHeight = numberOfBoxes[1] * (boxSize + 1) - 1 screen = Screen() screen.setup(screenWidth, screenHeight) screen.setworldcoordinates(0, -screenHeight, screenWidth, 0) screen.bgcolor("gray") imageMine = "res/Mine.gif" screen.addshape(imageMine) screen.tracer(0, 0) #for making turtle instant myMap = TileMap(numberOfBoxes, boxSize, numberOfMines) screen.onclick(myMap.click) #set action for clicking screen.update() #for making turtle instant screen.mainloop()
# Make the pen fast. bob.hideturtle() bob.speed(0) #ocean.tracer(0) colors = ['red', 'blue', 'green', 'orange', 'purple', 'black', 'plum'] #Where the paper is bx = -1000 by = -1000 def throwPaper(x, y): global bx, by bx = x by = y def tictoc(): global bx, by print('tt', bx, by) if (bx > -1000): bob.up() bob.goto(bx, by) bob.down() bob.circle(20) bx = bx + 10 ocean.ontimer(tictoc,200) ocean.onclick(throwPaper) ocean.ontimer(tictoc, 1000)
class GameView(object): """This class handles the user facing part of the game. This draws the game board and components.""" def __init__( self, controller: GameController, board_size: int, grid_size: int = 3 ) -> None: self.controller = controller #### Setup the screen. # Change it to a square 50% larger than the game board size. self.screen = Screen() screen_size = int(board_size * 1.5) self.resize_screen(screen_size, screen_size) #### Setup the game board. # Initialize the turtle that will draw the game board. self.board = GameView.new_turtle() self.lineweight = board_size / 60 self.board.pensize(self.lineweight) self.board.speed(0) #self.board.dot(0) self.board_size = board_size self.grid_size = grid_size self.grid_line_spacing = board_size / grid_size #### Create our player markers. self.players = [] marker_scale = board_size / 100 / grid_size marker_lineweight = 8 * marker_scale self.create_player_shapes() self.players.append(GameView.new_turtle('x marker', marker_scale, marker_lineweight)) self.players.append(GameView.new_turtle('o marker', marker_scale, marker_lineweight)) #### Final initialization self.draw_board() self.screen.onclick(self.mouse_click) self.screen.mainloop() def create_player_shapes(self, color: str = 'black') -> None: """Creates custom turtle shapes for the x and o player markers. This method sets up custom shapes that can be used with the turtle.shape() method. Recall that you could make your turtle look like an actual turtle (instead of the default arrow shape) by calling turtle.shape('turtle'). After this method has been called, you can change the sape of your turtle to an x or an o by calling turtle.shape('x marker') or turtle.shape('o marker'). These shapes are initialized at a size appropriate for display on a 3x3 grid on a 300px game board. """ # Build the x out of a backslash and forward slash. # These numbers are the vertices of the slashes. backslash = ((-25,-25), (25,25)) forwardslash = ((-25,25), (25,-25)) shape = Shape('compound') shape.addcomponent(backslash, '', color) shape.addcomponent(forwardslash, '', color) self.screen.register_shape('x marker', shape) # Approximate the o with a 20-sided polygon. # These numbers are the vertices of the polygon. circle = (( 00.00,-25.00), ( 07.73,-23.78), ( 14.69,-20.23), ( 20.23,-14.69), ( 23.78,-07.73), ( 25.00, 00.00), ( 23.78, 07.73), ( 20.23, 14.69), ( 14.69, 20.23), ( 07.73, 23.78), ( 00.00, 25.00), (-07.73, 23.78), (-14.69, 20.23), (-20.23, 14.69), (-23.78, 07.73), (-25.00, 00.00), (-23.78,-07.73), (-20.23,-14.69), (-14.69,-20.23), (-07.73,-23.78),) shape = Shape('compound') shape.addcomponent(circle, '', color) self.screen.register_shape('o marker', shape) def draw_line(self, x: float, y: float, heading: float, length: float) -> None: """Draws a line on the game board. Args: x, y: The coordinates where the line starts. heading: The angle of the line. length: The length of the line. """ self.board.setheading(heading) self.board.penup() self.board.goto(x, y) self.board.pendown() self.board.forward(length) def draw_board(self) -> None: """Draws the game board centered on the point (0,0).""" # Each horizontal line will have a common starting x coordinate. # Each vertical line will have a common starting y coordinate. # These coordinates are equal to each other. anchor = self.board_size / 2 # The y-coordinates of horizontal lines and the x-coordinates of # vertical lines begin equal to each other and increment equally increments = list( anchor - i * self.grid_line_spacing for i in range(1, self.grid_size) ) for i in increments: self.draw_line(i, anchor, 270, self.board_size) self.draw_line(anchor, i, 180, self.board_size) def mark_play(self, player: int, space: List[int]) -> None: """Marks a play on the game board. Args: player: The player to mark, based on play order, starting at 1. space: The space to be marked. The bottom-left space is (0,0). """ # Offset the space coordinates so that (0,0) becomes the center space space = [s - self.grid_size // 2 for s in space] # Calculate the pixel offset between spaces on the game board space_offset = self.board_size / self.grid_size # Find the screen coordinates of the center of the selected space on # the game board. center = [space_offset * s for s in space] current_player = self.players[player - 1] current_player.goto(*center) current_player.stamp() def mouse_click(self, x: float, y: float) -> None: """Handles mouse click actions.""" # Ignore all clicks outside of the game board area extent = self.board_size / 2 if not (-extent < x < extent and -extent < y < extent): return # Find the space on the board in which the mose was clicked # The bottom-left square is space (0,0). space = [round(c / self.grid_line_spacing) + self.grid_size // 2 for c in [x, y]] # Ask the controller to make a play in this space player = self.controller.make_play(space) # If the play was successful, the controller will return the player # who made the play if player: # Mark the play on the board self.mark_play(player, space) def resize_screen(self, width: int, height: int) -> None: """Resizes the screen.""" self.screen.setup(width, height) @staticmethod def new_turtle( shape: Optional[str] = None, scale: float = 1.0, lineweight: float = 1.0 ) -> Turtle: """Creates a new turtle and hides it. Args: shape: A valid shapename. See TurtleScreen documentation. scale: A factor to scale the size the turtle. lineweight: The thickness of the lines composing the shape. Yields: TurtleGraphicsError: For invalid shape names. """ t = Turtle() t.shape(shape) t.shapesize(scale, scale, lineweight) t.penup() t.hideturtle() return t
class Tablero(): totalCeldas = 0 coords = {} #{1:[(),(),(),()],2:(),(),(),()} coordsSimple = {} #{(x,y):(f,c),(x,y):(f,c)} celdaOcupadaTablero = [ ] #Almacena las celdas ocupadas entre todos los jugadores en el tablero save_drawing = [] def __init__(self, lienzo, color='black', full=True, ancho_pantalla=810, alto_pantalla=430, visible=True, filas=3, celdas=3, alto_celda=20, ancho_celda=20, ejes=False, celdas_numeradas=False): self.widthScreen = ancho_pantalla self.heightScreen = alto_pantalla self.visible = visible self.alto = filas self.ancho = celdas self.alto_celda = alto_celda self.ancho_celda = ancho_celda self.t = Turtle() self.t.color(color) self.t.hideturtle() self.screen = Screen() self.screen.setup(self.widthScreen, self.heightScreen) self.screen.tracer(0, 0) self.screen.delay(0) self.malla(full=True) if celdas_numeradas == True: self.celdasNumeradas() self.paleta() self.lienzo(color=lienzo) if ejes == True: self.ejes() ############################################################################################ def go(self, x, y, down=True): self.t.up() self.t.goto(x, y) if down: self.t.down() ############################################################################################ def malla(self, x=0, y=0, full=False): """ Dibuja la cuadricula base. Si full=True la fila 1 comienza en la esquina sup iz de screen. Crea lista de coordenadas self.coords={FILA_1:(x,y),FILA_2:(x,y)} self.coordsSimple={(x,y):(1,2)} """ if full: x = self.widthScreen / -2 y = self.heightScreen / 2 self.ancho = int(self.widthScreen / self.ancho_celda) self.alto = int(self.heightScreen / self.alto_celda) self.go(x, y) #Va al punto de inicio, primera fila, primera celda for k in range(0, self.alto): # c calcula la coordenada de Y basada en la altura de la celda*fila c = (-k * self.alto_celda) + y self.go(x, c, down=self.visible) self.coords[k + 1] = [] for i in range(1, self.ancho + 1): self.celda(self.ancho_celda, self.alto_celda) #guardamos las coordenadas para cada celda #calcula el punto central de la celda basado en el ancho y alto de cada celda/2 xCor = ((self.ancho_celda * i) + x) - (self.ancho_celda / 2) yCor = c - (self.alto_celda / 2) self.coords[k + 1].append((xCor, yCor)) self.coordsSimple[(xCor, yCor)] = (k + 1, i) self.go((self.ancho_celda * i) + x, c, down=self.visible) def celda(self, ancho, alto): angulo = 360 self.totalCeldas += 1 #Lleva la cuenta de celdas dibujadas/veces llamado for i in range(1, 5): angulo -= 90 if i % 2 != 0: self.t.forward(ancho) self.t.seth(angulo) else: self.t.forward(alto) self.t.seth(angulo) ############################################################################################ def onclick(self): self.screen.onclick(lambda x, y: self.gestion(x, y)) ############################################################################################ def gestion(self, xClick, yClick): #Obtiene la coordenada central de la celda coordenadas_celda = self.getCelCoords(xClick, yClick) #Obtiene la coordenada simple(1,1) de esa celda coordenadas_celda_simple = self.coordsSimple[coordenadas_celda] #print('coordenada completa ',coordenadas_celda) print('coordenada simple ', coordenadas_celda_simple) color = 'green' if coordenadas_celda_simple[0] >= 3 and coordenadas_celda_simple[ 0] <= 19 and coordenadas_celda_simple[ 1] >= 3 and coordenadas_celda_simple[1] <= 38: self.celdaOcupadaTablero.append( (coordenadas_celda_simple[0], coordenadas_celda_simple[1], self.color)) self.relleno(coordenadas_celda) else: if coordenadas_celda_simple == (2, 7): self.color = 'red' elif coordenadas_celda_simple == (2, 9): self.color = 'blue' elif coordenadas_celda_simple == (2, 11): self.color = 'green' elif coordenadas_celda_simple == (2, 13): self.color = 'yellow' elif coordenadas_celda_simple == (2, 15): self.color = 'grey' elif coordenadas_celda_simple == (2, 17): self.color = 'purple' elif coordenadas_celda_simple == (20, 5): #DELETE print('delete') self.lienzo(color='beige') self.celdaOcupadaTablero = [] elif coordenadas_celda_simple == (20, 9): #SAVE print('save') file_name = self.screen.textinput('Save', 'Title:') outfile = open(file_name, 'wb') pickle.dump(self.celdaOcupadaTablero, outfile) outfile.close() elif coordenadas_celda_simple == (20, 13): #LOAD print('load') file_name = self.screen.textinput('Load', 'Title:') try: infile = open(file_name, 'rb') drawing = pickle.load(infile) infile.close() self.setDrawing(drawing) self.loadDrawing() except: print('Nombre no válido') #print(self.celdaOcupadaTablero) ############################################################################################ def getCoordsbySimple(self, f=0, c=0): for i in self.coordsSimple.items(): if i[1] == (f, c): return i[0] ############################################################################################ def getCelCoords(self, xClick, yClick): #devuelve las coordenadas de la celda respecto a las coordenadas del click #dicho de otra forma. Recibe las coordenadas del click y devuelve las coordenadas # de la celda for key in self.coords.keys(): count = 1 for celda in self.coords[key]: x = celda[0] y = celda[1] """ Calcula las cordenadas centrales de cada lado de la celda Luego compara las coordenadas del click y comprueba si están dentro de los extremos """ maxX = x + (self.ancho_celda / 2) minX = x - (self.ancho_celda / 2) maxY = y + (self.alto_celda / 2) minY = y - (self.alto_celda / 2) r = 0 if xClick < maxX and xClick > minX: r += 1 if yClick < maxY and yClick > minY: r += 1 if r == 2: return (x, y) else: count += 1 ############################################################################################ def lienzo(self, color='grey'): self.color = color for fila in self.coords.keys(): count = 0 if fila > 2 and fila < len(self.coords.keys()) - 1: for celda in self.coords[fila]: if count < len(self.coords[fila]) - 2 and count > 1: self.relleno(celda) count += 1 self.color = 'blue' ########################################################################################## def compruebaCeldaOcupada(self, celda=()): """ Devuelve cierto! si la celda=(x,y) se encuentra en el atributo de clase self.celdaOcupada """ if celda in self.celdaOcupadaTablero: return True else: return False ############################################################################################ def ejes(self, separacion=50): """ Dibuja ejes cartesianos de referencia """ self.t.color('black') self.go(self.widthScreen / -2, 0) self.t.forward(self.widthScreen) self.go(0, self.heightScreen / 2) self.t.seth(270) self.t.forward(self.heightScreen) for i in range(0, 4): self.go(0, 0) self.t.seth(90 * i) if i == 0 or i == 1: if i == 0: for i in range(1, int( (self.widthScreen / 2) / separacion)): self.t.forward(separacion) self.t.write('+' + str(separacion * i), font=("Arial", 5, "normal")) else: for i in range(1, int( (self.heightScreen / 2) / separacion)): self.t.forward(separacion) self.t.write('+' + str(separacion * i), font=("Arial", 5, "normal")) else: if i == 2: for i in range(1, int( (self.widthScreen / 2) / separacion)): self.t.forward(separacion) self.t.write('-' + str(separacion * i), font=("Arial", 5, "normal")) else: for i in range(1, int( (self.heightScreen / 2) / separacion)): self.t.forward(separacion) self.t.write('-' + str(separacion * i), font=("Arial", 5, "normal")) self.go(0, 0) self.t.seth(0) ############################################################################################ def celdasNumeradas(self): """ Muestra el numero de fila y celda en cada cuadro """ for coords in self.coordsSimple.keys(): self.go(coords[0], coords[1]) self.t.write(self.coordsSimple[coords]) ############################################################################################ def relleno(self, coordenadas): self.go(coordenadas[0], coordenadas[1] - (self.alto_celda / 2)) self.t.begin_fill() self.t.color(self.color) self.t.forward(self.ancho_celda / 2) self.t.seth(90) self.t.forward(self.alto_celda) self.t.seth(180) self.t.forward(self.ancho_celda) self.t.seth(270) self.t.forward(self.alto_celda) self.t.seth(0) self.t.forward(self.ancho_celda) self.t.end_fill() ############################################################################################ def paleta(self): choose = self.coords[2][1] self.go(x=choose[0], y=choose[1] - 5) self.t.write('Choose a colour') #DELETE choose = self.coords[20][1] self.go(x=choose[0], y=choose[1] - 5) self.t.write('Delete') self.color = 'black' button_delete = self.coords[20][4] self.relleno(button_delete) ################## #SAVE choose = self.coords[20][6] self.go(x=choose[0], y=choose[1] - 5) self.t.write('Save') self.color = 'black' button_save = self.coords[20][8] self.relleno(button_save) ################## #LOAD choose = self.coords[20][10] self.go(x=choose[0], y=choose[1] - 5) self.t.write('Load') self.color = 'black' button_save = self.coords[20][12] self.relleno(button_save) ################## self.color = 'red' rojo = self.coords[2][6] self.relleno(rojo) self.color = 'blue' azul = self.coords[2][8] self.relleno(azul) self.color = 'green' verde = self.coords[2][10] self.relleno(verde) self.color = 'yellow' amarillo = self.coords[2][12] self.relleno(amarillo) self.color = 'grey' gris = self.coords[2][14] self.relleno(gris) self.color = 'purple' morado = self.coords[2][16] self.relleno(morado) ############################################################################################ def loadDrawing(self): lista = self.celdaOcupadaTablero for celda in lista: self.color = celda[2] self.relleno(self.getCoordsbySimple(f=celda[0], c=celda[1])) ############################################################################################ def setDrawing(self, lista): for celda in lista: self.celdaOcupadaTablero.append(celda)
from turtle import Turtle, Screen def drawSquare(turtle): turtle.goto(100, 0) turtle.goto(100, 100) turtle.goto(0, 100) turtle.goto(0, 0) screen = Screen() screen.tracer(0, 0) screen.onclick(lambda x, y: screen.update()) turtle = Turtle() drawSquare(turtle) screen.mainloop()
def start(): global TSM global nodeAmount TSM = tsm(nodeAmount, moveEnds = False) TSM.draw() s.onkey(start, 'Return') def drawIterate(): global TSM if TSM is None: start() return TSM.iterate(1000) TSM.draw() s.onkey(drawIterate, 'space') def clickedOn(x, y): global TSM if TSM is None: start() return TSM.toggle(x,y) s.onclick(clickedOn) s.listen() s.mainloop()
tileSize = 32 number_of_initial_live_tiles = 100 numberOfTiles = [map_size, map_size] screenSize = [ numberOfTiles[0] * (tileSize + 1) - 1, numberOfTiles[1] * (tileSize + 1) - 1 ] screen = Screen() screen.setup(screenSize[0], screenSize[1]) screen.setworldcoordinates(-10, -20 - screenSize[1], 20 + screenSize[0], 10) screen.bgcolor("black") screen.tracer(0, 0) #for making drawing instant screen.onclick(close) game = Gameboard(numberOfTiles, tileSize, screenSize, screen) sim = Simulation(game) random_tuples = np.random.randint(0, map_size, (number_of_initial_live_tiles, 2)).tolist() for tpl in random_tuples: sim.add_live_cell(tpl) while not shutdown: sim.update_state() screen.update() #for making drawing instant sleep(0.1) screen.mainloop()
class TurtlePlot: def __init__(self, width, height, title=""): """ Initialize a Turtle Plot Args: width: Width of the screen height: Height of the screen """ self.width = width self.height = height self.title = title self.screen = Screen() self.screen.clear() self.screen.setup(width=width, height=height) self.screen.setworldcoordinates(0, 0, width, height) self.screen.tracer(0, 1) self.screen.onclick(lambda x, y: self.zoom_in(x, y)) self.screen.title(self.title + " (click to zoom in)") def done(self): """ Wait until user clicks or closes screen. """ self.screen.mainloop() def _setworldcoordinates(self, xmin, ymin, xmax, ymax): try: self.screen.setworldcoordinates(xmin, ymin, xmax, ymax) except Exception as e: pass def zoom_in(self, x, y): self._setworldcoordinates(x - 50, y - 50, x + 50, y + 50) self.screen.onclick(lambda x, y: self.zoom_out()) self.screen.title(self.title + " (click to zoom out)") def zoom_out(self): self._setworldcoordinates(0, 0, self.width, self.height) self.screen.onclick(lambda x, y: self.zoom_in(x, y)) self.screen.title(self.title + " (click to zoom in)") def draw(self, plot_record: PlotRecord, x_bounds, y_bounds): """ Draw a plot on the turtle screen. Args: plot_record: The plot record to display. x_bounds: The plots x bounds y_bounds: The plots y bounds """ outline_turtle = Turtle() outline_turtle.hideturtle() xy_turtles = [Turtle() for _ in plot_record.xys] for i, trtl in enumerate(xy_turtles): trtl.penup() trtl.pensize(2) trtl.pencolor(plot_record.xys[i].color) trtl.hideturtle() turtle_xmin, turtle_xmax = x_bounds turtle_ymin, turtle_ymax = y_bounds turtle_dx = turtle_xmax - turtle_xmin turtle_dy = turtle_ymax - turtle_ymin # leave 20% space on left and bottom # for labeling turtle_margin_left = 0.2 turtle_margin_right = 0.2 turtle_margin_bottom = 0.3 turtle_margin_top = 0.3 turtle_x_chart_min = turtle_xmin + (turtle_dx * turtle_margin_left) turtle_y_chart_min = turtle_ymin + (turtle_dy * turtle_margin_bottom) turtle_x_chart_max = turtle_xmax - (turtle_dx * turtle_margin_right) turtle_y_chart_max = turtle_ymax - (turtle_dy * turtle_margin_top) turtle_dx_chart = turtle_x_chart_max - turtle_x_chart_min turtle_dy_chart = turtle_y_chart_max - turtle_y_chart_min fontsize = 8 outline_turtle.penup() outline_turtle.setposition( turtle_xmin, (turtle_y_chart_min + turtle_y_chart_max) * 0.5) outline_turtle.write(plot_record.ylabel) outline_turtle.setposition(turtle_x_chart_min, turtle_y_chart_max) outline_turtle.pendown() outline_turtle.setposition(turtle_x_chart_min, turtle_y_chart_min) outline_turtle.setposition(turtle_x_chart_max, turtle_y_chart_min) outline_turtle.penup() all_xs = [x for xy in plot_record.xys for x in xy.x] all_ys = [y for xy in plot_record.xys for y in xy.y] series_xmin = min(all_xs) series_xmax = max(all_xs) series_ymin = min(all_ys) series_ymax = max(all_ys) series_dx = (series_xmax - series_xmin) or 1 series_dy = (series_ymax - series_ymin) or 1 # scale factor from series to turtle xscale = turtle_dx_chart / series_dx yscale = turtle_dy_chart / series_dy outline_turtle.setposition(turtle_x_chart_min - fontsize, turtle_y_chart_max - (fontsize * 0.5)) outline_turtle.write("%0.02f" % series_ymax, align='right') outline_turtle.setposition( turtle_x_chart_min - fontsize, turtle_y_chart_min + (turtle_dy_chart * 0.5) - (fontsize * 0.5)) outline_turtle.write("%0.02f" % ((series_ymin + series_ymax) * 0.5), align='right') outline_turtle.setposition(turtle_x_chart_min - fontsize, turtle_y_chart_min - (fontsize * 0.5)) outline_turtle.write("%0.02f" % series_ymin, align='right') outline_turtle.setposition(turtle_x_chart_max, turtle_y_chart_min - (fontsize * 2)) outline_turtle.write("%0.02f" % series_xmax, align='center') outline_turtle.setposition( turtle_x_chart_min + (turtle_dx_chart * 0.5) - fontsize, turtle_y_chart_min - (fontsize * 2)) outline_turtle.write("%0.02f" % ((series_xmin + series_xmax) * 0.5), align='center') outline_turtle.setposition(turtle_x_chart_min, turtle_y_chart_min - (fontsize * 2)) outline_turtle.write("%0.02f" % series_xmin, align='center') for i, xy in enumerate(plot_record.xys): # position turtle at first xy value xy_turtles[i].setposition( turtle_x_chart_min + (xscale * (xy.x[0] - series_xmin)), turtle_y_chart_min + (yscale * (xy.y[0] - series_ymin))) xy_turtles[i].pendown() for j in range(min(len(xy.x), len(xy.y))): xy_turtles[i].setposition( turtle_x_chart_min + (xscale * (xy.x[j] - series_xmin)), turtle_y_chart_min + (yscale * (xy.y[j] - series_ymin))) xy_turtles[i].penup() xy_turtles[i].setposition(turtle_x_chart_max + (fontsize * 2), turtle_y_chart_max - (fontsize * 2 * i)) xy_turtles[i].write(xy.label, align='left')
#Programa Principal filas = 4 columnas = 6 pantalla = Screen() pantalla.setup(columnas*50, filas*50) pantalla.screensize(columnas*50, filas*50) pantalla.setworldcoordinates(-5, -5, columnas+5, filas+5) pantalla.delay(0) tortuga = Turtle() tortuga.hideturtle() simbolo = crear_matriz(filas, columnas) tablero = crear_matriz(filas, columnas) inicializar_tablero(tablero) rellena_simbolos(simbolo) dibuja_tablero(tablero,simbolo) pantalla.onclick(clic) #tortuga.onclick(clic) pantalla.mainloop() #pantalla.exitonclick()
from turtle import Turtle, Screen import time screen = Screen() def create_turtle(x, y): t = Turtle(visible=False) t.penup() t.goto(x, y) t.showturtle() screen.onclick(create_turtle) screen.mainloop()
ocean = Screen() ocean.title("Let's find Splash") print("Creating a drawing turtle") bob = Turtle() bob.color('purple') bob.hideturtle() bob.speed(0) bob.width(5) colors = ['red', 'blue', 'orange', 'purple', 'black'] def rings(x, y): for i in range(20, 180, 10): bob.up() bob.goto(x, y - i) bob.down() bob.circle(i) def splash(x, y): print(x, y) bob.color(random.choice(colors)) rings(x, y) rings(x + 10, y) ocean.onclick(splash)
class Frame: def __init__(self, width=800, height=600): self.width = width self.height = height self.screen = Screen() self.screen.setup(width=width + 100, height=height + 100, startx=0, starty=0) self.screen.setworldcoordinates(-50, -50, width + 50, height + 50) self.quit = False self.draw_frame() def close(self): self.screen.bye() def clear(self): self.draw_frame() def draw_frame(self): self.screen.clear() width = self.width height = self.height boundary = Turtle() boundary.hideturtle() boundary.speed('fastest') boundary.penup() boundary.goto(0 + 2, 0 - 15) boundary.write('0') boundary.goto(0 - 8, 0) boundary.write('0') boundary.goto(0, 0) boundary.pendown() boundary.goto(width, 0) boundary.penup() boundary.goto(width - 10, 0 - 15) boundary.write(str(int(width))) boundary.goto(width, 0) boundary.pendown() boundary.goto(width, height) boundary.goto(0, height) boundary.penup() boundary.goto(0 - 25, height - 10) boundary.write(str(int(height))) boundary.goto(0, height) boundary.pendown() boundary.goto(0, 0) boundary.penup() self.screen.register_shape("button", ((0, 0), (0, 85), (25, 85), (25, 0))) t = Turtle(shape="button") t.hideturtle() t.penup() t.fillcolor('pink') t.goto(width - 95, -20) t.showturtle() boundary.goto(width - 62, -40) boundary.write("Quit", font=("Arial", 12, "normal")) self.screen.onclick(self.check_quit) def check_quit(self, x, y): self.quit = 706 < x < 792 and -47 < y < -20
colors = ['red', 'blue', 'green', 'orange', 'purple', 'black', 'plum'] bubbles = [] def blowBubble(x, y): color1 = random.choice(colors) color2 = random.choice(colors) b = Bubble(x, y, color1, color2) b.randomBump() bubbles.append(b) def tictoc(): # Simulate the passage of time for each bubbble for b in bubbles: b.sim() ocean.update() ocean.ontimer(tictoc, 20) # Create the initial set of bubbles for i in range(numBubbles): blowBubble(random.randint(-50, 50), random.randint(-50, 50)) ocean.onclick(blowBubble) ocean.ontimer(tictoc, 20) # What happens if the line below is missing ocean.mainloop()
closest_cell = cell_center minimum_distance = sneggy.distance(x, y) blue_figure.body[0].goto(closest_cell) blue_figure.positioning_blue() # MAIN CYCLE main_drawer = drawers.Drawer() main_drawer.draw_field_from_centers() main_drawer.draw_frame() blue_figure = figures.Figure(color="blue", length=4) screen.onclick(fun=mark_closest, btn=1) screen.onclick(fun=blue_figure.turn_blue, btn=3) for rows in constants.FIELD_CELLS_CENTERS: for cell in constants.FIELD_CELLS_CENTERS[rows]: print(cell) print(" ") while True: screen.update() time.sleep(0.1) # screen.onclick(fun=turn, btn=3) screen.mainloop()
if (self.numberOfTiles[0] * self.numberOfTiles[1] - self.numberOfMines == totalRevealed): print("I was here") self.majorTile.number = -3 self.majorTile.showTileContent() self.screen.onclick(self.endGame) #settings numberOfTiles = [20, 15] numberOfMines = 40 tileSize = 32 screenSize = [ numberOfTiles[0] * (tileSize + 1) - 1, numberOfTiles[1] * (tileSize + 1) - 1 ] screen = Screen() screen.setup(screenSize[0], screenSize[1]) screen.setworldcoordinates(0, -screenSize[1], screenSize[0], 0) screen.bgcolor("gray") screen.tracer(0, 0) #for making drawing instat game = GameBoard(numberOfTiles, numberOfMines, tileSize, screenSize, screen) print(game.tilesWithMine) screen.onclick(game.click) #set actions in case of mouse clicking screen.update() #for making drawing instat screen.mainloop()
class Plotter(object): """ A plotter object provides a graphical window for plotting data and mathematical functions. """ def __init__(self, width, height, min_x, max_x, min_y, max_y): """ (Plotter, int, int, int, int, int, int) -> turtle The constructor initializes the Turtle graphics window. It accepts parameters that define the window’s physical size and ranges of x and y axes. Initializes the plotter with a window that is <width> wide and <height> high. Its x-axis ranges from <min_x> to <max_x>, and it's y-axis ranges from <min_y> to <max_y>. Establishes the global begining and ending x values for the plot and the x_increament value. Draws the x-axis and y-axes """ # Init self.pen = Pen() # The plotter object's pen self.screen = Screen() # The plotter object's sceen self.pen.speed(0) # Speed up rendering self.screen.tracer(0, 0) # DONT draw pen while drawing # Establish global x and y ranges self.min_x, self.max_x = min_x, max_x self.min_y, self.max_y = min_y, max_y self.screen.setup(width=width, height=height) # Set up window size, in pixels # set up screen size, in pixels self.screen.screensize(width, height) self.screen.setworldcoordinates(min_x, min_y, max_x, max_y) # x-axis distance that correspond to one pixel in window distance self.x_increament = (max_x - min_x) / width self.draw_grid(20) self.draw_axes() self.screen.title('Plot') self.screen.update() def __del__(self): """ (Plotter) -> stdout Called when the client no longer uses the plotter object. The interpreter calls this method, also known as destructor, when the object is no longer bound to a reference with in the executing program. Among other times, this happens when the program’s execution terminates. """ print('Done Printing') def draw_axes(self, grid=False): """ (Plotter, bool) -> turtle Draws the x and y axes within the plotting window. An option Boolean parameter <grid> controls the drawing of accessory horizontal and vertical lines """ if grid: self.draw_grid(20) self.pen.hideturtle() # Make pen invisible prev_width = self.pen.width() self.pen.width(2) # Draw x axis self.pen.color('black') self.draw_arrow(self.min_x, 0, self.max_x, 0) # Draw y axis self.draw_arrow(0, self.min_y, 0, self.max_y) self.pen.width(prev_width) def draw_grid(self, num): """ (Plotter, int) -> turtle Draws horizontal and vertical accessory reference coordinate lines on the plot. Parameter <num> control the frequency of the reference lines. """ self.pen.up() # self.pen.setposition(self.min_x, self.min_y) inc = (self.max_x - self.min_y) / num self.pen.color('lightblue') x = self.min_x while x <= self.max_x: self.pen.setposition(x, self.min_y) self.pen.down() self.pen.setposition(x, self.min_y) self.pen.up() x += inc # Next x inc = (self.max_y - self.min_y) / num y = self.min_y while y <= self.max_y: self.pen.setposition(self.min_x, y) self.pen.down() self.pen.setposition(self.max_x, y) self.pen.up() y += inc # Next y def draw_arrow(self, x1, y1, x2, y2): """ (Plotter, int, int, int, int) -> turtle Draws a line segment with an attached arrow head. Expects four numeric parameters representing the (x 1 , y 1 ) tail end point and (x 2 , y 2 ) head end point of the arrow. """ # Draw arrow shaft self.pen.up() self.pen.setposition(x1, y1) # Move the pen starting point self.pen.down() # Draw line bottom to top self.pen.setposition(x2, y2) # Move the pen starting point # Draw arrow head dy = y2 - y1 dx = x2 - x1 angle = atan2(dy, dx) * 180 / pi self.pen.setheading(angle) self.pen.stamp() def plot_function(self, f, color, update=True): """ (Plotter, func, str, bool) -> turtle Plots the curve of a given function <f> with a specified color, established by initialize_plotter. Plots (x, f(x)), for all x in range min_x <= x < max_x The color parameter dicatates the curve's color An optional Boolean parameter determines if the function renders immediately or requires the client to call the update method after a series of plots (defaults to True). """ # Move pen to starting position self.pen.up() self.pen.setposition(self.min_x, f(self.min_x)) self.pen.color(color) self.pen.down() # Iterate over the range of x values for min_x <= x < max_x x = self.min_x while x < self.max_x: self.pen.setposition(x, f(x)) x += self.x_increament # Next x if update: self.screen.update() def plot_data(self, data, color, update=True): """ (Plotter, list, str, bool) -> turtle Plots the curve (x, y) pairs of values in data_list. A parameter <color> specifies the curve’s color. An optional Boolean parameter determines if the function renders immediately or requires the client to call the update method after a series of plots (defaults to True). """ self.pen.up() self.pen.setposition(data[0][0], data[0][1]) self.pen.color(color) self.pen.down() # Plot the points in th data set for x, y in data: self.pen.setposition(x, y) if update: self.screen.update() def update(self): """ (Plotter) -> turtle Draws any pending actions to the screen """ self.screen.update() def setcolor(self, color): """ (Plotter, str) -> turtle Sets the current drawing color. """ self.pen.color(color) def onclick(self, fun): """ (Plotter, func) -> turtle Assigns a callback function that the frame should call when the user clicks the mouse button when the pointer is over the plotter window. The function <fun> must accept two integer parameters that represent the (x, y) location of the mouse when the click occurred """ self.screen.onclick(fun) def interact(self): """ (Plotter) -> turtle Sets the plotter to interactive mode, enabling the user to provide mouse and keyboard input. """ self.screen.mainloop()
window.setup(1200 + 3, 800 + 3) window.bgpic(os.path.join(BASE_PATH, "images", "background.png")) window.screensize(1200, 800) # window.tracer(n=2, delay=0) # инициализируем список для хранения объектов ракет: missiles = [] # Запускаем вражеские ракеты: for i in range(1, randint(2, N + 1)): fire_missile(x=BASE_X, y=BASE_Y, pos_x=randint(-600, 600), pos_y=400) # главный цикл игры: while True: window.update() window.onclick(fire_missile) for missile in missiles: if missile.state == 'launched': missile.forward(4) if missile.distance(x=missile.target[0], y=missile.target[1]) < 20: missile.state = 'explode' missile.shape('circle') elif missile.state == 'explode': missile.radius += 1 if missile.radius > 5: missile.clear() missile.hideturtle() missile.state = 'dead' else: missile.shapesize(missile.radius)
class Plotter: """ A plotter object provides a graphical window for plotting data and mathematical functions. """ def __init__(self, width, height, min_x, max_x, min_y, max_y): """ Initializes the plotter with a window that is width wide and height high. Its x-axis ranges from min_x to max_x, and its y-axis ranges from min_y to max_y. Establishes the global beginning and ending x values for the plot and the x_increment value. Draws the x- and y-axes. """ self.pen = Pen() # The plotter object's pen self.screen = Screen() # The plotter object's screen self.pen.speed(0) # Speed up rendering self.screen.tracer(0, 0) # Do not draw pen while drawing # Establish global x and y ranges self.min_x, self.max_x = min_x, max_x self.min_y, self.max_y = min_y, max_y # Set up window size, in pixels self.screen.setup(width=width, height=height) # Set up screen size, in pixels self.screen.screensize(width, height) self.screen.setworldcoordinates(min_x, min_y, max_x, max_y) # x-axis distance that corresponds to one pixel in window distance self.x_increment = (max_x - min_x)/width self.draw_grid(20) self.draw_axes() self.screen.title("Plot") self.screen.update() def __del__(self): """ Called when the client no longer uses the plotter object. """ print("Done plotting") def draw_axes(self, grid=False): """ Draws the x and y axes within the plotting window. The grid parameter controls the drawing of accessory horizontal and vertical lines. """ if grid: self.draw_grid(20) self.pen.hideturtle() # Make pen invisible prev_width = self.pen.width() self.pen.width(2) # Draw x axis self.pen.color('black') self.draw_arrow(self.min_x, 0, self.max_x, 0) # Draw y axis self.draw_arrow(0, self.min_y, 0, self.max_y) self.pen.width(prev_width) def draw_grid(self, n): """ Draws horizontal and vertical accessory reference coordinate lines on the plot. Parameter n controls the frequency of the reference lines. """ self.pen.up() #self.pen.setposition(self.min_x, self.min_y) inc = (self.max_x - self.min_x)/n self.pen.color("lightblue") x = self.min_x while x <= self.max_x: self.pen.setposition(x, self.min_y) self.pen.down() self.pen.setposition(x, self.max_y) self.pen.up() x += inc # Next x inc = (self.max_y - self.min_y)/n y = self.min_y while y <= self.max_y: self.pen.setposition(self.min_x, y) self.pen.down() self.pen.setposition(self.max_x, y) self.pen.up() y += inc # Next y def draw_arrow(self, x1, y1, x2, y2): """ Draws an arrow starting at (x1, y1) and ending at (x2, y2). """ # Draw arrow shaft self.pen.up() self.pen.setposition(x1, y1) # Move the pen starting point self.pen.down() # Draw line bottom to top self.pen.setposition(x2, y2) # Move the pen starting point # Draw arrow head dy = y2 - y1 dx = x2 - x1 angle = atan2(dy, dx) *180/pi self.pen.setheading(angle) self.pen.stamp() def plot_function(self, f, color, update=True): """ Plots function f on the Cartesian coordinate plane established by initialize_plotter. Plots (x, f(x)), for all x in the range min_x <= x < max_x. The color parameter dictates the curve's color. """ # Move pen to starting position self.pen.up() self.pen.setposition(self.min_x, f(self.min_x)) self.pen.color(color) self.pen.down() # Iterate over the range of x values for min_x <= x < max_x x = self.min_x while x < self.max_x: self.pen.setposition(x, f(x)) x += self.x_increment # Next x if update: self.screen.update() def plot_data(self, data, color, update=True): """ Plots the (x, y) pairs of values in the data list. The curve's color is specified by the color parameter. """ # Move pen to starting position self.pen.up() self.pen.setposition(data[0][0], data[0][1]) self.pen.color(color) self.pen.down() # Plot the points in the data set for x, y in data: self.pen.setposition(x, y) if update: self.screen.update() def update(self): """ Draws any pending plotting actions to the screen. """ self.screen.update() def setcolor(self, color): """ Sets the current drawing color. """ self.pen.color(color) def onclick(self, fun): """ This method assigns a function to call when the user clicks the mouse over the plotting window. The function must accept two integer parameters that represent the (x, y) location of the mouse when the click occurred. """ self.screen.onclick(fun) def interact(self): """ Places the plotting object in interactive mode so the user can provide input via the mouse or keyboard. """ self.screen.mainloop()