@jeffrobot/

CP02_KeyInputs

Python (with Turtle)

No description

fork
loading
main.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import turtle
import time

last_move = 0
move_delay = 0.5

def MoveLeft():
  global last_move
  if(time.time() - last_move >= move_delay):
    last_move = time.time()
    global d_x
    global d_y
    d_x = d_x - bullet_speed
    defender.clear()
    defender.penup()
    defender.setpos(d_x, d_y)
    defender.pendown()
    DrawAvatar()
    print("Move Left")

def MoveRight():
  global last_move
  if(time.time() - last_move >= move_delay):
    last_move = time.time()
    global d_x
    global d_y
    d_x = d_x + bullet_speed
    defender.clear()
    defender.penup()
    defender.setpos(d_x, d_y)
    defender.pendown()
    DrawAvatar()  
    print("Move Right")

def DrawAvatar():
  DrawSquare(defender_size)
  defender.setpos(defender.xcor(), defender.ycor()-defender_size)
  DrawSquare(5)
  defender.setpos(defender.xcor()+defender_size-5, defender.ycor())
  DrawSquare(5)

def DrawSquare(size):
  defender.seth(0)
  for i in range(4):
    defender.forward(size)
    defender.right(90)

def Fire():
  print("Fire")
  global b_x
  global b_y 
  b_x = defender.xcor()
  b_y = -150
  bullet.penup()
  bullet.setpos(b_x, b_y)
  bullet.pendown()
  MoveBullet(bullet)

def MoveBullet(bullet):
  my_b_x = b_x
  global b_y
  for i in range(100):
    b_y = b_y + bullet_speed
    bullet.clear()
    bullet.setpos(b_x, b_y)
    bullet.circle(5)
    if(my_b_x != b_x):
      return
    my_b_x = b_x

window = turtle.Screen()
window.onkey(MoveLeft, "Left")
window.onkey(MoveRight, "Right")
window.onkey(Fire, "Space")
window.listen()

defender = turtle.Turtle()
defender_size = 25
d_x = 0
d_y = -200
defender.speed(0)
defender.penup()
defender.setpos(d_x, d_y)
defender.hideturtle()

bullet = turtle.Turtle()
bullet.hideturtle()
bullet.speed(0)
bullet_speed = 25
b_x = 0
b_y = 0
MoveLeft()

#1. Create a square that moves left and right with keyboard input
result
console