class Race(): def __init__(self): super().__init__() self.screen = Screen() self.screen.screensize(500, 500) self.turtles = [] self.last_turtle_position = -300 self.last_turtle_color = 0 def new_turtle(self): t = RaceTurtle() t.penup() t.setx(self.last_turtle_position) self.last_turtle_position += 100 t.sety(-200) t.speed('slow') self.turtles.append(t) return t def stop_race(self, winner): winner.celebrate() def run(self): while True: for t in self.turtles: if not t.race_move(): self.stop_race(t) self.screen.mainloop()
def kresli_vezu(): W = 500 H = 500 d = 5 win = Screen() win.screensize(W, H) t = Turtle() t.speed(1000) def obdlz(t, w, h): t.pendown() t.forward(d * w / 2) t.left(90) t.forward(d * h) t.left(90) t.forward(d * w) t.left(90) t.forward(d * h) t.left(90) t.forward(d * w / 2) t.left(90) t.penup() t.forward(d * h) t.right(90) s = 32 # mocniny dvojky! w = 1 while s > 0: s = s / 2 w = w * 2 obdlz(t, s, w) win.mainloop()
def draw(_sent,_angle): step=8 angle=_angle turtle=Turtle() turtle.hideturtle() turtle.speed(0) screen=Screen() screen.screensize(2000,1500) turtle.lt(90) # turtle.onclick(turtle.update()) for char in _sent: if (char is 'F' or char is 'A' or char is 'B'): turtle.pd() turtle.fd(step) elif(char is '-'): turtle.rt(angle) elif(char is '+'): turtle.lt(angle) elif(char is 'f'): turtle.pu() turtle.fd(step) elif(char is '['): turtleStack.push(turtle.heading()) turtleStack.push(turtle.pos()) elif(char is ']'): turtle.pu() turtle.setposition(turtleStack.pop()) turtle.setheading(turtleStack.pop()) turtle.pd() elif(char is '0'): turtle.fd(step/2) screen.exitonclick()
def main(): global s, sun s = Screen() s.setup(800, 600, 50, 50) s.screensize(750, 550) createPlanetShape() ## setup gravitational system s.setworldcoordinates(-hfw*4/3, -hfw, hfw*4/3, hfw) gs = GravSys() sun = Star(mS, Vec2D(0.,0.), Vec2D(0.,0.), gs, "circle") sun.color("yellow") sun.turtlesize(1.8) sun.pu() earth = Star(mE, Vec2D(rE,0.), Vec2D(0.,vE), gs, "planet") earth.pencolor("green") earth.shapesize(0.8) mercury = Star(mME, Vec2D(0., perihelME), Vec2D(-perihelvME, 0), gs, "planet") mercury.pencolor("blue") mercury.shapesize(0.5) venus = Star(mVE, Vec2D(-rVE, 0.), Vec2D(0., -vVE), gs, "planet") venus.pencolor("blue") venus.shapesize(0.65) mars = Star(mMA, Vec2D(0., -rMA), Vec2D(vMA, 0.), gs, "planet") mars.pencolor("blue") mars.shapesize(0.45) gs.init() gs.start() return "Done!"
def gen_screen(width, height, color=None): screen = Screen() if not color: screen.screensize(width, height) else: screen.screensize(width, height, color) return screen
class Alphabet(Turtle): ''' Alphabet drawing base class. Use Upper or Lower to actually draw. ''' def __init__(self, scale=100, pointer_on=False, *args, **kwargs): super().__init__(*args, **kwargs) self.scale = scale self.screen = Screen() self._starting_x = -((self.screen.screensize()[0] * .9)) self._starting_y = ((self.screen.screensize()[1] * .6)) self.move_without_draw(self._starting_x, self._starting_y) # set pointer off by default if not pointer_on: self.ht() def move_without_draw(self, x, y): self.pu() self.setpos(x, y) self.pd() def _set_next_letter_start(self, max_x, y): new_x = max_x + abs(max_x * .05) self.move_without_draw(new_x, y) self.setheading(0.0)
class Drawer: def __init__(self, amount: int): self.screen = Screen() self.screen.bgcolor("black") self.screen.screensize(canvwidth=512, canvheight=512) self.w = self.screen.window_width() self.h = self.screen.window_height() t = Turtle() draw_background(t) atexit.register(self.save) self.pointers = [Pen(self.w, self.h) for _ in range(amount)] def save(self): print("SAVING!!!!!!!!!") # get the current screen ts = self.pointers[0].t1.getscreen() # save the drawing to a post script ts.getcanvas().postscript(file="art_save.eps") def start(self): while True: for i in self.pointers: i.draw() turtle.update()
def configurar(valores_x, valores_y, lista_de_datos, color, tiempo=3): """Esta función configura las tortugas y luego dibuja. Recibe una lista con los valores del eje X, una lista con los valores del eje Y, y una lista con los valores de los datos a dibujar.""" # Defino la pantalla para que sea scrollable screen = Screen() width, height = screen.screensize() screen.screensize(width * base, height * base) # Definir pinceles tortuga_en_X = turtle.Pen() tortuga_en_Y = turtle.Pen() tortuga_graficar = turtle.Pen() tortuga_graficar_lineasPunteadas = turtle.Pen() #Aumentar velocidad de la tortuga tortuga_en_X.speed(0) tortuga_en_Y.speed(0) tortuga_graficar_lineasPunteadas.speed(0) # Ocultar tortuga tortuga_graficar.hideturtle() tortuga_graficar_lineasPunteadas.hideturtle() # Levantar pincel tortuga_en_X.up() tortuga_en_Y.up() tortuga_graficar.up() tortuga_graficar_lineasPunteadas.up() # Posicionar tortuga global initPosX """Variable global = Visible/utilizable desde cualquier ambito del programa. Si no se especifica como global se la considera local. Variable local = Visible/Utilizable solo en el bloque donde se crea """ initPosX -= 20 * len(lista_de_datos) tortuga_en_X.setpos(initPosX, initPosY) tortuga_en_Y.setpos(initPosX, initPosY) tortuga_graficar.setpos(initPosX, initPosY) tortuga_graficar_lineasPunteadas.setpos(initPosX, initPosY) # Dibujar eje x eje_x(tortuga_en_X, valores_x) # Dibujar eje y eje_y(tortuga_en_Y, valores_y) # Graficar barras tortuga_graficar.color(color) # Asigno el color con el que quiero graficar graficar(tortuga_graficar, lista_de_datos) # Graficar lineas punteadas graficar_lineas(tortuga_graficar_lineasPunteadas, valores_x, valores_y) tkinter.mainloop(30000000) time.sleep(tiempo)
def blank_image(self, l=None, w=None, bg=None, mode=None): if l is None: l = self.length if w is None: w = self.width if bg is None: bg = self.bg if mode is None: mode = self.mode screen = Screen() screen.setup(width=l, height=w, startx=0, starty=0) screen.screensize(l, w) screen.bgcolor(*bg) screen.colormode(mode) screen.delay(0) return screen
def main(): # Dimensiones ventana ancho = 625 alto = 625 # Lectura de datos num_aprobados = int(input("Aprobados: ")) num_suspensos = int(input("Suspensos: ")) num_notables = int(input("Notables: ")) num_sobresalientes = int(input("Sobresalientes: ")) # Convirtiendo a porcentajes total = num_aprobados + num_notables + num_sobresalientes + num_suspensos aprobados = (num_aprobados * 100) / total suspensos = (num_suspensos * 100) / total notables = (num_notables * 100) / total sobresalientes = (num_sobresalientes * 100) / total # Inicializacion pantalla = Screen() pantalla.setup(ancho, alto) pantalla.screensize(ancho - 25, alto - 25) pantalla.setworldcoordinates(0, 0, 100, 100) tortuga = Turtle() tortuga.speed(0) tortuga.penup() tortuga.setheading(90) tortuga.forward(10) tortuga.setheading(0) tortuga.pendown() # Dibujando barras dibuja_barra(tortuga, aprobados, "aprobados", 10) reubica_tortuga(tortuga, 2, 10) dibuja_barra(tortuga, suspensos, "suspensos", 10) reubica_tortuga(tortuga, 2, 10) dibuja_barra(tortuga, notables, "notables", 10) reubica_tortuga(tortuga, 2, 10) dibuja_barra(tortuga, sobresalientes, "sobresalientes", 10) tortuga.hideturtle() pantalla.exitonclick()
def main(): # Titulos titSobre = "Sobresalientes" titApro = "Aprobados" titNotab = "Notables" titSuspen = "Suspensos" # Radio del circulo radio = 300 # Dimenciones de la ventana ancho = 625 alto = 625 # Lectura de datos suspensos = float(input("Cant. Suspensos: ")) aprobados = float(input("Cant. Aprobados: ")) notables = float(input("Cant. Notables: ")) sobresalientes = float(input("Cant. Sobresalientes: ")) # Convertimos a porcentajes los datos recibidos total_estudiantes = suspensos + aprobados + notables + sobresalientes suspensos = (suspensos * 100) / total_estudiantes aprobados = (aprobados * 100) / total_estudiantes notables = (notables * 100) / total_estudiantes sobresalientes = (sobresalientes * 100) / total_estudiantes # Inicialización pantalla = Screen() pantalla.setup(ancho, alto) pantalla.screensize(ancho - 25, alto - 25) tortuga = Turtle() tortuga.speed(0) # maxima velocidad dibuja_circulo(radio, tortuga) # Se dibuja la torta dibuja_pedazo(radio, suspensos, tortuga, titSuspen) dibuja_pedazo(radio, aprobados, tortuga, titApro) dibuja_pedazo(radio, notables, tortuga, titNotab) dibuja_pedazo(radio, sobresalientes, tortuga, titSobre) tortuga.hideturtle() # Salir cuando se haga click pantalla.exitonclick()
def main(): global s, sun s = Screen() s.setup(800, 600) s.screensize(750, 550) createPlanetShape() ## setup gravitational system s.setworldcoordinates(-4.e11, -3.e11, 4.e11, 3.e11) gs = GravSys() sun = Star(mS, Vec2D(0.,0.), Vec2D(0.,0.), gs, "circle") sun.color("yellow") sun.turtlesize(1.2) sun.pu() earth = Star(mE, Vec2D(rE,0.), Vec2D(0.,vE), gs, "planet") earth.pencolor("green") gs.init() gs.start() return "Done!"
def main(): global s, sun s = Screen() s.setup(800, 600) s.screensize(750, 550) createPlanetShape() ## setup gravitational system s.setworldcoordinates(-4.e11, -3.e11, 4.e11, 3.e11) gs = GravSys() sun = Star(mS, Vec2D(0., 0.), Vec2D(0., 0.), gs, "circle") sun.color("yellow") sun.turtlesize(1.2) sun.pu() earth = Star(mE, Vec2D(rE, 0.), Vec2D(0., vE), gs, "planet") earth.pencolor("green") gs.init() gs.start() return "Done!"
def main(): pantalla = Screen() ancho, alto = 425, 500 pantalla.setup(ancho, alto) pantalla.screensize(ancho - 25, alto - 25) # tortuga = Turtle() # dibujaCuadradosConcentricos(tortuga) # # # Opcional prueba # lado = int(input("Ingrese lado: ")) # trianguloEquilatero(tortuga, lado) # # # Posicionamiento absoluto # posicionamientoAbsoluto(tortuga) # # trianguloEquiSinLeftRightSeg() cuadradosConcentricosSinLeftRight() pantalla.exitonclick()
def main(): total_steps = int( input(f"How many steps the drunken will make? Type a number: ")) # borracho = RandomWalk() # borracho.walk() borracho = t.Turtle() borracho.width(4) borracho.speed(0) t.colormode(255) step_size = 15 for _ in range(total_steps): towards = choice([0, 270, 180, 90]) borracho.setheading(towards) borracho.pencolor(random_color) borracho.fd(step_size) screen = Screen() screen.screensize(600) screen.exitonclick()
def Start(): global t, creater, omega, score, direction, s, bodyParts, canMove, wait, point, started, SCORE_TIMER, DEAD t = Turtle('circle') t.pu() t.ht() t.shapesize(0.5) creater = Turtle('circle') creater.pu() creater.ht() creater.color('yellow') omega = False started = False s = Screen() s.tracer(False) s.screensize(500, 500) score = Turtle() score.ht() score.pu() score.goto(-325, 350) score.color('green') direction = (10, 0) point = None wait = True canMove = True DEAD = 0 SCORE_TIMER = 50 bodyParts = [] started = True score.clearstamps() # s.clearscreen() for x in range(3): t.goto(x * 10, 0) bodyParts.append((t.pos(), t.stamp()))
def ejercicio(): x1 = float(input("LÍMITE SUPERIOR: ")) x2 = float(input("LÍMITE INFERIOR: ")) puntos = int(input("CANTIDAD PUNTOS: ")) pantalla = Screen() pantalla.setup(825, 425) pantalla.screensize(800, 400) pantalla.setworldcoordinates(x1, -1, x2, 1) tortuga = Turtle() x = x1 dx = (x2 - x1) / puntos tortuga.penup() tortuga.goto(x, sin(x)) tortuga.pendown() while x <= x2: tortuga.goto(x, sin(x)) x += dx pantalla.exitonclick()
def main(): # screensize 参数分别为画布的宽(单位像素),高,背景颜色 canvas = Screen() canvas.screensize(800, 600, bg='wheat') # 画树 turtle.penup() turtle.goto(0,-120) turtle.speed(0) turtle.hideturtle() turtle.left(75) turtle.backward(100) # turtle.showturtle() turtle.pendown() turtle.color('brown') pos_lst, heart_size = draw_tree(150) # 画心 for pos, size in zip(pos_lst, heart_size): draw_heart(turtle, pos, size=size*0.8) # 落款 turtle.hideturtle() turtle.color('black','pink') turtle.up() turtle.goto(120,-160) turtle.speed(5) turtle.down() turtle.write('Best wishes to ?',font=('STliti',15, 'italic'), align="center") turtle.up() turtle.goto(120,-190) turtle.down() turtle.write('2020.05.20 from gdq', font=('STliti',12, 'italic'), align="center") # 点击图片退出 canvas.exitonclick()
def main() -> None: my_screen = Screen() my_screen.screensize(800, 640) matthew = Turtle() matthew.shape("turtle") matthew.speed(0) print(matthew) draw_circle(matthew) matthew.pu() matthew.right(90) matthew.forward(100) matthew.left(90) matthew.pd() draw_square_orbits(matthew, 5, 20) matthew.pu() matthew.right(90) matthew.forward(50) matthew.left(90) matthew.pd() draw_rectangle(matthew, 50, 20) my_screen.exitonclick()
from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.screensize(canvwidth=640, canvheight=640) screen.bgcolor("black") screen.tracer(0) paddle1 = Paddle([(-440, -30), (-440, -10), (-440, 10), (-440, 30)]) paddle2 = Paddle([(440, -30), (440, -10), (440, 10), (440, 30)]) ball = Ball() scoreboard = Scoreboard() screen.listen() screen.onkeypress(paddle1.down, "s") screen.onkeypress(paddle1.up, "w") screen.onkeypress(paddle2.down, "Down") screen.onkeypress(paddle2.up, "Up") game_is_on = True while game_is_on: screen.update() time.sleep(0.02) ball.move()
color='red') heading = calc_heading(x1=pos_x, y1=pos_y, x2=BASE_X, y2=BASE_Y) else: missile = Missile(x, y) heading = calc_heading(x1=pos_x, y1=pos_y, x2=x, y2=y) missile.pendown() missile.setheading(heading) missile.showturtle() missiles.append(missile) # создаем окно игры: window = Screen() 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:
from turtle import Screen, Turtle pantalla = Screen() pantalla.setup(425, 225) pantalla.screensize(400, 200) tortuga = Turtle() tortuga.forward(100) pantalla.exitonclick()
user_arrow) <= 65: # This checks if the arrow hits the turtle user_arrow.color("red") turtle.color("red") messagebox.showinfo( "Turtle Tag!", "You caught the Turtle in {0} clicks!\nYou Win!".format( click_counter), ) # \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)
#LIBRERÍAS NECESARIAS PARA LA EJECUCIÓN DEL PROGRAMA from turtle import Screen, Turtle from math import sqrt import sys try: # CONFIGURACIÓN INICIAL DE LA VENTANA EMERGENTE CON SUS RESPECTIVAS PROPIEDADES pantalla = Screen() pantalla.setup(1020, 1025) pantalla.screensize(1000, 1000) pantalla.setworldcoordinates(-500, -500, 500, 500) pantalla.delay(0) #VALORES NECESARIOS PARA CADA UNO DE LOS CUERPOS x1 = -200 y1 = -200 velocidad_x1 = 0.1 velocidad_y1 = 0 m1 = 20 # VALORES NECESARIOS PARA EL SEGUNDO CUERPO x2 = 200 y2 = 200 velocidad_x2 = -0.1 velocidad_y2 = 0 m2 = 20 x3 = 300 y3 = 300 velocidad_x3 = 2.1 velocidad_y3 = 0
from turtle import Turtle, Screen # библиотека содержит функцию `Screen` которая создаёт объект экрана # этот оъект позволяет нам общаться с окном которое открыло наша программа а так же с экраном компьютера. # это как мы увидим далее очень полезно. screen = Screen() gap = 60 step = 100 canvwidth, canvheight = screen.screensize() screen.setworldcoordinates(0 - gap, 0 - gap, (canvwidth*2 - gap), (canvheight*2 - gap)) predefined_shapes = ['arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'] turtles = [] for index, shape in enumerate(predefined_shapes): turtle = Turtle() turtle.penup() turtle.sety(gap*index) turtle.shape(shape) turtles.append(turtle) t = Turtle() t.home() t.left(150) t.begin_poly() for i in range(1, 4): t.fd(20) t.right(60)
from turtle import Turtle, Screen import random screen = Screen() screen.screensize(canvwidth=480, canvheight=360) all_turtles = [] colors = ['red', 'blue', 'green', 'yellow', 'orange'] y_cood = [-80, -40, 0, 40, 80] for i in range(5): new_turtle = Turtle(shape="turtle") new_turtle.penup() new_turtle.color(colors[i]) new_turtle.setposition(-350, y_cood[i]) all_turtles.append(new_turtle) user_bet = screen.textinput('place your bet', 'Which color will reaches finish line first') if user_bet.lower() in colors: is_race_on = True else: is_race_on = False print("Wrong color entered") while is_race_on: for turtle in all_turtles: #230 is 250 - half the width of the turtle. if turtle.xcor() > 290: is_race_on = False winning_color = turtle.pencolor()
r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) color = (r, g, b) return color for _ in range(200): tut.color(random_color()) tut.forward(30) tut.setheading(random.choice(directions)) # Press the green button in the gutter to run the script. if __name__ == '__main__': screen = Screen() screen.screensize(2000, 1500) screen.exitonclick() # See PyCharm help at https://www.jetbrains.com/help/pycharm/ # def draw_shape(num_sides): # angle = 360 / num_sides # for _ in range(num_sides): # tut.forward(100) # tut.right(angle) # # # for n in range(3, 11): # tut.color(random.choice(turtle_colors)) # draw_shape(n)
if nivel == 0: tortuga.forward(longitud) else: tortuga.right(45) dragon(tortuga, longitud / sqrt(2), nivel - 1) tortuga.left(90) nogard(tortuga, longitud / sqrt(2), nivel - 1) tortuga.right(45) def nogard(tortuga, longitud, nivel): if nivel == 0: tortuga.forward(longitud) else: tortuga.left(45) dragon(tortuga, longitud / sqrt(2), nivel - 1) tortuga.right(90) nogard(tortuga, longitud / sqrt(2), nivel - 1) tortuga.left(45) # Programa principal pantalla = Screen() pantalla.setup(500, 500) pantalla.screensize(500, 500) pantalla.setworldcoordinates(0, -350, 500, 150) tortuga = Turtle() tortuga.speed(0) dragon(tortuga, 400, 10) pantalla.exitonclick()
class TetrisBoard(object): def __init__(self, cols, rows): self.cols, self.rows = cols, rows self.screen = Screen() self.screen.screensize(BLOCKWIDTH*cols-50, BLOCKWIDTH*rows-50) self.screen.setup(BLOCKWIDTH*cols+12, BLOCKWIDTH*rows+12) self.screen.title("Turtle Tetris") self.screen.bgcolor("black") self.writer = Turtle() self.writer.ht() self.label = None self.grid = {} self.screen.tracer(False) for row in range(rows): for col in range(cols): self.grid[(col, row)] = TetrisTurtle(col, row) self.screen.tracer(True) self.brick = TetrisBrick(self) self.result = 0 self.LEVEL = 0.6 self.keybuffer = KeyBuffer(self.screen, ["Right", "Left", "Up", "Down", "space", "Escape"]) self.reset() self.screen.listen() self.t1 = time() def reset(self): self.result = 0 self.LEVEL = 0.600 self.screen.tracer(False) self.writer.clear() if self.label: self.writer.clearstamp(self.label) for x in range(COLUMNS): for y in range(ROWS): self.grid[(x,y)].fillcolor("") self.screen.tracer(True) self.state = "NEWBRICK" def blink(self, y, n=1): for _ in range(n): for color in ("white", "black"): self.screen.tracer(False) for x in range(COLUMNS): self.grid[(x,y)].pencolor(color) sleep(self.LEVEL/10.0) self.screen.tracer(True) def display_result(self): tb = self tb.writer.color("white", "gray20") tb.writer.shape("square") tb.writer.shapesize(5, 15) tb.writer.goto(-4 ,0) self.label = tb.writer.stamp() tb.writer.goto(-2,3) tb.writer.write(str(tb.result) + " rows!", align="center", font = ("Courier", 24, "bold") ) tb.writer.goto(-2,-22) tb.writer.write("New game : <spacebar>", align="center", font = ("Courier", 16, "bold") ) tb.writer.goto(-2,-42) tb.writer.write("Quit : <escape>", align="center", font = ("Courier", 16, "bold") ) def getcolor(self, col, row): return self.grid[(col, row)].fillcolor() def setcolor(self, col, row, color): return self.grid[(col, row)].fillcolor(color) def rowfree(self, row): return not any([self.getcolor(col, row) for col in range(COLUMNS)]) def rowfull(self, row): return all([self.getcolor(col, row) for col in range(COLUMNS)]) def cleanup(self, shp): try: ymax = max([y for (x,y) in shp]) except ValueError: self.state = "FINIS" return currenty = ymax while currenty > 0: if self.rowfull(currenty): self.blink(currenty, 2) self.result += 1 if self.result == 8: self.LEVEL = 0.4 elif self.result == 20: self.LEVEL = 0.25 y = currenty while True: self.screen.tracer(False) for c in range(COLUMNS): self.setcolor(c, y, self.getcolor(c, y-1)) self.screen.tracer(True) if self.rowfree(y): break else: y -= 1 else: currenty -= 1 tetris.state = "NEWBRICK" def run(self): tb = self b = self.brick ### actions to be done unconditionally if tb.state == "NEWBRICK": if b.reset(): self.t1 = time() tb.state = "FALL" else: tb.state = "FINIS" t2 = time() if tb.state == "FALL" and t2 - self.t1 > self.LEVEL: b.down() b.apply("Step") self.t1 = t2 ### actions bound to key events key = self.keybuffer.getkey() if key: if tb.state == "FALL": if key == "Left": b.shiftleft() elif key == "Right": b.shiftright() elif key == "Down": b.drop() tb.state = "CLEANUP" elif key == "Up": b.turn() elif key == "space": tb.state = "BREAK" b.apply(key) elif tb.state == "BREAK": if key == "space": tb.state = "FALL" elif tb.state == "ADE": if key == "space": tb.reset() tb.state = "NEWBRICK" elif key == "Escape": tb.screen.bye() if tb.state == "CLEANUP": tb.cleanup(b.shape1) if tb.state == "FINIS": tb.display_result() tb.state = "ADE" self.screen.ontimer(self.run, 100)
from turtle import Turtle, Screen from random import choice from time import sleep from queue import SimpleQueue w: int w, h = (853, 480) wn = Screen() wn.screensize(w, h) wn.bgcolor("#d3d3d3") #estado da sala Room_state = {"Limpo": "#FFFFFF", "Sujo": "#FF0000"} cleaned = 0 def filler(t, color, delay=1.5, vacclean=False): global cleaned t.fillcolor(color) t.penup() if color == Room_state['Limpo']: sleep(delay) #To avoid instant cleaning if vacclean: cleaned += 1 t.begin_fill() t.circle(130) t.end_fill() def setup():
from turtle import Screen, Turtle from paddle import Paddle from ball import Ball import time from scoreboard import Scoreboard screen = Screen() divider = Turtle() screen.bgcolor("black") screen.screensize(800, 800) screen.tracer(0) screen.title("Pong") screen.listen() paddle1 = Paddle((-390, 0)) screen.onkey(paddle1.move_up, "w") screen.onkey(paddle1.move_down, "s") paddle2 = Paddle((390, 0)) screen.onkey(paddle2.move_up, "Up") screen.onkey(paddle2.move_down, "Down") screen.onkey(paddle2.move_up, "Up") screen.onkey(paddle2.move_down, "Down") divider.penup() ball = Ball((0, 0)) scoreboard = Scoreboard()
from turtle import Turtle, Screen import time from paddle import Paddle from ball import Ball from scoreboard import Scoreboard from screen_divider import ScreenDivider screen = Screen() screen.screensize(600, 600) screen.bgcolor("black") screen.title("The Pong Game") screen.tracer(0) screen.listen() screen_divider = ScreenDivider() paddle1 = Paddle("left") paddle2 = Paddle("right") ball = Ball() scoreboard1 = Scoreboard("left") scoreboard2 = Scoreboard("right") screen.update() screen.onkeypress(fun=paddle1.move_up, key="Up") screen.onkeypress(fun=paddle1.move_down, key="Down") screen.onkeypress(fun=paddle2.move_up, key="w") screen.onkeypress(fun=paddle2.move_down, key="s") game_on = True while game_on:
class MazeGraphics(object): def __init__(self, config): self.width = config.getValueAsInt("maze", "maze_size") self.height = config.getValueAsInt("maze", "maze_size") self.bg_color = config.getValue("maze", "bg_color") self.line_color = config.getValue("maze", "line_color") self.line_centroid_color = config.getValue("maze", "line_centroid_color") self.forward_centroid_color = config.getValue("maze", "forward_centroid_color") self.reverse_centroid_color = config.getValue("maze", "reverse_centroid_color") self.path_color = config.getValue("maze", "path_color") self.screen = Screen() self.setupTurtle(self.width, self.height) def setupTurtle(self, width, height): self.screen.tracer(False) self.screen.screensize(width, height) # some basic turtle settings self.screen.setworldcoordinates(-1, -1, width + 1, height + 1) self.screen.title("Random Turtle Maze") self.screen.bgcolor(self.bg_color) self.screen.delay(None) self.designer = Turtle(visible=False) def drawGrid(self): for i in xrange(0, self.width + 1): self.drawXLines(i, self.width, self.line_color) for i in xrange(0, self.height + 1): self.drawYLines(i, self.width, self.line_color) self.screen.update() def drawXLines(self, position, width, color): self.drawLines(position, 0, width, color, 90) def drawYLines(self, position, width, color): self.drawLines(0, position, width, color, 0) def drawLines(self, xPosition, yPosition, width, color, heading): self.designer.up() self.designer.setposition(xPosition, yPosition) self.designer.color(color) self.designer.down() self.designer.setheading(heading) self.designer.forward(width) self.designer.up() def drawCentroid(self, cell, color): """ Draw a centroid for animation purposes but then overwrite it. """ self.designer.setposition(cell.centroid) self.designer.dot(5, color) self.screen.update() self.designer.dot(5, self.bg_color) def removeWall(self, posx, posy, heading, color): """ We tear down walls to build the maze """ self.designer.up() self.designer.setposition(posx, posy) self.designer.down() self.designer.color(color) self.designer.setheading(heading) self.designer.forward(1) self.designer.up() self.screen.update() def drawPath(self, cell1, cell2): """ This draws a line for the solution as it's worked out. """ self.designer.setposition(cell1.centroid) self.designer.color(self.path_color) direction = self.getDirection(cell1, cell2) if direction == "N": self.designer.setheading(90) self.designer.down() self.designer.forward(1) self.designer.up() elif direction == "S": self.designer.setheading(270) self.designer.down() self.designer.forward(1) self.designer.up() elif direction == "W": self.designer.setheading(0) self.designer.down() self.designer.forward(1) self.designer.up() elif direction == "E": self.designer.setheading(0) self.designer.down() self.designer.backward(1) self.designer.up() self.drawCentroid(cell2, self.line_centroid_color) self.screen.update() def getDirection(self, currCell, nextCell): direction = None if nextCell.x < currCell.x: direction = "E" elif nextCell.x > currCell.x: direction = "W" elif nextCell.y < currCell.y: direction = "S" elif nextCell.y > currCell.y: direction = "N" return direction