forked from saniyarahmani786/Projects
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pong1.py
77 lines (63 loc) · 1.44 KB
/
pong1.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
from random import choice, random
from turtle import *
from freegames import vector
def value():
"Randomly generate value between (-5, -3) or (3, 5)."
return (3 + random() * 2) * choice([1, -1])
ball = vector(0, 0)
aim = vector(value(), value())
state = {1: 0, 2: 0}
def move(player, change):
"Move player position by change."
state[player] += change
def rectangle(x, y, width, height):
"Draw rectangle at (x, y) with given width and height."
up()
goto(x, y)
down()
begin_fill()
for count in range(2):
forward(width)
left(90)
forward(height)
left(90)
end_fill()
def draw():
"Draw game and move pong ball."
clear()
rectangle(-200, state[1], 10, 50)
rectangle(190, state[2], 10, 50)
ball.move(aim)
x = ball.x
y = ball.y
up()
goto(x, y)
dot(10)
update()
if y < -200 or y > 200:
aim.y = -aim.y
if x < -185:
low = state[1]
high = state[1] + 50
if low <= y <= high:
aim.x = -aim.x
else:
return
if x > 185:
low = state[2]
high = state[2] + 50
if low <= y <= high:
aim.x = -aim.x
else:
return
ontimer(draw, 50)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: move(1, 20), 'w')
onkey(lambda: move(1, -20), 's')
onkey(lambda: move(2, 20), 'i')
onkey(lambda: move(2, -20), 'k')
draw()
done()