# ArrowDraw.py import turtle t = turtle.Pen() t.speed(0) t.turtlesize(2,2,2) def up(): t.forward(50) def left(): t.left(90) def right(): t.right(90) turtle.onkeypress(up, "Up") turtle.onkeypress(left, "Left") turtle.onkeypress(right, "Right") turtle.listen()
def loadkeystoturtle(): config = configparser.ConfigParser() config.optionxform=str # preserve case config.read('config.ini') for section in config.sections(): if section.lower() == 'keys': for key in config[section]: name = config['Keys'][key] obta = sys.modules[__name__] if hasattr(obta, name): func = getattr(obta, name) # a function with no arguments or None # try: turtle.onkeypress(func, key)
direction=DOWN #Change direction to up print("You pressed the down key!") #2. Make functions down(), left(), and right() that change direction ####WRITE YOUR CODE HERE!! turtle.onkeypress(up, UP_ARROW) # Create listener for up key turtle.onkeypress(down, DOWN_ARROW) turtle.onkeypress(left, LEFT_ARROW) turtle.onkeypress(right, RIGHT_ARROW) #3. Do the same for the other arrow keys ####WRITE YOUR CODE HERE!! turtle.listen() def make_food(): #The screen positions go from -SIZE/2 to +SIZE/2 #But we need to make food pieces only appear on game squares #So we cut up the game board into multiples of SQUARE_SIZE. min_x=-int(SIZE_X/2/SQUARE_SIZE)+1
UP_EDGE = 450 DOWN_EDGE = -450 RIGHT_EDGE = 900 LEFT_EDGE = -900 def up (): global direction direction = UP print('you pressed the Up key!') def down (): global direction direction = DOWN print('you pressed the Down key!') turtle.onkeypress(up,UP_ARROW) turtle.onkeypress(down,DOWN_ARROW) turtle.listen() def move_pong(): global direction my_pos = pong.pos() x_pos = my_pos[0] y_pos = my_pos[1] elif direction==UP: pong.goto(x_pos,SQUARE_SIZE+y_pos) print('you moved up') elif direction==DOWN: pong.goto(x_pos,y_pos-SQUARE_SIZE) print('you moved down')
def enable_keys(pl): onkeypress(pl.goleft, "Left") onkeypress(pl.goright, "Right")
for i in (turtle_pos): print(i) while True: pacman.fd(1) def k1(): pacman.setheading(90) def k2(): pacman.setheading(180) def k3(): pacman.setheading(270) def k4(): pacman.setheading(0) turtle.onkeypress(k1, "Up") turtle.onkeypress(k2, "Left") turtle.onkeypress(k3, "Down") turtle.onkeypress(k4, "Right") turtle.listen() for i in (turtle_pos): turtle.mainloop()
def slow(): global spd spd -= 1 def shoot(): global pen bull = turtle.Turtle() bull.shape("circle") bull.pu() bull.speed(100) bull.shapesize(0.5, 0.5, 0.5) bull.setposition(round(pen.xcor(), 1), round(pen.ycor(), 1)) bull.left(pen.heading()) bull.speed(2) bull.forward(200) bull.ht() print(bull.shapesize()) turtle.onkeypress(f, "w") turtle.onkeypress(ri, "d") turtle.onkeypress(le, "a") turtle.onkeypress(slow, "s") turtle.onkeypress(shoot, "space") screen.onclick(pen.goto) wasd = screen.textinput("Name", "Name: ") turtle.listen() # main part while True: pen.forward(spd)
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 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)
t.color("black") #거북이 색 검정색으로 되돌리기 t.goto(-200, 10) #거북이 위치 처음 발사 했던 곳으로 되돌리기 t.setheading(ang) #각도가 처음 기억해둔 각도로 되돌리기 # 땅그리기 t.goto(-300,0) t.down() t.goto(300,0) # 목표 지점 설정그리기 target = random.randint(50, 150) t.pensize(3) t.color("green") t.up() t.goto(target - 25,2) t.down() t.goto(target + 25,2) # 거북이 색 검은색 지정 처음 발사했던곳으로 되돌리기 t.color("black") t.up t.goto(-200, 10) t.setheading(20) # 거북이 동작 t.onkeypress(turn_up, "Up") t.onkeypress(turn_down, "Down") t.onkeypress(fire, "space") t.listen()
turtle.pendown() #Movement def up(): turtle.forward(10) def down(): turtle.back(10) def right(): turtle.right(45) def left(): turtle.left(45) turtle.onkeypress(up, "w") turtle.onkeypress(down, "s") turtle.onkeypress(right, "d") turtle.onkeypress(left, "a") turtle.pensize(20) turtle.pencolor('red') turtle.listen() turtle.mainloop()
def keyboard_bindings(): # Create keyboard bindings listen() onkeypress(move_left, "Left") onkeypress(move_right, "Right") onkeypress(move_up, "Up") onkeypress(move_down, "Down") onkeypress(build_wall, "space") onkeypress(remove_wall, "Control_L") onkeypress(set_start_cell, "F1") onkeypress(set_finish_cell, "F2") onkeypress(end_of_drawing, "Escape") onkeypress(save_file, "s") onkeypress(restart_maze, "Delete")
def play_game(): entry_window.withdraw() player_name = e.get() delay = 0.1 score = 0 boundary_width = 620 boundary_height = 620 screen = turtle.Screen() screen.title('Snake Game') screen.bgcolor('green') screen.setup(width=1500, height=800) screen.tracer(0) boundary = turtle.Turtle() boundary.speed(0) boundary.color('black') boundary.hideturtle() boundary.pensize(3) boundary.up() boundary.goto(-boundary_width / 2, -boundary_height / 2) boundary.down() for i in range(4): if i % 2 == 0: boundary.forward(boundary_width) else: boundary.forward(boundary_height) boundary.left(90) snake_head = turtle.Turtle() snake_head.speed(0) snake_head.color('blue') snake_head.shape('square') snake_head.up() snake_head.direction = 'stop' snake_body = [] snake_food = turtle.Turtle() snake_food.speed(0) snake_food.color('red') snake_food.shape('circle') snake_food.up() snake_food.goto( random.randint(-boundary_width / 2 + 15, boundary_width / 2 - 15), random.randint(-boundary_height / 2 + 15, boundary_height / 2 - 15)) pen = turtle.Turtle() pen.speed(0) pen.color('white') pen.hideturtle() pen.up() pen.goto(0, -boundary_height / 2 - 50) pen.write('SCORE: {}'.format(score), align='center', font=('Comic Sans MS', 20, 'bold')) def go_up(): if snake_head.direction != 'down': snake_head.direction = 'up' def go_down(): if snake_head.direction != 'up': snake_head.direction = 'down' def go_left(): if snake_head.direction != 'right': snake_head.direction = 'left' def go_right(): if snake_head.direction != 'left': snake_head.direction = 'right' def move(): if snake_head.direction == 'up': snake_head.sety(snake_head.ycor() + 20) if snake_head.direction == 'down': snake_head.sety(snake_head.ycor() - 20) if snake_head.direction == 'left': snake_head.setx(snake_head.xcor() - 20) if snake_head.direction == 'right': snake_head.setx(snake_head.xcor() + 20) turtle.listen() turtle.onkeypress(go_left, 'Left') turtle.onkeypress(go_right, 'Right') turtle.onkeypress(go_up, 'Up') turtle.onkeypress(go_down, 'Down') while True: screen.update() if snake_head.distance(snake_food) < 20: score += 1 snake_food.goto( random.randint(-boundary_width / 2 + 15, boundary_width / 2 - 15), random.randint(-boundary_height / 2 + 15, boundary_height / 2 - 15)) body = turtle.Turtle() body.speed(0) body.color('black') body.shape('square') body.up() snake_body.append(body) pen.clear() pen.write('SCORE: {}'.format(score), align='center', font=('Comic Sans MS', 20, 'bold')) delay -= 0.001 for i in range(len(snake_body) - 1, 0, -1): snake_body[i].goto(snake_body[i - 1].xcor(), snake_body[i - 1].ycor()) if len(snake_body) > 0: snake_body[0].goto(snake_head.xcor(), snake_head.ycor()) move() if (snake_head.xcor() > (boundary_width / 2 - 10)) or ( snake_head.xcor() < (-boundary_width / 2 + 10)) or ( snake_head.ycor() > (boundary_height / 2 - 10)) or ( snake_head.ycor() < (-boundary_height / 2 + 10)): screen.bye() display_score(player_name, score) for i in range(1, len(snake_body)): if (snake_body[i].distance(snake_head) < 20): screen.bye() display_name(player_name, score) time.sleep(delay) screen.mainloop()
t.forward(10) def turn_left(): t.setheading(180) t.forward(10) def turn_up(): t.setheading(90) t.forward(10) def turn_down(): t.setheading(270) t.forward(10) def blank(): t.clear() t.shape("turtle") t.speed(0) t.onkeypress(turn_right, "Right") t.onkeypress(turn_left, "Left") t.onkeypress(turn_up, "Up") t.onkeypress(turn_down, "Down") t.onkeypress(blank, "Escape") t.listen()
def down(): global direction direction = down print('You pressed down!') old_pos = turtle.pos() x = old_pos[0] y = old_pos[1] turtle.goto(x, y - 10) print(turtle.pos()) def right(): global direction direction = right print('You pressed right!') old_pos = turtle.pos() x = old_pos[0] y = old_pos[1] turtle.goto(x + 10, y) print(turtle.pos()) turtle.onkeypress(up, up_arrow) turtle.onkeypress(left, left_arrow) turtle.onkeypress(down, down_arrow) turtle.onkeypress(right, right_arrow) turtle.onkeypress(turtle.stamp, spacebar) turtle.listen() turtle.mainloop()
def down(): global direction direction = DOWN print('you pressed the down key') def left(): global direction direction = LEFT print('you pressed the left key') def right(): global direction direction = RIGHT print('you pressed the right key') turtle.onkeypress(up, UP_ARROW) turtle.onkeypress(down, DOWN_ARROW) turtle.onkeypress(left, LEFT_ARROW) turtle.onkeypress(right, RIGHT_ARROW) turtle.listen() def move_bird(): my_pos = turtle.pos() x_pos = my_pos[0] y_pos = my_pos[1] if direction == RIGHT: turtle.goto(x_pos + 10,y_pos) elif direction == LEFT:
global temp_current_direction if allowed_move(RIGHT): temp_current_direction = RIGHT def move_up(): global temp_current_direction if allowed_move(UP): temp_current_direction = UP def move_down(): global temp_current_direction if allowed_move(DOWN): temp_current_direction = DOWN # Keypress listeners turtle.onkeypress(move_left, "Left") turtle.onkeypress(move_right, "Right") turtle.onkeypress(move_up, "Up") turtle.onkeypress(move_down, "Down") turtle.listen() # Initialize food food_positions = [] food_stamps = [] food = turtle.clone() turtle.register_shape("apple.gif") food.shape("apple.gif") # Spawns a new food, removes the oldest food if there are too many on the board def spawn_food(): if game_over:
screen.ontimer(blink_on, 450) screen.ontimer(blink_on, 1) #vincular tecla para iniciar start = False def start_pressed(): global start start = True turtle.listen() turtle.onkeypress(start_pressed, "Return") while not start: screen.update() ball.showturtle() def paddle_up(n1): if n1 == 1: p = paddle_1 else: p = paddle_2 y = p.ycor() if y < 250: y += 30 else: y = 250
def buildWindow(self): self.master.title("Huada's Draw Program") bar = tkinter.Menu(self.master) fileMenu = tkinter.Menu(bar, tearoff=0) self.graphicsCommands = PyList() def newWindow(): theTurtle.clear() theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() screen.update() screen.listen() self.graphicsCommands = PyList() fileMenu.add_command(label="New",command=newWindow) def parse(filename): xmldoc = xml.dom.minidom.parse(filename) graphicsCommandsElement = xmldoc.getElementsByTagName("GraphicsCommands")[0] graphicsCommands = graphicsCommandsElement.getElementsByTagName("Command") for commandElement in graphicsCommands: print(type(commandElement)) command = commandElement.firstChild.data.strip() attr = commandElement.attributes if command == "GoTo": x = float(attr["x"].value) y = float(attr["y"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = GoToCommand(x,y,width,color) elif command == "Rectangular": longside = float(attr["longside"].value) shortside = float(attr["shortside"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = RectangularCommand(longside,shortside,width,color) elif command == "Circle": radius = float(attr["radius"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = CircleCommand(radius, width, color) elif command == "BeginFill": color = attr["color"].value.strip() cmd = BeginFillCommand(color) elif command == "EndFill": cmd = EndFillCommand() elif command == "PenDown": cmd = PenDownCommand() else: raise RuntimeError("Unkonwn Command: " + command) self.graphicsCommands.append(cmd) def loadFile(): filename = tkinter.filedialog.askopenfilename(title="Select a Graphics File") newWindow() self.graphicsCommands = PyList() parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() fileMenu.add_command(label="Load...",command=loadFile) def addToFile(): filename = tkinter.filedialog.askopenfilename(title="Select a Graphics File") theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() theTurtle.pencolor("#000000") theTurtle.fillcolor("#000000") cmd = PenUpCommand() self.graphicsCommands.append(cmd) cmd = GoToCommand(0,0,1,"#000000") self.graphicsCommands.append(cmd) cmd = PenUpCommand() self.graphicsCommands.append(cmd) screen.update() parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() fileMenu.add_command(label="Load Into ...",command=addToFile) def write(filename): file = open(filename, "w") file.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n') file.write('<GraphicsCommands>\n') for cmd in self.graphicsCommands: file.write(' '+str(cmd)+"\n") file.write('</GraphicsCommands>\n') file.close() def saveFile(): filename = tkinter.filedialog.asksaveasfilename(title="Save Picture As...") write(filename) fileMenu.add_command(label="Save As...",command=saveFile) fileMenu.add_command(label="Exit",command=self.master.quit) bar.add_cascade(label="File",menu=fileMenu) self.master.config(menu=bar) canvas = tkinter.Canvas(self,width=600,height=600) canvas.pack(side=tkinter.LEFT) theTurtle = turtle.RawTurtle(canvas) theTurtle.shape("circle") screen = theTurtle.getscreen() screen.tracer(0) sideBar = tkinter.Frame(self,padx=5,pady=5) sideBar.pack(side=tkinter.RIGHT, fill=tkinter.BOTH) pointLabel = tkinter.Label(sideBar,text="Width") pointLabel.pack() widthSize = tkinter.StringVar() widthEntry = tkinter.Entry(sideBar,textvariable=widthSize) widthEntry.pack() widthSize.set(str(1)) radiusLabel = tkinter.Label(sideBar,text="Radius") radiusLabel.pack() radiusSize = tkinter.StringVar() radiusEntry = tkinter.Entry(sideBar,textvariable=radiusSize) radiusSize.set(str(10)) radiusEntry.pack() longsideLabel = tkinter.Label(sideBar,text="Longside") longsideLabel.pack() longsideSize = tkinter.StringVar() longsideEntry = tkinter.Entry(sideBar,textvariable=longsideSize) longsideSize.set(str(10)) longsideEntry.pack() shortsideLabel = tkinter.Label(sideBar,text="shortside") shortsideLabel.pack() shortsideSize = tkinter.StringVar() shortsideEntry = tkinter.Entry(sideBar,textvariable=shortsideSize) shortsideSize.set(str(10)) shortsideEntry.pack() def rectangularHandler(): cmd = RectangularCommand(float(longsideSize.get()),float(shortsideSize.get()),float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() rectangularButton = tkinter.Button(sideBar,text = "Draw Rectangular", command=rectangularHandler) rectangularButton.pack(fill=tkinter.BOTH) def circleHandler(): cmd = CircleCommand(float(radiusSize.get()),float(widthSize.get()), penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() circleButton = tkinter.Button(sideBar, text ="Draw Circle", command=circleHandler) circleButton.pack(fill=tkinter.BOTH) screen.colormode(255) penLabel = tkinter.Label(sideBar,text="Pen Color") penLabel.pack() penColor = tkinter.StringVar() penEntry = tkinter.Entry(sideBar, textvariable=penColor) penEntry.pack() penColor.set("#000000") def getPenColor(): color = tkinter.colorchooser.askcolor() if color != None: penColor.set(str(color)[-9:-2]) penColorButton = tkinter.Button(sideBar, text="Pick Pen Color", command=getPenColor) penColorButton.pack(fill=tkinter.BOTH) fillLabel = tkinter.Label(sideBar,text="Fill Color") fillLabel.pack() fillColor = tkinter.StringVar() fillEntry = tkinter.Entry(sideBar,textvariable=fillColor) fillEntry.pack() fillColor.set("#000000") def getFillColor(): color = tkinter.colorchooser.askcolor() if color != None: fillColor.set(str(color)[-9:-2]) fillColorButton = \ tkinter.Button(sideBar, text= "Pick Fill Color",command=getFillColor) fillColorButton.pack(fill=tkinter.BOTH) def beginFillHandler(): cmd = BeginFillCommand(fillColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) beginFillButton = tkinter.Button(sideBar, text="Begin Fill",command=beginFillHandler) beginFillButton.pack(fill=tkinter.BOTH) def endFillHandler(): cmd = EndFillCommand() cmd.draw(theTurtle) self.graphicsCommands.append(cmd) endFillButton = tkinter.Button(sideBar,text = "End Fill", command=endFillHandler()) endFillButton.pack(fill=tkinter.BOTH) penLabel = tkinter.Label(sideBar,text="Pen Is Down") penLabel.pack() def penUpHandler(): cmd = PenUpCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Up") self.graphicsCommands.append(cmd) penUpButton = tkinter.Button(sideBar,text="Pen Up", command=penUpHandler()) penUpButton.pack(fill=tkinter.BOTH) def penDownHandler(): cmd = PenDownCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Down") self.graphicsCommands.append(cmd) penDownButton = tkinter.Button(sideBar,text="Pen Up", command=penDownHandler()) penDownButton.pack(fill=tkinter.BOTH) def clickHandler(x,y): cmd = GoToCommand(x,y,float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() screen.onclick(clickHandler) def dragHandler(x,y): cmd = GoToCommand(x,y,float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() theTurtle.ondrag(dragHandler) def undoHandler(): if len(self.graphicsCommands) > 0: self.graphicsCommands.removeLast() theTurtle.clear() theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() screen.listen() turtle.onkeypress(undoHandler(),"u") screen.listen()
turtle.hideturtle() turtle.register_shape("newnew_bird.gif") birdy = turtle.clone() birdy.shape("newnew_bird.gif") birdy.penup() birdy.showturtle() UP_ARROW = "Up" def grav(): my_pos = birdy.pos() x_pos = my_pos[0] y_pos = my_pos[1] birdy.goto(x_pos, (y_pos - 5)) turtle.ontimer(grav, 30) grav() def up(): for i in range(10): my_pos = birdy.pos() x_pos = my_pos[0] y_pos = my_pos[1] birdy.goto(x_pos, y_pos + 5) turtle.onkeypress(up, UP_ARROW) turtle.listen()
turtle.color("red") def change_color_random(): turtle.pencolor("blue" or "red" or "pink" or "green" or "yellow" or "brown" or "black") def change_color_blue(): turtle.pencolor("blue") turtle.color("blue") def change_color_white(): turtle.pencolor("black") turtle.color("white") turtle.pensize(100) turtle.onkeypress(change_color_red, "r") turtle.onkeypress(change_color_blue, "b") turtle.onkeypress(change_color_white, "w") turtle.onkeypress(change_color_random, "k") turtle.onscreenclick(draw_square, btn=3) turtle.onscreenclick(draw_circle, add=True) turtle.ondrag(turtle.goto, add=True) turtle.ondrag(turtle.goto, btn=3, add=True)
checkResult = False break # Let's check the final result and show an appropriate message if checkResult == True: turtle.clear() turtle.color("red") turtle.write("Congratulations! Your jigsaw is correct!", font=("Arial", 20, "bold")) else: turtle.clear() turtle.color("red") turtle.write("Oh no! Your jigsaw is WRONG!!", font=("Arial", 20, "bold")) ### Here is the main part of the program allTurtles = [] # We will store all the turtles in this list createJigsaw() # Create the jigsaw pieces turtle.onkeypress(checkJigsaw, "c") # Press 'c' whenever you want to check the jigsaw turtle.listen() # Listen for key presses ### Note: turtle.mainloop() is exactly the same as turtle.done() turtle.mainloop( ) # Keep checking if anything is happening, if so do something appropriate
snake.direction="up" move_snake() print("you pressed the up key!") def down(): snake.direction="down" move_snake() print("you pressed the up key!") def left(): snake.direction="left" move_snake() print("you pressed the up key!") def right(): snake.direction="right" move_snake() print("you pressed the up key!") turtle.onkeypress(up,"up") turtle.onkeypress(down,"down") turtle.onkeypress(left,"left") turtle.onkeypress(left,"left") turtle.listen() def move_snake(): my_pos=snake.pos() x_pos=my_pos[0] y_pos=my_pos[1] if snake.direction=="up": snake.goto(x_pos,y_pos+square_size) print("you moved up!") elif snake.direction=="down"(): snake.goto(x_pos,y_pos+square_size) print("you moved down!") elif snake.dire
stick_health = random.randint(1, 5) if bush_health <= 0: bush.setpos(random.randint(-275, 275), random.randint(-275, 275)) bush_health = random.randint(1, 5) if rock_health <= 0: rock.setpos(random.randint(-275, 275), random.randint(-275, 275)) rock_health = random.randint(1, 5) fire.shape('images/campfire1.gif') if alive is True: turtle.ontimer(tick_update, 350) turtle.onkeypress(up, 'w') turtle.onkeypress(down, 's') turtle.onkeypress(left, 'a') turtle.onkeypress(right, 'd') turtle.onkeypress(action, 'e') turtle.onkeypress(eat, '1') turtle.onkeypress(build_campfire, '2') turtle.onkeypress(craft_axe, '3') tick_update() turtle.listen() turtle.mainloop()
dron2.ycor()) < 25: cgeneral = True coldron2(True) bala.pendown() bala.st() bala.shape('recursos/explosion.gif') bala.clear() bala.penup() bala.ht() Balas -= 1 # Llamado de funciones: turtle.listen() # Permite al programa recibir input del teclado. turtle.onkeypress( apuntefr, "Right") # El tanque apunta frontalmente con la tecla 'Derecha'. turtle.onkeypress(apunte45, "Up") # El tanque apunta 45 grados con la tecla 'Arriba'. turtle.onkeypress(tanque_der, "d") # El tanque se mueve a la derecha con la tecla 'D'. turtle.onkeypress(tanque_izq, "a") # El tanque se mueve a la izquierda con la tecla 'A'. turtle.onkeypress(disparo, "space") # El tanque dispara con la tecla 'Espacio'. game_over = False while not game_over: turtle.update() # Actualiza la ventana constantemente. # Actualizacion del scoreboard: if dgeneral is True: # Si el tanque dispara sin importar su angulo:
player.penup() player.speed(0) player.setposition(0, -250) player.setheading(90) playerspeed = 15 #Move the player left and right def move_left(): x = player.xcor() x -= playerspeed if x < -280: x = -280 player.setx(x) def move_right(): x = player.xcor() x += playerspeed if x > 280: x = 280 player.setx(x) #Create keyboard bindings turtle.listen() #Use onkey when you don't want to habilitate long press turtle.onkeypress(move_left, 'Left') turtle.onkeypress(move_right, 'Right') turtle.done()
# Player player = turtle.Turtle() player.tilt(180) player.penup() player.shape("triangle") player.color("yellow") player.shapesize(1,2) def up_move(): player.sety(player.ycor()+5) def down_move(): player.sety(player.ycor()-5) # key board action turtle.listen() turtle.onkeypress(up_move, "space") turtle.onkey(up_move, "w") turtle.onkey(down_move, "Left") turtle.onkeypress(down_move, "s") # parameter for objects x = 2.8 height = 620 gap = 200 screen.tracer(x*10) down_rate = 0.05 Score = 0 while True: screen.update() if x <= 8: x += 0.1 for obj1 in up_wall:
def sol(): turtle.left(90) def sag(): turtle.right(90) def pink(): turtle.pencolor("pink") def speed(): turtle.speed(10) def time(): turtle.time(10) turtle.onkeypress(ileri, "Up") turtle.onkeypress(geri, "Down") turtle.onkeypress(sol, "Left") turtle.onkeypress(sag, "Right") turtle.onkeypress(pink, "p") turtle.onkeypress(speed, "n") turtle.onkeypress(time, "t") turtle.listen()
#move_truck1() def left_1(): global direction_1 direction_1 = LEFT #move_truck1() def right_1(): global direction_1 direction_1 = RIGHT #move_truck1() turtle.onkeypress(up_1, UP_ARROW) turtle.onkeypress(down_1, DOWN_ARROW) turtle.onkeypress(left_1, LEFT_ARROW) turtle.onkeypress(right_1, RIGHT_ARROW) turtle.listen() def up_2(): global direction_2 direction_2 = UP #move_truck2() def down_2(): global direction_2 direction_2 = DOWN
border.forward(760) border.left(90) else: border.forward(650) border.left(90) # border coordinates # 380 -320 # 380 330 # -380 330 # -380 -320 turtle.listen() # turtle.onkeypress(turnleft, 'Left') # turtle.onkeypress(turnright, 'Right') turtle.onkeypress(speedup, 'Up') turtle.onkeypress(speeddown, 'Down') snake[0].penup() snake[0].shape('smiley.gif') snake[0].color('cyan') if len(snake) != 1: wn.listen() follow() #main game code while True: queryMousePosition() xrandno = random.randint(-370, 370) yrandno = random.randint(-310, 320)
pl = Image.open('papernobg.gif') pn=pl.resize((50,50),Image.ANTIALIAS) pn.save('player.gif') turtle.register_shape('player.gif') screen.bgpic = ('thebackground.gif') player.shape('player.gif') player.penup() player.goto(0,450) mazeCube = player.clone() mazeCube.shape('square') def move_left(): x,y = player.pos() player.goto(x-20,y) def move_right(): x,y = player.pos() player.goto(x+20,y) def move_down(): x,y = player.pos() player.goto(x,y-50) turtle.onkeypress(move_left, "Left") turtle.onkeypress(move_right, "Right") turtle.onkeypress(move_down, "Down") turtle.listen()
seaturtle.showturtle() def up(): seaturtle.direction = "Up" #Change direction to up move_seaturtle() print("You pressed the up key!") def down(): seaturtle.direction = "Down" #Change direction to up move_seaturtle() print("You pressed the down key!") turtle.onkeypress(up, "Up") # Create listener for up key turtle.onkeypress(down, "Down") turtle.listen() def dist(pos1, pos2): return ((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2)**0.5 def move_seaturtle(): my_pos = seaturtle.pos() x_pos = my_pos[0] y_pos = my_pos[1] new_pos = seaturtle.pos() new_x_pos = new_pos[0] new_y_pos = new_pos[1]
s = socket.socket() s.connect((IP, KEYPORT)) def forward(): s.send("w".encode()) def backward(): s.send("s".encode()) def left(): s.send("a".encode()) def right(): s.send("d".encode()) def stop(): s.send("q".encode()) turtle.onkeypress(forward, "w") turtle.onkeypress(left, "a") turtle.onkeypress(backward, "s") turtle.onkeypress(right, "d") turtle.onkeypress(stop, "q") turtle.listen()
t.write(m1, False, "center",("", 20)) t.goto(0, -100) t.write(m2, False, "center",("", 20)) t.home() t.title("Turtle Run") t.setup(500, 500) t.shape("turtle") t.bgcolor("skyblue") t.speed(0) t.up() t.color("gold") t.onkeypress(turn_right, "Right") t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.onkeypress(start , "space") t.listen() start()
if(currentColor >= len(colorList)-1): currentColor = 0 else: currentColor += 1 turtle.getscreen().onkeypress(changeColor,"n") ###### #changeShape function def changeShape(): global shapeList global currentShape turtle.shape(shapeList[currentShape]) if currentShape >= len(shapeList)-1: currentShape = 0 else: currentShape += 1 turtle.onkeypress(changeShape,"c") ###### #changeSize function def enlarge(): global lengthSize global widthSize turtle.resizemode("user") turtle.shapesize(lengthSize+1,widthSize+1) lengthSize += 1 widthSize += 1 turtle.onkeypress(enlarge,"equal") def reduceSize(): global lengthSize global widthSize turtle.resizemode("user") if lengthSize > 1 and widthSize >1:
t.forward(10) # t.fd(10)로 입력해도 됩니다. def turn_up(): # 위로 이동하는 함수 t.setheading(90) t.forward(10) def turn_left(): # 왼쪽으로 이동하는 함수 t.setheading(180) t.forward(10) def turn_down(): # 아래로 이동하는 함수 t.setheading(270) t.forward(10) def blank(): # 화면을 지우는 함수 t.clear() t.shape("turtle") # 거북이 모양을 사용합니다. t.speed(0) # 거북이 속도를 가장 빠르게 지정합니다. t.onkeypress(turn_right, "Right") # [→]를 누르면 turn_right 함수를 실행합니다. t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.onkeypress(blank, "Escape") # [Esc]를 누르면 blank 함수를 실행합니다. t.listen() # 거북이 그래픽 창이 키보드 입력을 받습니다.
# ArrowDraw.py import turtle t = turtle.Pen() t.speed(0) t.turtlesize(2,2,2) def up(): t.forward(50) def left(): t.left(45) def right(): t.right(45) def bigger(): t.width(t.width() + 2) def smaller(): t.width(t.width() - 2) def move(x,y): t.penup() t.setpos(x,y) t.pendown() turtle.onkeypress(up, "Up") turtle.onkeypress(left, "Left") turtle.onkeypress(right, "Right") turtle.onkeypress(bigger, ">") turtle.onkeypress(smaller, "<") turtle.listen() turtle.onscreenclick(move)
def left (): global direction if player.pos()[0] > -280: direction=LEFT else: direction = IDLE move() def right (): global direction if player.pos()[0] < 280: direction=RIGHT else: direction = IDLE move() turtle.onkeypress(left, LEFT_ARROW) turtle.onkeypress(right, RIGHT_ARROW) turtle.listen() def move(): global direction my_pos = player.pos() x_pos = my_pos[0] y_pos = my_pos[1] if direction==RIGHT: player.goto(x_pos + SQUARE_SIZE, y_pos) print ("You moved right!") elif direction==LEFT: player.goto(x_pos - SQUARE_SIZE, y_pos) print("You moved left!")
# ClickArrowDraw.py import turtle t = turtle.Pen() t.speed(0) t.turtlesize(2,2,2) turtle.bgcolor("blue") t.pencolor("green") def up(): t.forward(50) def left(): t.left(45) def right(): t.right(45) def move(x,y): t.penup() t.setpos(x,y) t.pendown() def thicker(): t.width( t.width() + 2 ) def thinner(): t.width( t.width() - 2 ) turtle.onkeypress(up, "Up") turtle.onkeypress(left, "Left") turtle.onkeypress(right, "Right") turtle.onkeypress(thicker, ">") turtle.onkeypress(thinner, "<") turtle.listen() turtle.onscreenclick(move)
####WRITE YOUR CODE HERE!! def down(): snake.direction="Down" #Change direction to up print("You pressed the down key!") def left(): snake.direction="Left" #Change direction to up print("You pressed the left key!") def right(): snake.direction="Right" #Change direction to up print("You pressed the right key!") turtle.onkeypress(up, "Up") # Create listener for up key #3. Do the same for the other arrow keys ####WRITE YOUR CODE HERE!! turtle.onkeypress(down, "Down") turtle.onkeypress(left, "Left") turtle.onkeypress(right, "Right") turtle.listen() turtle.register_shape("ap.gif") #Add trash picture # Make sure you have downloaded this shape # from the Google Drive folder and saved it # in the same folder as this Python script
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 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 on_exit(): t.bye() t.showturtle() # assign functions to keys t.onkeypress(on_forward, 'f') t.onkeypress(on_backward, 'b') t.onkeypress(on_left, 'l') t.onkeypress(on_right, 'r') t.onkeypress(on_exit, 'e') # catch key presses in main window t.listen() # run loop which will execute functions t.mainloop()
te.goto(0, 200) te.shape("turtle") te.color("red") ts = t.Turtle() ts.up() ts.goto(0, -200) ts.shape("circle") ts.color("green") t.up() t.goto(0, 0) t.shape("turtle") t.color("white") t.onkeypress(right, "Right") t.onkeypress(up, "Up") t.onkeypress(left, "Left") t.onkeypress(down, "Down") t.listen() x = True score = 0 while x: # x는 스위치 역할 play() if t.distance(te) <= 10: #print("나와 악당의 거리는? ", t.distance(te)) t.color("red") t.write("GAME OVER", False, "center", ("", 100)) t.color("blue") t.write(score, False, "center", ("", 50))
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 on_exit(): t.bye() t.showturtle() # assign functions to keys t.onkeypress(on_forward, 'f') t.onkeypress(on_backward, 'b') t.onkeypress(on_left, 'l') t.onkeypress(on_right, 'r') t.onkeypress(on_exit, 'e') # catch key presses in main window t.listen() # run loop which will execute functions t.mainloop()