def main(): swarmSize = 100 t = Turtle() win = Screen() win.setworldcoordinates(-600, -600, 600, 600) t.speed(10) t.hideturtle() t.tracer(15) for i in range(swarmSize): if random.randrange(100) == 0: LeaderFish() else: FocalFish() for i in range(5): Obstacle() for turn in range(1000): for schooler in Schooler.swarm: schooler.getNewHeading() for schooler in Schooler.swarm: schooler.setHeadingAndMove() win.exitonclick()
def main(): # creating a window window = Screen() # window.bgcolor("orange") remo = Turtle() remo.shape("turtle") remo.color("green") remo.speed(50) for i in range(36): remo.circle(100) remo.left(10) remo.color("red") for i in range(36): remo.circle(80) remo.left(10) remo.color("yellow") for i in range(36): remo.circle(60) remo.left(10) window.exitonclick()
def main(): global s at = clock() s = Screen() s.bgcolor("black") s.tracer(36, 0) mn_eck(36, 19) et = clock() return "Laufzeit: %.3f sec" % (et - at)
class World(object): def __init__(self, index, size_x, size_y): self.index = index self.canvas = Screen() self.canvas.setup(size_x, size_y) def show_world(self): #self.canvas.ontimer(god.slowly_kill_humans(), 100) self.canvas.exitonclick()
def main(): global s, t s = Screen() s.bgcolor("gray10") t = Turtle(visible=False, shape="square") t.pu() t.speed(0) s.tracer(False) ta = clock() recsquare(256, 0.5, colors) tb = clock() return "{0:.2f}sec.".format(tb-ta)
class MHManager(Turtle): """Special Turtle, perform the task to manage the Moorhuhn-GUI. """ def __init__(self, w, h): Turtle.__init__(self, visible=False) self.screen = Screen() self.screen.setup(w, h) self.speed(0) self.penup() self.goto(-WINWIDTH//2 + 50, -WINHEIGHT//2 + 20) self.pencolor("yellow") def message(self, txt): """Output text to graphics window. """ self.clear() self.write(txt, font=("Courier", 18, "bold"))
def main(): global screen, red, green, blue screen = Screen() screen.delay(0) screen.setworldcoordinates(-1, -0.3, 3, 1.3) red = ColorTurtle(0, .5) green = ColorTurtle(1, .5) blue = ColorTurtle(2, .5) setbgcolor() writer = Turtle() writer.ht() writer.pu() writer.goto(1,1.15) writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic"))) return "EVENTLOOP"
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 main(): global screen screen = Screen() screen.colormode(255) p = Turtle() p.ht() screen.tracer(75,0) u = doit1(6, Turtle(undobuffersize=1)) s = doit2(7, Turtle(undobuffersize=1)) t = doit3(5, Turtle(undobuffersize=1)) v = doit4(6, Turtle(undobuffersize=1)) w = doit5(5, Turtle(undobuffersize=1)) a = clock() while True: done = 0 for b in u,s,t,v,w: try: next(b) except: done += 1 if done == 5: break screen.tracer(1,10) b = clock() return "runtime: {0:.2f} sec.".format(b-a)
def draw_art(): window = Screen() window.bgcolor('cyan') angie = Turtle() angie.shape('turtle') angie.color('blue') angie.speed(2000) # angie.left(105) for j in range(80): angie.right(5) draw_rhombus(angie, 100) angie.left(90) angie.forward(300) # Close window window.exitonclick()
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 main(): swarmSize = 50 t = Turtle() win = Screen() win.setworldcoordinates(-600,-600,600,600) t.speed(10) t.hideturtle() t.tracer(15) for i in range(swarmSize): FocalFish() for turn in range(300): for schooler in Schooler.swarm: schooler.getNewHeading() for schooler in Schooler.swarm: schooler.setHeadingAndMove() win.exitonclick()
def main(): swarmSize = 30 t = Turtle() win = Screen() win.setworldcoordinates(-600,-600,600,600) t.speed(10) t.tracer(15) t.hideturtle() for i in range(swarmSize): Schooler() #for turn in range(1000): while True: try: for schooler in Schooler.swarm: schooler.moveAllBoidsToNewPositions() except KeyboardInterrupt: break win.exitonclick()
def main(): ## create compound yellow/blue turtleshape for planets s = Screen() s.reset() s.tracer(0, 0) t = Turtle() t.ht() t.pu() t.fd(6) t.lt(90) t.begin_poly() t.circle(6, 180) t.end_poly() m1 = t.get_poly() t.begin_poly() t.circle(6,180) t.end_poly() m2 = t.get_poly() planetshape = Shape("compound") planetshape.addcomponent(m1,"orange") planetshape.addcomponent(m2,"blue") s.register_shape("planet", planetshape) s.tracer(1,0) ## setup gravitational system gs = GravSys() sun = Star(1000000, Vec(-250,0), Vec(0,-0.35), gs, "circle") sun.color("yellow") sun.pensize(1.8) sun.pu() earth = Star(5000, Vec(450,0), Vec(0,70), gs, "planet") earth.pencolor("green") earth.shapesize(0.8) rm=12.0583 vm=(8.0*5000/rm)**.5 moon = Star(1, Vec(450+rm,0), Vec(0,70+vm), gs, "planet") moon.pencolor("blue") moon.shapesize(0.5) 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(-3.e11, -3e11, 3.e11, 3e11) 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) moon = Star(mM, Vec2D(rE+rM,0.), Vec2D(0.,vE+vM), gs, "planet") moon.pencolor("blue") moon.shapesize(0.5) #gs.init() gs.start() return "Done!"
def principal(): janela = Screen() janela.setup(800,600) janela.title('Digimon, digitais, Digimon são campeões!') janela.bgcolor('white') carregaimagens('personagens', janela) carregaimagens ('digimons', janela) carregaimagens('digimonftowners', janela) carregaimagens('fundos', janela) cria_personagens() abertura(janela) ato2(janela) ato3(janela) ato4(janela) ato5(janela) ato6(janela) ato7(janela) ato8(janela) #finale(janela) fechamento(janela) debora_animacao(janela)
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 createPlanetShape(): s = Screen() s.tracer(0, 0) t = Turtle() t.ht() t.pu() t.fd(6) t.lt(90) t.begin_poly() t.circle(6, 180) t.end_poly() m1 = t.get_poly() t.begin_poly() t.circle(6, 180) t.end_poly() m2 = t.get_poly() planetshape = Shape("compound") planetshape.addcomponent(m1, "orange") planetshape.addcomponent(m2, "blue") s.register_shape("planet", planetshape) s.tracer(True, 0)
def main(): s = Screen() s.bgcolor("black") p=Turtle() p.speed(0) p.hideturtle() p.pencolor("red") p.pensize(3) s.tracer(36,0) at = clock() mn_eck(p, 36, 19) et = clock() z1 = et-at sleep(1) at = clock() while any(t.undobufferentries() for t in s.turtles()): for t in s.turtles(): t.undo() et = clock() return "runtime: %.3f sec" % (z1+et-at)
def main(): s = Screen() s.bgcolor("black") p=Turtle() p.speed(0) p.hideturtle() p.pencolor("red") p.pensize(3) s.tracer(36,0) at = clock() mn_eck(p, 36, 19) et = clock() z1 = et-at sleep(1) at = clock() while any([t.undobufferentries() for t in s.turtles()]): for t in s.turtles(): t.undo() et = clock() return "Laufzeit: {0:.3f} sec".format(z1+et-at)
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 Screen from playertur import PlayerTur from cars import Car from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=800, height=600) screen.title("Welcome to turtle crossing game") screen.listen() screen.tracer(0) tim = PlayerTur() car = Car() scoreboard = Scoreboard() screen.onkey(fun=tim.move_up, key="Up") game_on = True while game_on: time.sleep(car.speed) screen.update() car.move() car.detect_edge() # Detect collision for rectangle in car.cars: if tim.distance(rectangle) < 28 and rectangle.xcor() >= 0: scoreboard.game_over()
from turtle import Turtle, Screen amy = Turtle() amy.shape('turtle') amy.color('purple') amy.forward(100) my_screen = Screen() my_screen.exitonclick()
for p in plist: p.forward(l) q = p.clone() p.left(a) q.right(a) lst.append(p) lst.append(q) for x in tree(lst, l * f, a, f): yield None def maketree(): p = Turtle() p.pencolor("#697C82") p.setundobuffer(None) p.hideturtle() p.speed(0) p.tracer(30, 0) p.left(90) p.penup() p.forward(-210) p.pendown() t = tree([p], 200, 65, 0.6375) for x in t: pass s = Screen() maketree() print s.getcanvas().postscript()
from turtle import Screen from paddle import Paddle from ball import Ball import time from playsound import playsound from scoreboard import Scoreboard # Global Variables BG_COLOR = "black" screen = Screen() screen.setup(width=800, height=600) screen.bgcolor(BG_COLOR) screen.title("Pong Game") screen.tracer(0) screen.listen() r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) ball = Ball() scoreboard = Scoreboard() screen.onkeypress(r_paddle.go_up, "Up") screen.onkeypress(r_paddle.go_down, "Down") screen.onkeypress(l_paddle.go_up, "w") screen.onkeypress(l_paddle.go_down, "s") is_game_on = True while is_game_on:
#!/usr/bin/python # coding: utf-8 from turtle import Screen from turtle import Turtle s = Screen() s.bgcolor('black') ikea_lys = Turtle() bestemors_lys = Turtle() ikea_lys.shape('circle') ikea_lys.color('black') ikea_lys.shapesize(3) bestemors_lys.shape('circle') bestemors_lys.color('black') bestemors_lys.shapesize(3) class Lampe(): lyser = False turtle = None def lag_skilpadde(self): """ Lager en egen skilpadde for denne lamen.""" self.turtle = Turtle() self.turtle.penup() self.turtle.hideturtle() # Gult lys når vi lyser.
turtle.left(angle) hilbert_curve(n - 1, turtle, -angle) turtle.forward(1) turtle.right(angle) hilbert_curve(n - 1, turtle, angle) turtle.forward(1) hilbert_curve(n - 1, turtle, angle) turtle.right(angle) turtle.forward(1) hilbert_curve(n - 1, turtle, -angle) turtle.left(angle) depth = 5 #int(sys.argv[1]) size = 2**depth screen = Screen() screen.setworldcoordinates(0, 0, size, size) yertle = Turtle('turtle') yertle.speed('fastest') yertle.penup() yertle.goto(0.5, 0.5) yertle.pendown() hilbert_curve(depth, yertle) yertle.hideturtle() screen.exitonclick()
from random_walk_class import RandomWalk from polygon_class import Polygon import turtle from turtle import Screen from datetime import datetime colors = ['#FA9579', '#654062', '#65D6CE', '#FFE9D6'] wn = Screen().setup(300, 300) for i in range(8): for col in colors: turtle.color(col) random_walk = RandomWalk(turtle, 50, 300, 300) random_walk.draw_random_walk() #for x in range(3, 100): # turtle.speed(100) # if x%2 == 0: # shape = Polygon(10,x) # shape.draw() # else: # shape = Polygon(10,x, 'left') # shape.draw() now = datetime.today().strftime('%Y-%m-%d-%H:%M:%S') turtle.getcanvas().postscript( file=f"step_4_18_300_300_pen_up_0/random_walk_{now}.eps") random_walk.destroy()
""" Event listeners. Function as an input """ from turtle import Turtle, Screen tim = Turtle() screen = Screen() def move_forward(): tim.forward(20) screen.listen() screen.onkey(key="space", fun=move_forward) screen.exitonclick()
from turtle import Turtle, Screen from random import seed, randint seed() DELAY = 100 # milliseconds # setup the output window picSize = (400, 600) playGround = Screen() playGround.screensize(*picSize) # setup the turtles bob = Turtle(shape='turtle', visible=False) bob.penup() bob.color('red') bob.speed('slow') jeff = Turtle(shape='turtle', visible=False) jeff.penup() jeff.color('blue') jeff.speed('normal') x_quadrant = -picSize[0] // 2, picSize[0] // 2 y_quadrant = -picSize[1] // 2, picSize[1] // 2 # find random positions for the turtles jeff_xy = randint(*x_quadrant), randint(*y_quadrant) bob_xy = randint(*x_quadrant), randint(*y_quadrant) # find a point to move bob to and rotate towards its target location
# Throw rocks in a ocean from turtle import Turtle, Screen print("Creating an Ocean") ocean = Screen() ocean.title("Let's find Splash") print("Creating a drawing turtle") bob = Turtle() bob.color('purple') bob.speed(0) def splash(x, y): print("splash at", x, y) bob.color('purple') bob.goto(x, y) bob.circle(50) ocean.onclick(splash) bob.ondrag(drag, btn=2) ocean.listen()
""" Day 020 of the 100 Days of Code course Author: Wayne Kwiat Date: 1/22/2021 """ from turtle import Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Welcome to the snake game!") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") game_is_on = True while game_is_on: screen.update() time.sleep(0.1)
def move_right(): canvas.xview_scroll(1, "units") turtle.setx(turtle.xcor() + MAGNIFICATION) def move_up(): canvas.yview_scroll(-1, "units") turtle.sety(turtle.ycor() + MAGNIFICATION) def move_down(): canvas.yview_scroll(1, "units") turtle.sety(turtle.ycor() - MAGNIFICATION) screen = Screen() width, height = screen.screensize() screen.screensize(width * MAGNIFICATION, height * MAGNIFICATION) canvas = screen.getcanvas() canvas.config(xscrollincrement=str(MAGNIFICATION)) canvas.config(yscrollincrement=str(MAGNIFICATION)) turtle.width(MAGNIFICATION) turtle.resizemode('auto') screen.onkey(move_left, "Left") screen.onkey(move_right, "Right") screen.onkey(move_up, "Up") screen.onkey(move_down, "Down") screen.listen()
from turtle import Screen, Turtle from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("Pong") screen.tracer(0) r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) ball = Ball() scoreboard = Scoreboard() screen.listen() screen.onkey(r_paddle.go_up, "Up") screen.onkey(r_paddle.go_down, "Down") screen.onkey(l_paddle.go_up, "w") screen.onkey(l_paddle.go_down, "s") game_is_on = True while game_is_on: time.sleep(ball.move_speed) screen.update() ball.move() if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce_y()
from turtle import Turtle, Screen import time baseX = -75 baseY = -75 gridlength = 50 boardState = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] buttonStr = ["Play Again", "Exit"] buttonLoc = [] al = Turtle() al.shape("turtle") screen = Screen() al.speed(7) playerOneTurn = True gameOver = False errorText = "" def createBoard(): """Establish the backend and frontend boards""" global boardState global playerOneTurn global gameOver boardState = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] playerOneTurn = True gameOver = False for x in range(3): for y in range(3): __createBox(x, y) __createLabels() __createButtons()
""" Simple version of the classic Asteroids video game. Implemented with Turtle graphics from Python standard turtle module. Adapted from "Python Programming Fundamentals" by Kent Lee http://knuth.luther.edu/~leekent/IntroToComputing/ """ from time import sleep from turtle import Turtle, Screen import turtle import random import math screen = Screen() screenMinX = -screen.window_width() / 2 screenMinY = -screen.window_height() / 2 screenMaxX = screen.window_width() / 2 screenMaxY = screen.window_height() / 2 screen.setworldcoordinates(screenMinX, screenMinY, screenMaxX, screenMaxY) screen.bgcolor("black") offscreen_x = screenMinX - 100 t = Turtle() t.penup() t.ht() t.speed(0) t.goto(0, screenMaxY - 20)
from turtle import Turtle from turtle import Screen bert = Turtle() screen = Screen() def draw_shapes(): bert.penup() bert.left(90) bert.forward(100) bert.right(90) bert.left(180) bert.forward(100) bert.pendown() bert.left(180) # Triangle for _ in range(3): bert.forward(100) bert.right(120) # Square for _ in range(4): bert.color('red') bert.forward(100) bert.right(90) # Pentagon for _ in range(5): bert.color('blue')
class PongGame: def __init__(self): # Create the Screen Object self.screen = Screen() self.screen.setup(SCREEN_XCOR, SCREEN_YCOR) self.screen.bgcolor("black") # Create Screen Cursor; Draw Pong Game Layout self.screen_cursor = Turtle() self.screen_cursor.ht() self.establish_game_layout() self.ball_speed = 0.07 self.screen.tracer(0) # Create Score Cursor; Visualize and Update the Score self.score_cursor = Turtle() self.score_cursor.ht() self.score_cursor.color("white") self.score_cursor.speed("fastest") self.score_cursor.pu() self.scores = [0, 0] self.update_players_score() # Create Paddles Objects self.rt_paddle = Turtle() self.lt_paddle = Turtle() self.init_paddle(LT_PADDLE_POSITION, RT_PADDLE_POSITION) # Create Ball Object self.ball = Turtle() self.x_move = 10 self.y_move = 10 self.init_ball() def establish_game_layout(self): self.screen.title("Pong Game") self.screen_cursor.color("white") self.screen_cursor.pensize(3) self.screen_cursor.penup() self.screen_cursor.speed("fastest") # Type Game Title self.screen_cursor.setposition(x=0, y=(SCREEN_YCOR/2 - Y_MARGIN/1.3)) self.screen_cursor.write("- Pong Game -", move=False, align="center", font=("Calibri", 30, "bold")) # Draw the Pong Table Margins self.screen_cursor.setposition((-GAME_XCOR/2), (GAME_YCOR/2)) self.screen_cursor.pd() self.screen_cursor.fd(GAME_XCOR) self.screen_cursor.rt(90) self.screen_cursor.fd(GAME_YCOR) self.screen_cursor.rt(90) self.screen_cursor.fd(GAME_XCOR) self.screen_cursor.rt(90) self.screen_cursor.fd(GAME_YCOR) # Draw Dotted line self.screen_cursor.pu() self.screen_cursor.pensize(1) self.screen_cursor.setposition(0, (GAME_YCOR/2)) self.screen_cursor.setheading(270) for i in range(int(GAME_YCOR/10)): if i % 2 == 0: self.screen_cursor.pd() else: self.screen_cursor.pu() self.screen_cursor.fd(10) def update_players_score(self, index=None): if index is not None: self.scores[index] += 1 self.score_cursor.clear() self.score_cursor.setposition(-50, (GAME_YCOR/2)-70) self.score_cursor.write(f"{self.scores[LT_PLAYER]}", move=False, align="center", font=("Courier", 40, "bold")) self.score_cursor.setposition(50, (GAME_YCOR/2)-70) self.score_cursor.write(f"{self.scores[RT_PLAYER]}", move=False, align="center", font=("Courier", 40, "bold")) def init_paddle(self, lt_paddle_position, rt_paddle_position): self.lt_paddle.shape("square") self.lt_paddle.pu() self.lt_paddle.setheading(90) self.lt_paddle.shapesize(1, 6) self.lt_paddle.color("white") self.lt_paddle.setposition(lt_paddle_position) self.rt_paddle.shape("square") self.rt_paddle.pu() self.rt_paddle.setheading(90) self.rt_paddle.shapesize(1, 6) self.rt_paddle.color("white") self.rt_paddle.setposition(rt_paddle_position) def init_ball(self): self.ball.shape("circle") self.ball.pu() self.ball.shapesize(1.5, 1.5) self.ball.color("lime") def move_rt_paddle_up(self): if self.rt_paddle.ycor() <= (GAME_YCOR/2 - 80): self.rt_paddle.forward(20) def move_rt_paddle_down(self): if self.rt_paddle.ycor() >= -(GAME_YCOR/2 - 80): self.rt_paddle.backward(20) def move_lt_paddle_up(self): if self.lt_paddle.ycor() <= (GAME_YCOR/2 - 80): self.lt_paddle.forward(20) def move_lt_paddle_down(self): if self.lt_paddle.ycor() >= -(GAME_YCOR/2 - 80): self.lt_paddle.backward(20) def move_ball(self): self.ball.goto((self.ball.xcor()+self.x_move), (self.ball.ycor()+self.y_move)) def bounce_ball_yAxis(self): self.y_move *= -1 def bounce_ball_xAxis(self): self.x_move *= -1 def reset_ball_position(self): # Reverse Ball Direction self.x_move *= -1 # Reset Ball Position and Speed self.ball.setposition(0, 0) self.ball_speed = 0.12 def check_hit_wall(self): if self.ball.xcor() >= (GAME_XCOR/2 - 10): return LT_PLAYER elif self.ball.xcor() <= -(GAME_XCOR/2 - 10): return RT_PLAYER if self.ball.ycor() >= (GAME_YCOR/2 - 30) or \ self.ball.ycor() <= -(GAME_YCOR/2 - 30): self.bounce_ball_yAxis() return None def check_hit_paddle(self): if self.ball.distance(self.rt_paddle) < 60 and self.ball.xcor() > 340 or \ self.ball.distance(self.lt_paddle) < 60 and self.ball.xcor() < -340: # Make Ball move Faster self.ball_speed *= 0.9 # Reverse Ball Direction self.bounce_ball_xAxis()
def main(): # TODO 1: Configure screen screen = Screen() screen.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT) screen.bgcolor(SCREEN_BACKGROUND_COLOR) screen.tracer(0) # Add borders border = Border() border.createBorder() # TODO 2: Configure initial snake snake = Snake() food = Food() scoreboard = Scoreboard() # TODO 3: Move the snake screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") #global paused #def unpause(): # global paused # paused = not paused #screen.onkey(unpause, "p") game_is_on = True while game_is_on: #while paused: # sleep(0.2) screen.update() sleep(SLEEP_TIME) snake.move() # TODO 4: Detect collision with food snake_food_collision_distance = ( food.width() + snake.head.width()) / 2 - COLLISION_ERROR if snake.head.distance(food) < snake_food_collision_distance: scoreboard.score += 1 snake.add_segment() food.refresh() for segment in snake.tail: while segment.position() == food.position(): food.clear() food.refresh() scoreboard.refresh() # TODO 5: Detect collision with walls pass_x_wall = ( snake.head.xcor() < -SCREEN_WIDTH / 2 + snake.head.width() or snake.head.xcor() > SCREEN_WIDTH / 2 - snake.head.width()) pass_y_wall = ( snake.head.ycor() < -SCREEN_HEIGHT / 2 + snake.head.width() or snake.head.ycor() > SCREEN_HEIGHT / 2 - snake.head.width()) wall_collision = pass_x_wall or pass_y_wall if wall_collision: scoreboard.resetHighestScore() snake.resetSnake() # TODO 6: Detect collision with tail tail_head_collision_distance = snake.head.width() - COLLISION_ERROR for segment in snake.tail[1:]: if segment.distance(snake.head) < tail_head_collision_distance: scoreboard.resetHighestScore() snake.resetSnake() screen.exitonclick()
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) player = Player() car_manager = CarManager() scoreboard = Scoreboard() screen.listen() screen.onkey(player.go_up, "Up") screen.onkey(player.go_down, "Down") game_is_on = True while game_is_on: time.sleep(0.1) screen.update() car_manager.create_cars() car_manager.move_cars() #detect collision with car for car in car_manager.all_cars: if car.distance(player) < 20: scoreboard.game_over() game_is_on = False
from turtle import Turtle, Screen import random T = [] is_race_on = False screen = Screen() screen.setup(width=500, height=400) colors = [ "red", "RosyBrown", "RoyalBlue", "SaddleBrown", "SeaGreen", "SlateBlue" ] user_bet = screen.textinput("make your bet", "which turtle win the race?") for i in range(len(colors)): turtle = Turtle() T.append(turtle) T[i].penup() T[i].shape("turtle") T[i].color(colors[i]) T[i].goto(-150, -60 + 20 * i) if user_bet: is_race_on = True while is_race_on: for i in T: print(i.color()) random_number = random.randint(0, 20) i.forward(random_number)
self.pu() self.goto(c*A, r*A*3**.5/3) self.shapesize(SHS, SHS, 1) self.D = self.distance(0,0) self.e = (1/self.D)*self.pos() def setturn(self, phi): self.goto(SF*self.D*dsin(90-phi)*self.e) self.settiltangle(phi*self.f) self.shapesize(SHS*SF) if abs(self.c) + abs(self.r) > 2: self.fillcolor([x + (1-x)*phi/360 for x in self.basecolor]) bc = phi/360. self.pencolor(bc, bc, bc) s = Screen() s.reset() s.tracer(0) d = Turtle(visible=False) lines(500) triangles = [] for c in range(-5,6,2): triangles.append(TriTurtle(c, 1, 1)) triangles.append(TriTurtle(c, -1, 2)) for c in range(-4,5,2): triangles.append(TriTurtle(c, 2, 2)) triangles.append(TriTurtle(c, -2, 1)) triangles.append(TriTurtle(c, -4, 2)) triangles.append(TriTurtle(c, 4, 1)) for c in range(-3,4,2):
t.forward(peso) t.left(90) t.end_fill() A = list() # Cria uma lista vazia for c in range(7): try: A.append(int(input('Digite um valor: '))) except: print('Erro encotrado. Só números inteiros podem ser inseridos.') cor = list() # Cria uma lista vazia cor.append(str(input('Digite a cor da borda: '))) # Cria um elemento para a 1ª posição da lista cor.append(str(input('Digite a cor do prenchimento: '))) # Cria um elemento para a 2ª posição da lista tela = Screen() # Mostra a janela e seus atributos tela.bgcolor("lightgreen") touche = Turtle() # Cria a tartaruga touche.pensize(3) touche.penup() touche.backward(120) touche.pendown() try: touche.color(cor[0], cor[1]) except: print('Erro encontrado. Você não inseriu uma cor válida.') for a in A: histograma(touche, a)
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) player = Player() car_manager = CarManager() scoreboard = Scoreboard() screen.listen() screen.onkey(player.move, "Up") game_is_on = True while game_is_on: time.sleep(0.1) screen.update() car_manager.create_car() car_manager.move_cars() for car in car_manager.all_cars: if car.distance(player) < 20: game_is_on = False if player.is_at_finish_line(): player.go_to_start()
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("white") screen.tracer(0) player = Player() scoreboard = Scoreboard() cars = CarManager() game_is_on = True while game_is_on: time.sleep(0.1) screen.update() collision = cars.generate(player) if collision: scoreboard.game_over() game_is_on = False if player.check_pass(): scoreboard.increase_level() cars.accelerate()
from turtle import Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time # 0. Game setup screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("The UNSW BSOC Experience") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() # 3. Control the snake screen.listen() # Arrow Key Options screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") # WAS Option screen.onkey(snake.up, "w") screen.onkey(snake.down, "s")
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) colours = ["red", "orange", "green", "blue", "yellow", "purple"] step = [0, 5, 10] choice = screen.textinput(title="Who will win?", prompt="Pick a turtle, choose a color: ") def config_turtle(pick, colour): pick.color(colours[colour]) pick.penup() def random_step(pick): pick.speed("fastest") move = random.choice(step) pick.forward(move) t0 = Turtle(shape="turtle") t1 = Turtle(shape="turtle") t2 = Turtle(shape="turtle") t3 = Turtle(shape="turtle") t4 = Turtle(shape="turtle") t5 = Turtle(shape="turtle") turtles = [t0, t1, t2, t3, t4, t5]
def __init_drawing_window(cls): if cls.__screen is None: cls.__screen = Screen() cls.__screen.bgcolor("black") cls.__screen.setup(400, 300)
import turtle from turtle import Screen tl = turtle.Turtle() Screen().setup(height=1.0, width=1.0) def arbre(n, l): if n == 0: return elif n != 0: tl.forward(l) tl.left(30) arbre(n - 1, l / 1.5) tl.right(60) arbre(n - 1, l / 1.5) tl.left(30) tl.backward(l) arbre(10, 100) turtle.mainloop()
tdemo_tangram.py Inspired by Pawel Boytchev's Elica-Logo implementation of the tangram game. Use left mouse button to drag, middle and right mouse button clicks to turn tiles, left button doubleclick to flip rhomboid. """ from turtle import Turtle, Screen, Vec2D from button import Button import sys, random, time from tangramdata import tangramdata sys.setrecursionlimit(20000) screen = Screen() screen.tracer(False) screen.mode("logo") designer = Turtle(visible=False) designer.pu() startdata = tangramdata[0] tangramdata = tangramdata[1:] A = 198.0 a = A / 4.0 d = a * 2**.5 def makerhomboidshapes(): designer.shape("square") designer.shapesize(5, 2.5) designer.shearfactor(-1) # needs Python 3.1
from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=800, height=600) screen.bgcolor('black') screen.title('Pong') screen.tracer(0) r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) ball = Ball() scoreboard = Scoreboard() screen.listen() screen.onkey(r_paddle.up, 'Up') screen.onkey(r_paddle.down, 'Down') screen.onkey(l_paddle.up, 'w') screen.onkey(l_paddle.down, 's') game_on = True while game_on: time.sleep(ball.move_speed) screen.update() ball.move() # Detect collision with wall
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.title("Turtle Crossing") screen.setup(width=600, height=600) # Turn off the tracer screen.tracer(0) turtle_player = Player() screen.listen() screen.onkey(fun=turtle_player.move_up, key="Up") car_manager = CarManager() scoreboard = Scoreboard() game_is_on = True iteration = 0 while game_is_on: iteration += 1 time.sleep(0.1) # Screen update every 0.1s screen.update() car_manager.create_car() car_manager.move_cars()
class Time: # screen and turtle turtle = Turtle() turtle.fillcolor('gray') turtle.hideturtle() turtle.speed(0) turtle._delay(0) screen = Screen() screen.setup(width=600, height=400) screen.bgcolor('black') n = numbers.Numbers() d = digit.digit() # other turtles t1 = Turtle() t1.hideturtle() t1.speed(0) t1._delay(0) t1.fillcolor('white') t2 = Turtle() t2.hideturtle() t2.speed(0) t2._delay(0) t2.fillcolor('white') t3 = Turtle() t3.hideturtle() t3.speed(0) t3._delay(0) t3.fillcolor('white') t4 = Turtle() t4.hideturtle() t4.speed(0) t4._delay(0) t4.fillcolor('white') t5 = Turtle() t5.hideturtle() t5.speed(0) t5._delay(0) t5.fillcolor('white') # now def h1(self): now = datetime.now() h1 = str(now.strftime("%H")[0:1]) h1 = int(h1) return h1 def h2(self): now = datetime.now() h2 = str(now.strftime("%H")[1:2]) h2 = int(h2) return h2 def m1(self): now = datetime.now() m1 = str(now.strftime("%M")[0:1]) m1 = int(m1) return m1 def m2(self): now = datetime.now() m2 = str(now.strftime("%M")[1:2]) m2 = int(m2) return m2 # keret def keret(self, x, width): self.turtle.penup() self.turtle.begin_fill() self.turtle.setheading(90) self.turtle.goto(x, -100) self.turtle.pendown() for i in range(2): self.turtle.forward(220) self.turtle.left(90) self.turtle.forward(width) self.turtle.left(90) self.turtle.end_fill() def fullkeret(self): self.keret(-145, width=120) self.keret(-25, width=120) self.keret(25, width=50) self.keret(145, width=120) self.keret(265, width=120) # numbers selector def selector(self, number, size, turtle, x, y): if number == 0: self.n.number0(size=size, turtle=turtle, x=x, y=y) if number == 1: self.n.number1(size=size, turtle=turtle, x=x, y=y) if number == 2: self.n.number2(size=size, turtle=turtle, x=x, y=y) if number == 3: self.n.number3(size=size, turtle=turtle, x=x, y=y) if number == 4: self.n.number4(size=size, turtle=turtle, x=x, y=y) if number == 5: self.n.number5(size=size, turtle=turtle, x=x, y=y) if number == 6: self.n.number6(size=size, turtle=turtle, x=x, y=y) if number == 7: self.n.number7(size=size, turtle=turtle, x=x, y=y) if number == 8: self.n.number8(size=size, turtle=turtle, x=x, y=y) if number == 9: self.n.number9(size=size, turtle=turtle, x=x, y=y) def digit_selector(self, number, size, turtle, x, y): if number == 0: self.d.num0(size=size, turtle=turtle, x=x, y=y) if number == 1: self.d.num1(size=size, turtle=turtle, x=x, y=y) if number == 2: self.d.num2(size=size, turtle=turtle, x=x, y=y) if number == 3: self.d.num3(size=size, turtle=turtle, x=x, y=y) if number == 4: self.d.num4(size=size, turtle=turtle, x=x, y=y) if number == 5: self.d.num5(size=size, turtle=turtle, x=x, y=y) if number == 6: self.d.num6(size=size, turtle=turtle, x=x, y=y) if number == 7: self.d.num7(size=size, turtle=turtle, x=x, y=y) if number == 8: self.d.num8(size=size, turtle=turtle, x=x, y=y) if number == 9: self.d.num9(size=size, turtle=turtle, x=x, y=y) # base event + variables oldh1 = 10 oldh2 = 10 oldm1 = 10 oldm2 = 10 oldsec = 10 valtozo = 1 def base_event(self): m2 = self.m2() if m2 != self.oldm2: self.minute2(ido=m2) print('minute2 changed') self.oldm2 = m2 m1 = self.m1() if m1 != self.oldm1: self.minute1(ido=m1) print('minute1 changed') self.oldm1 = m1 h1 = self.h1() if h1 != self.oldh1: self.hour1(ido=h1) print('hour1 changed') self.oldh1 = h1 h2 = self.h2() if h2 != self.oldh2: self.hour2(ido=h2) print('hour2 changed') self.oldh2 = h2 self.screen.ontimer(fun=self.base_event, t=100) # second def second(self): now = datetime.now() second = str(now.strftime("%S")[1:2]) second = int(second) if second != self.oldsec: if self.valtozo == 1: self.d.pont(turtle=self.t5, x=25, y=-100) self.valtozo = self.valtozo - 1 else: self.t5.clear() self.valtozo = self.valtozo + 1 self.oldsec = second self.screen.ontimer(fun=self.second, t=100) # writing def hour1(self, ido): self.t1.clear() """self.selector(number=ido, size=100, turtle=self.t1, x=-145, y=-100)""" self.digit_selector(number=ido, size=80, turtle=self.t1, x=-145, y=-100) def hour2(self, ido): self.t2.clear() """self.selector(number=ido, size=100, turtle=self.t2, x=-25, y=-100)""" self.digit_selector(number=ido, size=80, turtle=self.t2, x=-25, y=-100) def minute1(self, ido): self.t3.clear() """self.selector(number=ido, size=100, turtle=self.t3, x=145, y=-100)""" self.digit_selector(number=ido, size=80, turtle=self.t3, x=145, y=-100) def minute2(self, ido): self.t4.clear() """self.selector(number=ido, size=100, turtle=self.t4, x=265, y=-100)""" self.digit_selector(number=ido, size=80, turtle=self.t4, x=265, y=-100) # init def __init__(self): self.fullkeret() self.base_event() self.second() self.screen.mainloop()
from turtle import Screen, Turtle pantalla = Screen() pantalla.setup(425, 225) pantalla.screensize(400, 200) tortuga = Turtle() tortuga.forward(100) tortuga.left(90) tortuga.forward(100) tortuga.left(90) tortuga.forward(100) tortuga.left(90) tortuga.forward(100) pantalla.exitonclick()
from turtle import Turtle, Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time WIDTH = 600 HEIGHT = 600 WALL_W = WIDTH - 60 WALL_H = HEIGHT - 60 screen = Screen() screen.bgcolor("black") screen.setup(WIDTH, HEIGHT) screen.title("Snake Eater") outline = Turtle() outline.color("white") outline.pencolor("white") outline.penup() outline.goto(WALL_W / 2, -WALL_H/2) outline.pendown() outline.goto(WALL_W / 2, WALL_H / 2) outline.goto(-WALL_W / 2, WALL_H / 2) outline.goto(-WALL_W / 2, -WALL_H / 2) outline.goto(WALL_W / 2, -WALL_H / 2) body = []
def main(): global d, SHS, SF, A A = 42 # answer to the ultimate question ... (you know) SHS = A / 20.0 SF = 1.0 DSF = 1.0038582416 s = Screen() s.setup(800, 600) s.reset() s.tracer(0) d = Turtle(visible=False) for i in range(6): d.fd(500) d.bk(500) d.left(60) triangles = [] for c in range(-5, 6, 2): if abs(c) != 1: triangles.append(TriTurtle(c, 1, 1)) triangles.append(TriTurtle(c, -1, 2)) for c in range(-4, 5, 2): if c != 0: triangles.append(TriTurtle(c, 2, 2)) triangles.append(TriTurtle(c, -2, 1)) triangles.append(TriTurtle(c, -4, 2)) triangles.append(TriTurtle(c, 4, 1)) for c in range(-3, 4, 2): triangles.append(TriTurtle(c, 5, 2)) triangles.append(TriTurtle(c, -5, 1)) triangles.append(TriTurtle(c, -7, 2)) triangles.append(TriTurtle(c, 7, 1)) for c in range(-2, 3, 2): triangles.append(TriTurtle(c, 8, 2)) triangles.append(TriTurtle(c, -8, 1)) for c in (-1, 1): triangles.append(TriTurtle(c, 1, 1)) triangles.append(TriTurtle(c, -1, 2)) triangles.append(TriTurtle(0, 2, 2)) triangles.append(TriTurtle(0, -2, 1)) s.tracer(1) for phi in range(1, 361): SF = SF * DSF s.tracer(0) for t in triangles: t.setturn(phi) s.tracer(1) return "DONE!"
from turtle import Turtle, Screen import random is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput( title="Make your bet", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] turtles = [] for color_index in range(0, len(colors) - 1): new_turtle = Turtle(shape="turtle") new_turtle.color(colors[color_index]) new_turtle.penup() new_turtle.goto(-230, -100 + color_index * 50) turtles.append(new_turtle) if user_bet: is_race_on = True while is_race_on: for turtle in turtles: if turtle.xcor() > 230: is_race_on = False winning_color = turtle.pencolor() if user_bet == winning_color: print(f"You've won! The {winning_color} turtle is the winner!") else:
print ("PSYCO -- SUPER!!") except: print ("-- psyco not installed - reduced performance --") print ("-- Download psyco at http://psyco.sourceforge.net/ --") # MAX_X and MAX_Y must be odd MAX_X = 79 MAX_Y = 57 SQUARE_WIDTH = 10 # must be even FREEROWS = 3 WINHEIGHT = MAX_Y + FREEROWS MARG_X = 2 + SQUARE_WIDTH//2 MARG_Y = 8 DM = 10 screen = Screen() def coords(col, row): return ((-MAX_X//2 + col)*SQUARE_WIDTH + MARG_X, ((-MAX_Y+ FREEROWS)//2 + row )*SQUARE_WIDTH + MARG_Y) def cellindices(x, y): return ((x-MARG_X + (SQUARE_WIDTH-1)//2)//SQUARE_WIDTH + MAX_X//2 + 1, (y-MARG_Y + (SQUARE_WIDTH-1)//2)//SQUARE_WIDTH + (MAX_Y- FREEROWS)//2) def calccolor(i): i = min(20, i) return (1.05-i/20., 0., i/20.-0.05) def generate(state): NBADDR = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1))
def __init__(self, w, h): Turtle.__init__(self, visible=False) self.screen = Screen() self.screen.setup(w, h) self.speed(0) self.penup() self.goto(-WINWIDTH//2 + 50, -WINHEIGHT//2 + 20) self.pencolor("yellow")
def main(): t = Turtle() my_win = Screen() t.width(12) t.speed(10) t.left(90) t.up() t.backward(100) t.down() t.color("brown") tree(75, t) my_win.exitonclick()