def main(): ## create compound yellow/blue turtleshape for planets global s s = Screen() s.setup(1120,840) 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) s.update() ## 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 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 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)
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)
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!"
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 "Laufzeit: {0:.3f} sec".format(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 "runtime: %.3f sec" % (z1+et-at)
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 designer.tilt(90)
def fire(): ship.fireBullet() def quit(): turtle.goto(0, screenMaxY - 100) turtle.color("green") turtle.write("Thanks for playing!", font=("Arial", 30), align="center") sleep(1) exit() turtle.hideturtle() screen.tracer(0) screen.onkey(turnLeft, "Left") screen.onkey(turnRight, "Right") screen.onkey(go, "Up") screen.onkey(fire, "x") screen.onkey(quit, "q") screen.listen() play() screen.mainloop() print("Done")
from turtle import Screen from paddle import Paddle from ball import Ball from block import Block screen = Screen() screen.setup(width=1000, height=768) screen.bgcolor("black") screen.title("Breakout") screen.tracer(n=2, delay=0) paddle = Paddle(0, -300) ball = Ball() screen.listen() screen.onkey(paddle.go_left, "Left") screen.onkey(paddle.go_right, "Right") row_of_blocks = [] for i in range(20): block = Block(-475 + (i * 50), 300, "red") row_of_blocks.append(block) game_is_on = True while game_is_on: screen.update() ball.move() #Detect collision with paddles if ball.distance(paddle) < 50 and ball.ycor() < -280:
from turtle import Screen, Turtle, bye, Terminator from _tkinter import TclError from game_object import GameObject, objs, Obstacle from time import sleep # Constants FRAMERATE = 30 # Window wn = Screen() wn.setup(height=800, width=1000) wn.title('Stupid game shit') wn.bgcolor('#220022') wn.tracer(0) wn.listen() # Goodbye to the game wn.onkeypress(bye, 'Escape') # Players player1 = GameObject('circle', '#880000', 1, 1, -200, 0) player1.binds(wn, ['w', 's', 'a', 'd']) player2 = GameObject('square', '#008800', 1, 1, 200, 0) player2.binds(wn, ['Up', 'Down', 'Left', 'Right']) # Their lives player1.lives = 3 player2.lives = 3
from turtle import Turtle, Screen import time import datetime t = Turtle() t.hideturtle() screen = Screen() screen.tracer(n=10, delay=100) # exit_from_prog = False # def pr(): # print('exit') # exit = True # screen.onkey(pr,'Escape') # screen.listen() while True: # if(exit): # break t.reset() current_time = datetime.datetime.now() time_string = current_time.isoformat() t.write(time_string, font=("Arial", 20, "normal")) time.sleep(1)
from turtle import Screen from turtle import Turtle from paddle import Paddle from ball import Ball import time from scoreboard import Scoreboard screen = Screen() screen.setup(800, 600) screen.bgcolor("Black") screen.title("Pong") screen.tracer( 0) # turn off the animation , now we have to update our screen manually 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()
from turtle import Turtle, Screen import time import random import car_manager from player_turt import Players scr = Screen() scr.setup(600, 600) scr.colormode(255) player = Players() scr.listen() scr.onkeypress(player.up, "Up") scr.onkeypress(player.down, "Down") scr.tracer(0) car = car_manager.Cars() gameOn = True while gameOn: time.sleep(0.1) scr.update() car.create_car() car.move_car() for i in car.cars_list: if player.distance(i) < 20: gameOn = False scr.exitonclick()
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()
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
from turtle import Turtle, Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time #Create window for the game. Setup size and color screen = Screen() screen.setup(width=800, height=600) screen.bgcolor("black") screen.title("Pong Game") screen.listen() #Function to kisten for user inputs screen.tracer(0) #Stop screen from updating on its own #Create paddles from paddle class paddle_r = Paddle((350, 0)) paddle_l = Paddle((-350, 0)) #Create ball from ball class ball = Ball() #Create scoreboard from scoreboard class scoreboard = Scoreboard() scoreboard.update_scoreboard() game_is_on = True #Boolean to keep game running #Functions to control the two paddles from the listen function screen.onkey(fun=paddle_r.move_up, key="Up") screen.onkey(fun=paddle_r.move_down, key="Down") screen.onkey(fun=paddle_l.move_up, key="w") screen.onkey(fun=paddle_l.move_down, key="s")
class BaseTurtle(Turtle): def __init__( self, window_size: int = 800, # width and height of the turtle canvas reach: float = 16, speed: int = 0, # how fast to draw machine=None, # the PantoGraph object to which the turtle belongs coarseness: int = 0, # a factor, in degrees, to represent the resolution of the servos ): super().__init__() self.window_size = window_size self.reach = reach self.machine = machine self.coarseness = coarseness if self.machine: self.angle_1 = self.machine.angle_1 self.angle_2 = self.machine.angle_2 # some basic dimensions of the drawing area grid_size = (self.window_size / 1.05 ) # the grid is a little smaller than the window self.multiplier = grid_size / 2 / self.reach self.draw_reach = (self.reach * self.multiplier * 1.05 ) # maximum possible drawing reach # set up the screen for the turtle self.screen = Screen() self.screen.mode("logo") self.speed(0) self.screen.tracer(speed, 0) self.screen.setup(width=window_size, height=window_size) # ----------------- grid drawing methods ----------------- def draw_grid(self): self.draw_grid_lines(draw_every=1, color="#bbb", width=1, include_numbers=False) self.draw_grid_lines(draw_every=5, color="black", width=1, include_numbers=True) def draw_grid_lines(self, draw_every=1, color="gray", width=1, include_numbers=False): self.color(color) self.width(width) for i in range(int(-self.reach), int(self.reach + 1)): if not (i % draw_every): draw_i = i * self.multiplier self.up() self.goto(draw_i, -self.draw_reach) self.down() self.goto(draw_i, self.draw_reach) self.up() self.goto(-self.draw_reach, draw_i) self.down() self.goto(self.draw_reach, draw_i) if include_numbers: self.up() self.goto(i * self.multiplier, -1 * self.multiplier) self.write(" " + str(i), move=False, font=("Helvetica", 16, "bold")) self.goto(-self.reach * self.multiplier, i * self.multiplier) self.write(i, move=False, font=("Helvetica", 16, "bold")) def set_angles(self, angle_1, angle_2): if self.coarseness: coarsened_angle_1 = self.coarsen_angle(angle_1) coarsened_angle_2 = self.coarsen_angle(angle_2) diff_1 = coarsened_angle_1 - self.angle_1 diff_2 = coarsened_angle_2 - self.angle_2 length = math.sqrt(diff_1**2 + diff_2**2) no_of_steps = int(length * 10) if no_of_steps: (length_of_step_1, length_of_step_2) = ( diff_1 / no_of_steps, diff_2 / no_of_steps, ) for step in range(no_of_steps): self.angle_1 = self.angle_1 + length_of_step_1 self.angle_2 = self.angle_2 + length_of_step_2 x, y = self.machine.angles_to_xy(self.angle_1, self.angle_2) self.setpos(x * self.multiplier, y * self.multiplier) else: x, y = self.machine.angles_to_xy(angle_1, angle_2) self.setpos(x * self.multiplier, y * self.multiplier) def coarsen_angle(self, angle): return round(angle / self.coarseness) * self.coarseness
# Author: TM 2022 # ---------------------------------------------------------*/ #!/usr/bin/env python3 import time from turtle import Screen, Turtle from paddle import Paddle from ball import Ball from scoreboard import Scoreboard # Screen-Setup screen = Screen() screen.setup(width=800, height=600) screen.bgcolor("black") screen.title("My Pong Game") screen.tracer(0) # Turn animations of turtle off # Screen-Separator separator = Turtle() separator.penup() separator.goto(0, -300) separator.color("white") separator.pendown() separator.setheading(90) for _ in range(30): separator.forward(10) separator.penup() separator.forward(10) separator.pendown() separator.hideturtle()
from turtle import Turtle, Screen from goalkeeper import Goalkeeper from ball import Ball players = [] # this was same pong_screen = Screen() pong_screen.setup(width=800, height=600) pong_screen.bgcolor("black") pong_screen.listen() pong_screen.tracer(0) def separate_screen(): separater_turtle = Turtle() separater_turtle.color("white") separater_turtle.penup() separater_turtle.hideturtle() separater_turtle.setpos((0, -280)) separater_turtle.setheading(90) separater_turtle.pensize(5) while separater_turtle.ycor() < 280: separater_turtle.pendown() separater_turtle.forward(10) separater_turtle.penup() separater_turtle.forward(20) pong_screen.update()
#parameters map_size = 16 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)
def fire(): ship.fireBullet() def quit(): turtle.goto(0, screenMaxY - 100) turtle.color('green') turtle.write("Thanks for playing!", font=("Arial", 30), align="center") sleep(1) exit() turtle.hideturtle() screen.tracer(0); screen.onkey(turnLeft, 'Left') screen.onkey(turnRight, 'Right') screen.onkey(go, 'Up') screen.onkey(fire, 'x') screen.onkey(quit, 'q') screen.listen() play() screen.mainloop() print("Done")
DATABASE_NAME = 'system/stats.db' # # # Game states #### # 0 - choose game play # 50 - choose game type # 100 - choose game size # 150 - choose players # 200 - in game # window screen set up window = Screen() window.title("Table tennis scoreboard") window.bgcolor("black") window.setup(width=1024, height=600) window.delay(0) window.tracer(False) # turtle set up pen = Turtle() pen.speed(0) pen.color("white") pen.hideturtle() pen.penup() # definitions of game functions def database_update_singles(): global player2_id, player1_id, playerNames, match_duration, leftScore, rightScore conn = connect(DATABASE_NAME) c = conn.cursor()
from turtle import Screen # ,Turtle from snake import Snake # import Snake class from snake module from food import Food from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer(0) # turn animation off # Create new snake object from Snake class, initialize a snake object snake = Snake() # Create food object food = Food() # Create scoreboard object scoreboard = Scoreboard() # Control snake screen.listen() # starting listening for keystroke: up, down, left, right screen.onkey(snake.up, "Up") # bind Up from keyboard to snake object function up screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") # move Snake: tail will follow head game_is_on = True while game_is_on: # only update screen when all segments move forward
from turtle import Screen, Turtle from snake import Snake import time # Screen settings WIDTH = 600 HEIGHT = 600 S_COLOR = "#000" s = Screen() s.setup(WIDTH, HEIGHT) s.bgcolor(S_COLOR) s.title("Snake Game") s.tracer(0) snake = Snake() # Keybinds s.listen() s.onkey(snake.up, "Up") s.onkey(snake.down, "Down") s.onkey(snake.left, "Left") s.onkey(snake.right, "Right") game_on = True while game_on:
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)
class Game: def __init__(self): # game object has a screen, a turtle, a basic snake and a food self.screen = Screen() self.artist = Turtle(visible=False) self.artist.up() self.artist.speed("slowest") self.snake = Snake() self.food = Food(100, 0) self.counter = 0 # this will be used later self.commandpending = False # as will this self.screen.tracer(0) # follow it so far? self.screen.listen() self.screen.onkey(self.snakedown, "Down") self.screen.onkey(self.snakeup, "Up") self.screen.onkey(self.snakeleft, "Left") self.screen.onkey(self.snakeright, "Right") def snakeup(self): if not self.commandpending: self.commandpending = True self.snake.moveup() self.commandpending = False def snakedown(self): if not self.commandpending: self.commandpending = True self.snake.movedown() self.commandpending = False def snakeleft(self): if not self.commandpending: self.commandpending = True self.snake.moveleft() self.commandpending = False def snakeright(self): if not self.commandpending: self.commandpending = True self.snake.moveright() self.commandpending = False def nextFrame(self): self.artist.clear() if (self.snake.nextposition[0], self.snake.nextposition[1]) == (self.food.x, self.food.y): self.snake.eatFood() self.food.changelocation() else: self.snake.moveOneStep() if self.counter == 10: self.food.changestate() # makes the food flash slowly self.counter = 0 else: self.counter += 1 self.food.drawself(self.artist) # show the food and snake self.snake.drawself(self.artist) self.screen.update() self.screen.ontimer(lambda: self.nextFrame(), 100)
from turtle import Screen, Turtle from SquareV2 import * screen = Screen() screen.tracer(False) # Assiging the images to variables RedInfantry = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\InfantryRedV20.gif" BlueInfantry = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\InfantryBlueV20.gif" RedTank = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\TankRedV20.gif" BlueTank = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\TankBlueV20.gif" RedMobileGun = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\MobileGunRedV20.gif" BlueMobileGun = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\MobileGunBlueV20.gif" RedRocketLauncher = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\RocketLauncherRedV20.gif" BlueRocketLauncher = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\RocketLauncherBlueV20.gif" RedAntiAirTank = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\AntiAirTankRedV20.gif" BlueAntiAirTank = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\AntiAirTankBlueV20.gif" RedSupplyTruck = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\TransporterRedV20.gif" BlueSupplyTruck = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\TransporterBlueV20.gif" RedAntiAirMissleLauncher = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\AntiAirMissleLauncherRedV20.gif" BlueAntiAirMissleLauncher = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\AntiAirMissleLauncherBlueV20.gif" RedHelicopter = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\HelicopterRedV20.gif" BlueHelicopter = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\HelicopterBlueV20.gif" RedBomber = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\BomberRedV20.gif" BlueBomber = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\BomberBlueV20.gif" RedJeep = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Red team\JeepRedV20.gif" BlueJeep = r"C:\Users\User\Desktop\a level computer science\Coursework\Week\Blue team\JeepBlueV20.gif" #Adding the red team screen.addshape(RedAntiAirMissleLauncher)
from turtle import Screen, Turtle from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 tim = Turtle('circle') screen = Screen() screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT) screen.bgcolor('black') screen.title("MY PONG GAME") screen.tracer(0) r_paddle = Paddle('right') l_paddle = Paddle('left') ball = Ball() scoreboard = Scoreboard() screen.listen() screen.onkeypress(r_paddle.up, 'Up') screen.onkeypress(r_paddle.down, 'Down') screen.onkeypress(l_paddle.up, 'w') screen.onkeypress(l_paddle.down, 's') # ball.speed(2) tim.hideturtle() tim.penup() tim.color('white') tim.setheading(90)
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): triangles.append(TriTurtle(c, 5, 2)) triangles.append(TriTurtle(c, -5, 1))
# Bubbles on the water, no trails from turtle import Turtle, Screen import random import math print("Creating an Ocean") ocean = Screen() ocean.title("Let's find Splash") ocean.setup(800, 800) # Make the pen fast. ocean.tracer(0) class Bubble: # Special name for the very first method called __init__ def __init__(self, x, y, color1, color2): # Set location and direction self.x = x self.y = y self.dx = 0 self.dy = 0 # Make our own 'private' turtle for drawing self.turtle = Turtle() self.turtle.color(color1, color2) self.turtle.hideturtle() self.turtle.up() self.turtle.goto(self.x, self.y) self.turtle.width(3)
from turtle import Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time # Set up the screen snake = Snake() food = Food() scoreboard = Scoreboard() screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer( 0) # Move the snake body all together; It turns off the animation # Move the snake (i.e. the 3 objects) screen.listen() screen.onkey(fun=snake.up, key='Up') screen.onkey(fun=snake.down, key='Down') screen.onkey(fun=snake.left, key='Left') screen.onkey(fun=snake.right, key='Right') game_is_on = True while game_is_on: screen.update( ) # After use the 'tracer()' method, in order for it to work you need this method time.sleep(0.1) # Slow down the speed of the snake snake.move() # Move the snake--the last segment moves first
from turtle import Turtle, 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 Game") screen.tracer(0) # screen.update() method must be added see while loop r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) 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") ball = Ball() scoreboard = Scoreboard() game_is_on = True while game_is_on: time.sleep(ball.move_speed) screen.update() ball.move()
def main(): """Main loop where all the game logic is handled. Args: None. Returns: None. """ game_window = Screen() game_window.bgcolor("black") game_window.title("The Bouncy Space Ship Game") game_window.bgpic("background.gif") border = Border() game = Game() player1_score = Score(-290, 310, 1) player2_score = Score(190, 310, 2) border.draw_border() player1 = Player("blue") player2 = Player("purple") the_food = [] #List of Food objects. for _ in range(Food.amount): the_food.append( Food() ) #Spawning the food onto the screen and adding them to the food list. the_traps = [] #List of Trap objects. for _ in range(Traps.amount): the_traps.append( Traps() ) #Spawning the traps onto the screen and adding them to the food list. game_window.tracer(0) #Turn automatic scren updates off for preformance. player1_score.change_score(0) #Start the score at 0. player2_score.change_score(0) game_active1 = True game_active2 = True game_window.listen() game_window.onkey( player1.turnleft, "Left" ) #Turn the player's avatar left when the left button is pressed. game_window.onkey(player1.turnright, "Right") game_window.onkey( player1.increasespeed, "Up" ) #Increase the speed of the player's avatar when the up button is pressed. game_window.onkey(player1.decreasespeed, "Down") game_window.listen() game_window.onkey(player2.turnleft, "A") game_window.onkey(player2.turnright, "D") game_window.onkey(player2.increasespeed, "W") game_window.onkey(player2.decreasespeed, "S") game_window.onkey(player2.turnleft, "a") game_window.onkey(player2.turnright, "d") game_window.onkey(player2.increasespeed, "w") game_window.onkey(player2.decreasespeed, "s") while game_active1 or game_active2: game_window.update() #Update the game window every loop. for food in the_food: food.move() #Move the food. if player1 is not None and game.touch_checker( player1, food ): #If the player touches a food reset the food's position, play the eating sound, and update the score. food.regenerate() game.play_eating_sound() player1_score.change_score(10) if player2 is not None and game.touch_checker(player2, food): food.regenerate() game.play_eating_sound() player2_score.change_score(10) for trap in the_traps: trap.move() #Move the trap. if player1 is not None and game.game_over( player1, trap ): #If a player's avatar hits a trap take it out of the game. game.play_game_over_sound() game_active1 = False player1.hideturtle() del player1 player1 = None if player2 is not None and game.game_over(player2, trap): game.play_game_over_sound() game_active2 = False player2.hideturtle() del player2 player2 = None if game_active1: player1.move() #Move the player's avatar. if game_active2: player2.move() if not game_active1: #End the game if player 1's avatar has a lower score than player 1 and it gets hit by a trap. if player1_score.score < player2_score.score: game_active2 = False if not game_active2: #End the game if player 2's avatar has a lower score than player 2 and it gets hit by a trap. if player2_score.score < player1_score.score: game_active1 = False game.update_game_status(player1_score.score, player2_score.score) #Display the winner/ a draw. sleep(2.5)
from turtle import Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time theScreen = Screen() theScreen.setup(width=600, height=600) theScreen.bgcolor("black") theScreen.title("The Snake Game") theScreen.tracer(0) theSnake = Snake() theFood = Food() theScore = Scoreboard() theScreen.listen() theScreen.onkeypress(theSnake.up, "Up") theScreen.onkeypress(theSnake.down, "Down") theScreen.onkeypress(theSnake.left, "Left") theScreen.onkeypress(theSnake.right, "Right") keepPlaying = True while keepPlaying: theScreen.update() time.sleep(0.1) theSnake.move() theScore.showScore()
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)
def plot_temp_vs_day(t_list): # # t_list = [t_year, t_ave] t = Turtle() wn = Screen() wn.tracer(0) # t.speed(100) t.ht() # Setting grid coordinates x_max = len(t_list[1]) x_min = 0 y_max = int(max(t_list[1])) y_min = 0 if min(t_list[1]) < 0: y_min = int(min(t_list[1]) - 10) # Grid Scales x_scl = 20 y_scl = 20 wn.setworldcoordinates(x_min - 20, y_min - 20, x_max + 20, y_max + 20) # Draw axis axis = [[x_min, y_min],[x_max, y_min],[0.0, y_min],[0.0, y_max]] for i in range(0, 4, 2): t.up() t.goto(axis[i][0],axis[0][1]) # Origin x,y (0,2) t.down() t.goto(axis[i + 1][0], axis[i + 1][1]) # highest point x,y (0,2) t.up() # Draw lines # x-lines t.up() t.goto(x_min, y_min) #goes to origin for i in range(x_max//x_scl): t.up() t.forward(x_scl) t.left(90) t.forward(1) t.down() t.forward(-2) t.up() t.forward(-4) t.write(str(i * x_scl), font=("Arial", 14, "normal")) t.forward(5) t.right(90) # y-lines t.up() t.goto(x_min, y_min) #goes to origin t.left(90) for i in range(y_max//y_scl): t.up() t.forward(y_scl) t.left(90) t.forward(1) t.forward(8) t.write(str(i * x_scl), font=("Arial", 14, "normal")) t.forward(-8) t.down() t.forward(-2) t.up() t.forward(1) t.right(90) t.up() # Draw the graph t.color('blue') t.goto(x_min, y_min) t.down() for i in range(len(t_list[1])): if t_list[1][i] != -99: # t.up() t.goto(i, t_list[1][i]) t.down() t.dot() t.up() # Draw the graph t.color('green') t.goto(x_min, y_min) t.down() for i in range(len(t_list[0])): if t_list[0][i] != -99: #t.up() t.goto(i * 2.8969, t_list[0][i]) t.down() t.dot() wn.update() wn.exitonclick()
from turtle import Turtle,Screen import time screen = Screen() screen.setup(width=600,height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer(0) #make the snake appears to be insync when moving starting_positions = [(0,0),(-20,0),(-40,0)] segments = [] for position in starting_positions: new_segment = Turtle("square") new_segment.color("white") new_segment.penup() new_segment.goto(position) segments.append(new_segment) game_is_on = True while game_is_on: screen.update() #updates the screen time.sleep(0.1) #This will be changed to set the snake to turn # for seg in segments: # seg.forward(20) for seg_num in range( len(segments) - 1 , 0, -1): new_x = segments[seg_num -1].xcor() new_y = segments[seg_num -1].ycor() segments[seg_num].goto(new_x,new_y)
# import required modules from turtle import Screen from time import sleep from spaceship import SpaceShip from aliens import Invaders from scoreboard import ScoreBoard # setting up the game screen game_screen = Screen() game_screen.setup(width=600, height=650) game_screen.bgcolor("black") game_screen.title("Space Invaders") game_screen.tracer(0) game_screen.listen() # setup and display each game component space_ship = SpaceShip() aliens = Invaders() scores = ScoreBoard() game_on = True loops = 0 def end_game(): """A function that ends the game abruptly""" global game_on game_on = False
from turtle import Screen, Turtle from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time #TODO1: Create the screen screen = Screen() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("Pong Game") screen.listen() screen.tracer(0) # Disableing the animations #TODO2: Create a moving paddle r_paddle = Paddle((350, 0)) screen.onkey(r_paddle.go_up, "Up") screen.onkey(r_paddle.go_down, "Down") #TODO3: Create another moving paddle l_paddle = Paddle((-350, 0)) screen.onkey(l_paddle.go_up, "w") screen.onkey(l_paddle.go_down, "s") #TODO4: Create the ball and make it move ball = Ball() #TODO8: Keep scores scoreboard = Scoreboard() game_is_on = True
turtle.clearstamp(block.stamp) stamp = turtle.stamp() if color != WHITE: blocks.append(Block(block.position, color, stamp)) # not white yet so keep changing this block if blocks: # stop all changes if/when all blocks turn white screen.ontimer(change, DELAY) HALF_SIZE = SIZE // 2 screen = Screen() screen.colormode(WHITE[0]) screen.register_shape("block", ((HALF_SIZE, -HALF_SIZE), (HALF_SIZE, HALF_SIZE), (-HALF_SIZE, HALF_SIZE), (-HALF_SIZE, -HALF_SIZE))) screen.tracer(GRID ** 2) # ala @PyNuts turtle = Turtle(shape="block", visible=False) turtle.speed("fastest") turtle.up() Block = namedtuple('Block', ['position', 'color', 'stamp']) blocks = list() HALF_GRID = GRID // 2 for x in range(-HALF_GRID, HALF_GRID): for y in range(-HALF_GRID, HALF_GRID): turtle.goto(x * SIZE, y * SIZE) color = [randrange(ceil(INCREASE), DARK) for primary in WHITE]
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, Turtle from random import randint s = Screen() s.setup(560,560) s.title("A drunken turtle collecting ...") s.tracer(False) writer = Turtle(visible=False) writer.penup() writer.goto(0, -275) coins = [] for i in range(-4,5): for j in range(-4, 5): if i == j == 0: continue c = Turtle(shape="circle") c.color("", "orange") c.shapesize(0.5) c.goto(40*i, 40*j) coins.append(c) s.tracer(True) DRUNKENNESS = 45 t = Turtle(shape="turtle") t.color("black","") points = 0 while abs(t.xcor()) < 200 and abs(t.ycor()) < 200: t.forward(5) t.right(randint(-DRUNKENNESS, DRUNKENNESS))