-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek09.py
More file actions
61 lines (47 loc) · 1.97 KB
/
Copy pathweek09.py
File metadata and controls
61 lines (47 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Week 9: Move the Hero (Keyboard Events)
# Goal: Use keyboard events to control a turtle with arrow keys
# This is the foundation for keyboard-controlled games!
import turtle
# Setup screen with specific size
screen = turtle.Screen()
screen.title("Move the Hero")
screen.setup(width=600, height=400)
# Create hero turtle
hero = turtle.Turtle()
hero.shape("turtle") # Built-in shapes: "turtle", "square", "circle", "arrow"
hero.penup() # Don't draw lines when moving
hero.speed(0) # Instant movement (looks smooth)
# CONSTANT: how far to move with each key press
STEP = 20 # Try changing this! Bigger = faster movement
# ===== Movement Functions (Event Handlers) =====
# Each function is called when the corresponding arrow key is pressed
def up():
"""Move hero up by STEP pixels"""
hero.sety(hero.ycor() + STEP) # ycor() gets current Y, add STEP to move up
def down():
"""Move hero down by STEP pixels"""
hero.sety(hero.ycor() - STEP) # Subtract to move down
def left():
"""Move hero left by STEP pixels"""
hero.setx(hero.xcor() - STEP) # xcor() gets current X, subtract to move left
def right():
"""Move hero right by STEP pixels"""
hero.setx(hero.xcor() + STEP) # Add to move right
# ===== Connect Keys to Functions =====
# This is called EVENT BINDING - connect events to handlers
screen.listen() # Tell screen to listen for keyboard events (MUST do this first!)
# onkey(function, key_name) connects key press to function
# Important: Pass function NAME without (), otherwise it runs immediately!
screen.onkey(up, "Up") # Up arrow key → call up()
screen.onkey(down, "Down") # Down arrow key → call down()
screen.onkey(left, "Left") # Left arrow key → call left()
screen.onkey(right, "Right") # Right arrow key → call right()
# ===== Coordinate System Reference =====
# Center of screen is (0, 0)
# +Y (up)
# |
# -X -----+----- +X (right)
# (left) |
# -Y (down)
# Keep window open
screen.mainloop()