def main(): program_key = ''' *** Welcome to Computer Turtle *** Character Meaning f...............move turtle forwad b...............move turtle backward l...............turn turtle left r...............turn turtle right u...............pen up d...............pen down ''' print( program_key) print( "Right click the turtle for more info...") get_command() t.listen() t.onclick( pos, 2) inititals() t.mainloop()
def top_layer(): turtle.clearscreen() screen_setup() stations() sp = turtle.Turtle() sp.color('white') sp.penup() global top_pos sp.setpos(top_pos) sp.showturtle() sp.speed(1) def sta1(): turn_and_go(sp, 'sta1') def sta2(): turn_and_go(sp, 'sta2') def sta3(): turn_and_go(sp, 'sta3') def zoom1(): global top_pos top_pos = sp.pos() global middle_sta1_pos middle_sta1_pos = 250,-150 if sp.pos() == (200,75): middle_layer_sta1() else: zoom() turtle.onkey(sta1, 'a') turtle.onkey(sta2, 'b') turtle.onkey(sta3, 'c') turtle.onkey(zoom1, '=') turtle.listen()
def play(self): cannon = LaserCannon() turtle.ontimer(self.add_alien,2000) turtle.listen() # Start the event loop. turtle.mainloop()
def top_layer(): turtle.clearscreen() screen_setup() stations() sp = turtle.Turtle() sp.color('white') sp.penup() sp.setpos(200, 75) sp.showturtle() sp.speed(1) def sta1(): sp.goto(200, 75) def sta2(): sp.goto(-300, 45) def sta3(): sp.goto(-100,-200) def zoom1(): if sp.pos() == (200,75): middle_layer_sta1() else: zoom() turtle.onkey(sta1, 'a') turtle.onkey(sta2, 'b') turtle.onkey(sta3, 'c') turtle.onkey(zoom1, '=') turtle.listen()
def docking_layer(): turtle.clearscreen() screen_setup() docking_port1() sp3 = turtle.Turtle() sp3.color('white') sp3.penup() sp3.speed(0) sp3.setpos(300, 0) sp3.seth(180) sp3.showturtle() speed = (10) def turnleft(): sp3.left(30) def turnright(): sp3.right(30) def forward(): sp3.forward(speed) def backward(): sp3.backward(speed) turtle.onkey(forward, 'Up') turtle.onkey(turnleft, 'Left') turtle.onkey(turnright, 'Right') turtle.onkey(backward, 'Down') turtle.onkey(middle_layer_sta1, '-') turtle.listen()
def middle_layer_sta1(): time.sleep(0.5) turtle.clearscreen() screen_setup() station_1() sp2 = turtle.Turtle() sp2.color('white') sp2.penup() sp2.speed(0) sp2.setpos(250, -150) sp2.seth(90) sp2.showturtle() speed = (10) b = 2 def turnleft(): sp2.left(30) def turnright(): sp2.right(30) def forward(): sp2.forward(speed) def backward(): sp2.backward(speed) def zoom1(): if sp2.xcor() > -162 and sp2.xcor() < -98 and sp2.ycor() > -112 and sp2.ycor() < -64: docking_layer() turtle.onkey(forward, 'Up') turtle.onkey(turnleft, 'Left') turtle.onkey(turnright, 'Right') turtle.onkey(backward, 'Down') turtle.onkey(top_layer, '-') turtle.onkey(zoom1,'=') turtle.listen()
def zoom(): time.sleep(0.5) turtle.clearscreen() screen_setup() sp2 = turtle.Turtle() sp2.color('white') sp2.penup() sp2.speed(0) sp2.setpos(250, -150) sp2.seth(90) sp2.showturtle() speed = (10) b = 2 def turnleft(): sp2.left(30) def turnright(): sp2.right(30) def forward(): sp2.forward(speed) def backward(): sp2.backward(speed) turtle.onkey(forward, 'Up') turtle.onkey(turnleft, 'Left') turtle.onkey(turnright, 'Right') turtle.onkey(backward, 'Down') turtle.onkey(top_layer, '-') turtle.listen()
def lab11(): Line() Rectangle() Circle() addkeys() addmouse() turtle.listen() turtle.mainloop()
def lab11(): ring() addkeys() addmouse() turtle.listen() turtle.mainloop() schoolLife() speech()
def on_forward(): val = t.textinput('Forward', "How much: ") if val: try: val = int(val) t.forward(val) except ValueError: messagebox.showinfo('Error', 'Wrong value') t.listen()
def on_right(): val = t.textinput('Right', "How much: ") if val: try: val = int(val) t.right(val) except ValueError: messagebox.showinfo('Error', 'Wrong value') t.listen()
def main(): # use sys.argv if needed print('generating spirograph...') # create parser descStr = """This program draws spirographs using the Turtle module. When run with no arguments, this program draws random spirographs. Terminology: R: radius of outer circle. r: radius of inner circle. l: ratio of hole distance to r. """ parser = argparse.ArgumentParser(description=descStr) # add expected arguments parser.add_argument('--sparams', nargs=3, dest='sparams', required=False, help="The three arguments in sparams: R, r, l.") # parse args args = parser.parse_args() # set to 80% screen width turtle.setup(width=0.8) # set cursor shape turtle.shape('turtle') # set title turtle.title("Spirographs!") # add key handler for saving images turtle.onkey(saveDrawing, "s") # start listening turtle.listen() # hide main turtle cursor turtle.hideturtle() # checks args and draw if args.sparams: params = [float(x) for x in args.sparams] # draw spirograph with given parameters # black by default col = (0.0, 0.0, 0.0) spiro = Spiro(0, 0, col, *params) spiro.draw() else: # create animator object spiroAnim = SpiroAnimator(4) # add key handler to toggle turtle cursor turtle.onkey(spiroAnim.toggleTurtles, "t") # add key handler to restart animation turtle.onkey(spiroAnim.restart, "space") # start turtle main loop turtle.mainloop()
def set_keyboard_handler(fn): ''' Sets callback function to invoke when a key is pressed. The function is passed the name of the key pressed as a string. Only one keyboard handler may be registered at a time. ''' _e.kbdfn = fn # XXX why can't the turtle module just send the !@&^#%$ keysym? canvas = turtle.getcanvas() canvas.bind('<KeyPress>', _E._keypress_cb) turtle.listen()
def tegn_romskip(): turtle.penup() turtle.shapesize(4) turtle.setpos(200, 400) turtle.setheading(90) turtle.color('blue') turtle.onkey(snu_hoyre, 'Right') turtle.onkey(snu_venstre, 'Left') turtle.onkey(bruk_motor, 'Up') turtle.listen()
def middle_layer_sta1(): time.sleep(0.5) turtle.clearscreen() screen_setup() station_1() sp2 = turtle.Turtle() sp2.color('white') sp2.penup() sp2.speed(0) global middle_sta1_pos sp2.setpos(middle_sta1_pos) sp2.seth(90) sp2.showturtle() speed = (10) b = 2 def turnleft(): sp2.left(30) def turnright(): sp2.right(30) def forward(): sp2.forward(speed) def backward(): sp2.backward(speed) def zoom1(): global middle_sta1_pos middle_sta1_pos = sp2.pos() if sp2.xcor() > -162 and sp2.xcor() < -98 and sp2.ycor() > -112 and sp2.ycor() < -64: docking_layer() turtle.onkey(forward, 'Up') turtle.onkey(turnleft, 'Left') turtle.onkey(turnright, 'Right') turtle.onkey(backward, 'Down') turtle.onkey(top_layer, '-') turtle.onkey(zoom1,'=') turtle.listen() for i in range(1000): x = random.randrange(-250, 450) h = random.randrange(220, 340) ship = turtle.Turtle() ship.hideturtle() ship.color('gray') ship.penup() ship.speed(0) ship.setpos(x, 260) ship.showturtle() ship.speed(1) ship.seth(h) ship.forward(1000) if sp2.xcor() > -162 and sp2.xcor() < -98 and sp2.ycor() > -112 and sp2.ycor() < -64: break
def set_listeners(self): turtle.onscreenclick(self.clickcb, 1) # In OSX, ctrl-click doesn't give a button-3 click. Instead, # trackpad users have to enable secondary click in system # preferences. Then, right-clicking on trackpad generates a # button-2 click. I don't know what one-button mouse users can # do? turtle.onscreenclick(self.rightclickcb, 2) # On Linux, right-click generates a button-3 click. turtle.onscreenclick(self.rightclickcb, 3) turtle.onkey(self.spacecb, "space") turtle.onkey(self.savecb, "s") turtle.onkey(self.redisplaycb, "r") turtle.listen()
def set_relative_keyboard_bindings(self): """Maps relative controls to player movement.""" turtle.listen() # Set P1 keyboard bindings turtle.onkeypress(self.P1.turn_left, 'a') turtle.onkeypress(self.P1.turn_right, 'd') turtle.onkeypress(self.P1.accelerate, 'w') turtle.onkeypress(self.P1.decelerate, 's') # Set P2 keyboard bindings turtle.onkeypress(self.P2.turn_left, 'Left') turtle.onkeypress(self.P2.turn_right, 'Right') turtle.onkeypress(self.P2.accelerate, 'Up') turtle.onkeypress(self.P2.decelerate, 'Down')
def save_graph(): import ImageGrab #windows only, for now from tkFileDialog import asksaveasfilename as save canvas = turtle.getscreen().getcanvas() turtle.update() turtle.listen() canvas.update() x0 = canvas.winfo_rootx() y0 = canvas.winfo_rooty() x1 = x0 + canvas.winfo_width() y1 = y0 + canvas.winfo_height() turtle.listen() image = ImageGrab.grab((x0,y0, x1,y1)) filename = save(defaultextension='.png') image.save(filename, "PNG") showinfo("File Saved",("File successfully saved as %s" %filename))
def start(x,y): turtle.onscreenclick(None) level_1() tfood = turtle.Turtle() tfood.hideturtle() tfood.pu() tfood.speed(0) tfood.shape("square") tfood.color("red") tscore = turtle.Turtle() tscore.hideturtle() tscore.pu() tscore.speed(0) tscore.goto(100,-250) tscore.write("Score:" + str(a[0]), align="center",font=(10)) while x > -210 and x < 210 and y > -210 and y <210: if fcoord[2] == 0: food(tfood) fcoord[2] = 1 turtle.onkey(u,"Up") turtle.onkey(l,"Left") turtle.onkey(r,"Right") turtle.onkey(d,"Down") turtle.listen() move() x = turtle.xcor() y = turtle.ycor() if x > fcoord[0]*20-5 and x < fcoord[0]*20+5 and y > fcoord[1]*20-5 and y < fcoord[1]*20+5: fcoord[2] = 0 tfood.clear() a[0] += 1 tscore.clear() tscore.write("Score:" + str(a[0]), align="center",font=(10)) if len(pos) > 1: for i in range(1,len(pos)): if x < pos[i][0]+5 and x > pos[i][0]-5 and y < pos[i][1]+5 and y > pos[i][1]-5: tscore.clear() tfood.clear() gameover() tscore.clear() tfood.clear() gameover()
def set_abs_keyboard_bindings(self): """Maps absolute controls to player movement.""" turtle.listen() # Set P1 keyboard bindings if self.P1.heading() == 0: # East turtle.onkeypress(self.P1.turn_left, 'w') turtle.onkeypress(self.P1.turn_right, 's') turtle.onkeypress(self.P1.accelerate, 'd') turtle.onkeypress(self.P1.decelerate, 'a') elif self.P1.heading() == 90: # North turtle.onkeypress(self.P1.turn_left, 'a') turtle.onkeypress(self.P1.turn_right, 'd') turtle.onkeypress(self.P1.accelerate, 'w') turtle.onkeypress(self.P1.decelerate, 's') elif self.P1.heading() == 180: # West turtle.onkeypress(self.P1.turn_left, 's') turtle.onkeypress(self.P1.turn_right, 'w') turtle.onkeypress(self.P1.accelerate, 'a') turtle.onkeypress(self.P1.decelerate, 'd') elif self.P1.heading() == 270: # South turtle.onkeypress(self.P1.turn_left, 'd') turtle.onkeypress(self.P1.turn_right, 'a') turtle.onkeypress(self.P1.accelerate, 's') turtle.onkeypress(self.P1.decelerate, 'w') # Set P1 keyboard bindings if self.P2.heading() == 0: # East turtle.onkeypress(self.P2.turn_left, 'Up') turtle.onkeypress(self.P2.turn_right, 'Down') turtle.onkeypress(self.P2.accelerate, 'Right') turtle.onkeypress(self.P2.decelerate, 'Left') elif self.P2.heading() == 90: # North turtle.onkeypress(self.P2.turn_left, 'Left') turtle.onkeypress(self.P2.turn_right, 'Right') turtle.onkeypress(self.P2.accelerate, 'Up') turtle.onkeypress(self.P2.decelerate, 'Down') elif self.P2.heading() == 180: # West turtle.onkeypress(self.P2.turn_left, 'Down') turtle.onkeypress(self.P2.turn_right, 'Up') turtle.onkeypress(self.P2.accelerate, 'Left') turtle.onkeypress(self.P2.decelerate, 'Right') elif self.P2.heading() == 270: # South turtle.onkeypress(self.P2.turn_left, 'Right') turtle.onkeypress(self.P2.turn_right, 'Left') turtle.onkeypress(self.P2.accelerate, 'Down') turtle.onkeypress(self.P2.decelerate, 'Up')
def __init__(self, win, turtle, cmd): self.win = win self.turtle = turtle self.cmd = cmd self.overwrite = False self.state_stack = [] # set up key bindings self.win.onkey(self.reset, "r") self.win.onkey(self.next_evolution, "n") self.win.onkey(self.clear, "c") self.win.onkey(self.toggle_overwrite, "o") self.win.onkey(self.close, "Escape") # store initial turtle position self.init_pos, self.init_heading = self.turtle.pos(), self.turtle.heading() self.draw() t.listen() t.mainloop()
def hold(self): """ holds the screen open until the user clicks or types 'q' """ # have the turtle listen for events turtle.listen() # hide the turtle and update the screen turtle.ht() turtle.update() # have the turtle listen for 'q' turtle.onkey( turtle.bye, 'q' ) # have the turtle listen for a click turtle.onscreenclick( lambda x,y: turtle.bye() ) # start the main loop until an event happens, then exit turtle.mainloop() exit()
def main(): descStr = "This draws spirographs with turtle graphics, if no arguments are given, random spirographs will be drawn." parser = argparse.ArgumentParser(description=descStr) #add expected args parser.add_argument('--sparams', nargs=3, dest='sparams', required=False, help="The three arguments in sparams: R, r, l.") #parse args args = parser.parse_args() #set width of window to 80% of screen width turtle.setup(width=0.8) #set cursor shape to turtle turtle.shape('turtle') #set title to Spirographs! turtle.title("Spirographs!") #add keyhandler to save drawings turtle.onkey(saveDrawing, 's') #start listening turtle.listen() #hide main turtle cursor turtle.hideturtle() #check for any arguments sent to --sparams and draw spirograph if args.sparams: params = [float(x) for x in args.sparams] #draw spiro with given params col = (0.0, 0.0, 0.0) spiro = Spiro(0, 0, col, *params) spiro.draw() else: #create animator objects span = SpiroAnimator(6) #add key handler to toggle cursor turtle.onkey(span.toggleTurtles, "t") #add keyhandler to restart turtle.onkey(span.restart, "space") #start main loop turtle.mainloop()
import turtle as t def turn_right(): t.seth(0) t.fd(10) def turn_up(): t.seth(90) t.fd(10) def turn_left(): t.seth(180) t.fd(10) def turn_down(): t.seth(270) t.fd(10) def blank(): t.clear() t.shape("turtle") t.speed(0) t.onkeypress(turn_right, "Right") t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.onkeypress(blank, "Escape") t.listen() t.mainloop() #거북이 그래픽 창을 종료할 때까지 마우스나 키보드 입력을 계속 처리하도록 하는 함수
tl.dot(120, 'blue') tl.back(100) tl.right(120) tl.update() def animate(): "Animate fidget spinner." if state['turn'] > 0: state['turn'] -= 1 spinner() tl.ontimer(animate, 20) def flick(): "Flick fidget spinner." state['turn'] += 10 tl.setup(420, 420, 370, 0) tl.hideturtle() tl.tracer(False) tl.width(20) tl.onkey(flick, 'space') tl.listen() animate() tl.done() tl.bye() print("hi")
y = player.ycor() + 10 bullet.setposition(x,y) bullet.showturtle() bullet_state = "fire" #universal collision fn for checking multiple collisions using 'pythagoras theoram' def collision(t1,t2): distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2) + math.pow(t1.ycor()-t2.ycor(),2)) # math.pow(a,b), a-base,b-power, math.sqrt(c) # if abs(t1.xcor() - t2.xcor())<10 and abs(t2.ycor() - t2.ycor() - not working properly if distance<10: return True else: return False #keyboard binding, key's working t.listen() # listen to keyboard action t.onkey(move_left,"Left") # when left key is pressed 'move_left' fn is called t.onkey(move_right,"Right") # when right key is pressed 'move_right' fn is called t.onkey(bfire,"space") # when spacebar is pressed 'fire' fn is called #game loop while True: #enemy movement x = enemy.xcor() x += enemy_spd enemy.setx(x) #right --> if x>280: y = enemy.ycor() y -= 25 # when enemy touches right boundry it'll get down by 25 pixels
def main(): display_help_window() scr = turtle.Screen() turtle.mode('standard') xsize, ysize = scr.screensize() turtle.setworldcoordinates(0, 0, xsize, ysize) turtle.hideturtle() turtle.speed('fastest') turtle.tracer(0, 0) turtle.penup() board = LifeBoard(xsize // CELL_SIZE, 1 + ysize // CELL_SIZE) # Set up mouse bindings def toggle(x, y): cell_x = x // CELL_SIZE cell_y = y // CELL_SIZE if board.is_legal(cell_x, cell_y): board.toggle(cell_x, cell_y) board.display() turtle.onscreenclick(turtle.listen) turtle.onscreenclick(toggle) board.makeRandom() board.display() # Set up key bindings def erase(): board.erase() board.display() turtle.onkey(erase, 'e') def makeRandom(): board.makeRandom() board.display() turtle.onkey(makeRandom, 'r') turtle.onkey(sys.exit, 'q') # Set up keys for performing generation steps, either one-at-a-time or not. continuous = False def step_once(): nonlocal continuous continuous = False perform_step() def step_continuous(): nonlocal continuous continuous = True perform_step() def perform_step(): board.step() board.display() # In continuous mode, we set a timer to display another generation # after 25 millisenconds. if continuous: turtle.ontimer(perform_step, 25) turtle.onkey(step_once, 's') turtle.onkey(step_continuous, 'c') # Enter the Tk main loop turtle.listen() turtle.mainloop()
def docking(): cr = turtle.Turtle() cr.hideturtle() cr.color('gray') cr.speed(0) cr.penup() cr.setpos(0,250) cr.seth(270) cr.pendown() cr.forward(500) cr.penup() cr.setpos(450,0) cr.seth(180) cr.pendown() cr.forward(900) def left(): global cenx global x x = x-10 cenx = cenx-10 def right(): global cenx global x x = x+10 cenx = cenx+10 def up(): global y global ceny y = y+10 ceny = ceny+10 def down(): global y global ceny y = y-10 ceny = ceny-10 for i in range(100): global r global x global cens ma.setx(cenx) ma.sety(ceny) al.setx(x) al.sety(y) al.pendown() al.seth(90) al.clear() ma.clear() al.circle(r) ma.dot(cens, 'white') al.penup() r = r+1 x = x+1 if cens <= 10: cens+0.5 turtle.onkey(left, 'Left') turtle.onkey(right, 'Right') turtle.onkey(up, 'Up') turtle.onkey(down, 'Down') turtle.listen() turtle.delay(50)
star_x = random.randint(-230, 230) star_y = random.randint(-230, 230) ts.goto(star_x, star_y) # 먹이를 다른 곳으로 옮깁니다. if playing: t.ontimer(play, 100) # 게임 플레이 중이면 0.1초 후 play 함수를 실행합니다. def message(m1, m2): # 메시지를 화면에 표시하는 함수 t.clear() t.goto(0, 100) t.write(m1, False, "center", ("", 20)) t.goto(0, -100) t.write(m2, False, "center", ("", 15)) t.home() t.title("Turtle Run") t.setup(500, 500) t.bgcolor("orange") t.shape("turtle") # 거북이 모양의 커서를 사용합니다. t.speed(0) # 거북이 속도를 가장 빠르게로 지정합니다 t.up() t.color("white") t.onkeypress(turn_right, "Right") # [→]를 누르면 turn_right 함수를 실행하도록 합니다. t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.onkeypress(start, "space") t.listen() # 거북이 그래픽 창이 키보드 입력을 받도록 합니다. message("Turtle Run", "[Space]")
import turtle turtle.penup() turtle.ht() def up(): print("You pressed Up!") def down(): print("You pressed Down!") def left(): print("You pressed Left!") def right(): print("You pressed Right!") turtle.onkey(up, 'Up') turtle.onkey(down, 'Down') turtle.onkey(left, 'Left') turtle.onkey(right, 'Right') def repeat(): turtle.ontimer(repeat, 500) turtle.listen() # Remember to put this after your listeners!
def gamestart(x, y): start_button.clear() start_button.hideturtle() labels.clear() enemy_number_text.clear() left_arrow.hideturtle() right_arrow.hideturtle() difficulty_text.clear() left_arrow_2.hideturtle() right_arrow_2.hideturtle() turtle.bgpic("ust2.gif") # Use the global variables here because we will change them inside this # function global player, laser, score, score_label, score_display # Score display initialization score_label.up() score_label.goto(-260, 275) score_label.color("Red") score_label.write("Score:", font=("System", 12, "bold"), align = "center") # Value display score_display.up() score_display.goto(-220, 275) score_display.color("Red") score_display.write(str(score), font=("System", 12, "bold"), align = "center") ### Player turtle ### # Add the spaceship picture turtle.addshape("redbird.gif") # Create the player turtle and move it to the initial position player = turtle.Turtle() player.shape("redbird.gif") player.up() player.goto(player_init_x, player_init_y) # Map player movement handlers to key press events turtle.onkeypress(playermoveleft, "Left") turtle.onkeypress(playermoveright, "Right") turtle.listen() ### Enemy turtles ### # Add the enemy picture turtle.addshape("closedbook.gif") turtle.addshape("openbook.gif") for i in range(enemy_number): # Create the turtle for the enemy enemy = turtle.Turtle() enemy.shape("closedbook.gif") enemy.up() # Move to a proper position counting from the top left corner enemy.goto(enemy_init_x + enemy_size * (i % 6), enemy_init_y - enemy_size * (i // 6)) # Add the enemy to the end of the enemies list enemies.append(enemy) turtle.onkeypress(stopkeypressed, 's') ### Laser turtle ### turtle.addshape("pen.gif") # Create the laser turtle laser = turtle.Turtle() laser.up() laser.shape("pen.gif") # Hide the laser turtle laser.hideturtle() turtle.onkeypress(shoot, "space") turtle.update() # Start the game by running updatescreen() turtle.ontimer(updatescreen, update_interval)
def main(): display_help_window() scr = turtle.Screen() turtle.colormode('standard') xsize, ysize = scr.screensize() turtle.setworldcoordinates(0, 0, xsize, ysize) turtle.hideturtle() turtle.speed('fastest') turtle.tracer(0, 0) turtle.penup() board = LifeBoard(xsize // CELL_SIZE, 1 + ysize // CELL_SIZE) def toggle(x, y): cellx = x // CELL_SIZE celly = y // CELL_SIZE if board.is_legal(cellx, celly): board.toggle(cellx, celly) board.display() turtle.onscreenclick(turtle.listen) turtle.onscreenclick(toggle) board.makeRandom() board.display() def erase(): board.erase() board.display() turtle.onkey(erase, 'e') def makeRandom(): board.makeRandom() board.display() turtle.onkey(makeRandom, 'r') turtle.onkey(sys.exit, 'q') continuous = False def step_once(): nonlocal continuous #continuous variable but a new one not the same scope continuous = False perform_step() def step_continuous(): nonlocal continuous continuous = True perform_step() def perform_step(): board.step() board.display() if continuous: turtle.ontimer(perform_step, 1) turtle.onkey(step_once, 's') turtle.onkey(step_continuous, 'c') def up_size(): global CELL_SIZE CELL_SIZE += 1 makeRandom() def down_size(): global CELL_SIZE CELL_SIZE -= 1 makeRandom() turtle.onkey(up_size, '+') turtle.onkey(down_size, '-') turtle.listen() turtle.mainloop()
def visLife(foerste,naeste,levende,klik): cs = 10 # celleside, global konstant tt.Screen() tt.speed('fastest') tt.hideturtle() tt.penup() kodefarve = ['white','blue','red','green','black'] # 0 = død, lige klikantal; 1 = levende, lige klikantal # 2 = levende, ulige klikantal; 3 = død, ulige klikantal; 4 = gitter # Lærredet bruger koordinater (x,y) og spillet koordinater (i,j) # Globale (x0,y0) er placering af tænkt celle (0,0) def toXY(i,j): return i*cs+x0,j*cs+y0 def fromXY(x,y): return int(floor(float(x-x0)/cs)),int(floor(float(y-y0)/cs)) def tegnGitter(i0,i1,j0,j1): """Gitteret har søjler fra i0 til og med i1 og rækker fra j0 til og med j1. Først blankstilles lærredet""" xmin,ymin = toXY(i0,j0) xlen,ylen = (i1-i0+2)*cs,(j1-j0+2)*cs tt.clear() tt.penup() tt.color(kodefarve[4]) # vandrette linjer x,y = xmin-cs/2,ymin tt.setheading(0) # øst for j in range(j0,j1+2): tt.goto(x,y) tt.pendown() tt.forward(xlen) tt.penup() y += cs # lodrette linjer x,y = xmin,ymin-cs/2 tt.setheading(90) # nord for i in range(i0,i1+2): tt.goto(x,y) tt.pendown() tt.forward(ylen) tt.penup() x += cs def tegnCelle(i,j,farve): x,y = toXY(i,j) tt.goto(x+1,y+1) tt.setheading(0) # øst tt.color(farve) tt.fill(True) tt.pendown() for k in range(4): tt.forward(cs-2) tt.left(90) tt.fill(False) tt.penup() def tegnGen(i0,i1,j0,j1): """Gitteret har søjler fra i0 til og med i1 og rækker fra j0 til og med j1""" for i in range(i0,i1+1): for j in range(j0,j1+1): skyggegen[(i,j)] = 0 # død if levende(i,j): tegnCelle(i,j,kodefarve[1]) skyggegen[(i,j)] = 1 # levende def skift(x,y): """Knyttes til museklik""" i,j = fromXY(x,y) if (i,j) in skyggegen: farvekode = 3 - skyggegen[(i,j)] # vend farve skyggegen[(i,j)] = farvekode tegnCelle(i,j,kodefarve[farvekode]) klik(i,j) def tast(): """Knyttes til tast af mellemrum""" i0,i1,j0,j1 = naeste() skyggegen = {} tegnGitter(i0,i1,j0,j1) tegnGen(i0,i1,j0,j1) def stop(): """Knyttes til tast af Escape""" tt.bye() # første generation i0,i1,j0,j1 = foerste() # beregn basis, dvs. placering af tænkt celle (0,0) x0,y0 = -(i0+i1+1)*cs/2,-(j0+j1+1)*cs/2 skyggegen = {} tegnGitter(i0,i1,j0,j1) tegnGen(i0,i1,j0,j1) # begivendhedsstyring: tt.onscreenclick(skift) tt.onkey(tast,'space') tt.onkey(stop,'Escape') tt.listen() tt.mainloop()
bullet.setposition(x, y + 10) bullet.showturtle() def isCollision(t1, t2): distance = math.sqrt( math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2)) if distance < 15: return True else: return False #create keyboard bindings turtle.listen() turtle.onkey(move_left, "Left") turtle.onkey(move_right, "Right") turtle.onkey(fire_bullet, "space") #main game loop while True: #move the enemy x = enemy.xcor() x += enemyspeed enemy.setx(x) #move the enemy back and down if enemy.xcor() > 280: y = enemy.ycor()
STEPSIZE = 500 direction = LEFT def up(): global direction direction = UP def down(): global direction direction = DOWN def left(): global direction direction = LEFT def right(): global direction direction = RIGHT t.onkey(up, 'Up') t.onkey(down, 'Down') t.onkey(left, 'Left') t.onkey(right, 'Right') def repeat(): print(direction) t.ontimer(repeat, STEPSIZE) t.listen()
h = turtle.window_height() if t.ycor() < h/2 - 10: t.seth(90) t.forward(10) def paint(): t.pendown() def dont_paint(): t.penup() def spin(x, y): t.left(2*360) t.right(2*360) t.onclick(spin) turtle.onscreenclick(move) turtle.onkey(move_right, 'Right') turtle.onkey(move_left, 'Left') turtle.onkey(move_up, 'Up') turtle.onkey(move_down, 'Down') turtle.onkey(paint, 'U') turtle.onkey(dont_paint, 'D') turtle.listen()
def screen_undo(): garo.undo() def screen_clear(): garo.clear() def exit(): garo.bye() # Event Listening garo.listen() # Controls # Movements garo.onkey(up, 'w') garo.onkey(down, 's') garo.onkey(left, 'a') garo.onkey(right, 'd') garo.onkey(upper_left, 'q') garo.onkey(lower_left, 'z') garo.onkey(upper_right, 'e') garo.onkey(lower_right, 'c') garo.onkey(home, 'x') # Pen up, Pen down,