Python交互小游戏(三):Pong——Lists,keyboard input,the basics of modeling motion

1 Keyboard Input(键盘输入)

例 1:

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
# Keyboard echo

import simplegui

# initialize state
current_key = ' '

# event handlers
def keydown(key):
global current_key
current_key = chr(key) # 返回整数i对应的ASCII字符。与ord()作用相反

def keyup(key):
global current_key
current_key = ' '

def draw(c):
# NOTE draw_text now throws an error on some non-printable characters
# Since keydown event key codes do not all map directly to
# the printable character via ord(), this example now restricts
# keys to alphanumerics

if current_key in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":
c.draw_text(current_key, [10, 25], 20, "Red")

# create frame
f = simplegui.create_frame("Echo", 35, 35)

# register event handlers
f.set_keydown_handler(keydown)
f.set_keyup_handler(keyup)
f.set_draw_handler(draw)

# start frame
f.start()


函数:chr(i)
中文说明:

返回整数i对应的ASCII字符。与ord()作用相反。
参数x:取值范围[0, 255]之间的正数。
版本:该函数在python2和python3各个版本中都可用。不存在兼容性问题。

英文说明:

Return a string of one character whose ASCII code is the integer i. For example, chr(97) returns the string ‘a’. This is the inverse of ord(). The argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that range. See also unichr().

例 2:

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
# control the position of a ball using the arrow keys

import simplegui

# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20

ball_pos = [WIDTH / 2, HEIGHT / 2]

# define event handlers
def draw(canvas):
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")

def keydown(key):
vel = 4
if key == simplegui.KEY_MAP["left"]:
ball_pos[0] -= vel
elif key == simplegui.KEY_MAP["right"]:
ball_pos[0] += vel
elif key == simplegui.KEY_MAP["down"]:
ball_pos[1] += vel
elif key == simplegui.KEY_MAP["up"]:
ball_pos[1] -= vel

# create frame
frame = simplegui.create_frame("Positional ball control", WIDTH, HEIGHT)

# register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)

# start frame
frame.start()

2 Motion(运动)

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
# Ball motion with an implicit timer

import simplegui

# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20

ball_pos = [WIDTH / 2, HEIGHT / 2]
vel = [0, 1] # pixels per update (1/60 seconds)

# define event handlers
def draw(canvas):
# Update ball position
ball_pos[0] += vel[0]
ball_pos[1] += vel[1]

# Draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")

# create frame
frame = simplegui.create_frame("Motion", WIDTH, HEIGHT)

# register event handlers
frame.set_draw_handler(draw)

# start frame
frame.start()

3 Collisions(碰撞)

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
import simplegui

# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20

ball_pos = [WIDTH / 2, HEIGHT / 2]
vel = [-40.0 / 60.0, 5.0 / 60.0]

# define event handlers
def draw(canvas):
# Update ball position
ball_pos[0] += vel[0]
ball_pos[1] += vel[1]

# collide and reflect off of left hand side of canvas
if ball_pos[0] <= BALL_RADIUS:
vel[0] = - vel[0]


# Draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")

# create frame
frame = simplegui.create_frame("Ball physics", WIDTH, HEIGHT)

# register event handlers
frame.set_draw_handler(draw)

# start frame
frame.start()

4 Velocity Control(控制速度)

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
# control the velocity of a ball using the arrow keys

import simplegui

# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20

ball_pos = [WIDTH / 2, HEIGHT / 2]
vel = [0, 0]

# define event handlers
def draw(canvas):
# Update ball position
ball_pos[0] += vel[0]
ball_pos[1] += vel[1]

# Draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")

def keydown(key):
acc = 1
if key==simplegui.KEY_MAP["left"]:
vel[0] -= acc
elif key==simplegui.KEY_MAP["right"]:
vel[0] += acc
elif key==simplegui.KEY_MAP["down"]:
vel[1] += acc
elif key==simplegui.KEY_MAP["up"]:
vel[1] -= acc

print ball_pos

# create frame
frame = simplegui.create_frame("Velocity ball control", WIDTH, HEIGHT)

# register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)

# start frame
frame.start()

本例与本文第 1 小节的例 2 的区别是,当按下按键后,并不是直接改变小球的位置,而是改变小球的速度向量,实现连续运动

5 Pong

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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# from __future__ import division
try:
import simplegui
except ImportError:
import simpleguics2pygame as simplegui


# ================================ my code ================================

# Implementation of classic arcade game Pong

#import simplegui
import random

# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True

ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [0.0, 0.0]
score1 = 0
score2 = 0
paddle1_pos = HEIGHT / 2
paddle2_pos = HEIGHT / 2
paddle1_vel = 0
paddle2_vel = 0

# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH / 2, HEIGHT / 2]
if(direction == LEFT): ball_vel[0] = -random.randrange(120, 240) / 60.0
elif(direction == RIGHT): ball_vel[0] = random.randrange(120, 240) / 60.0
ball_vel[1] = -random.randrange(60, 180) / 60.0

# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
score1 = 0
score2 = 0
paddle1_pos = HEIGHT / 2
paddle2_pos = HEIGHT / 2
paddle1_vel = 0
paddle2_vel = 0
spawn_ball(LEFT)

def draw(canvas):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel

# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")

# update ball
ball_pos[0] = ball_pos[0] + ball_vel[0]
ball_pos[1] = ball_pos[1] + ball_vel[1]
if(ball_pos[1] <= BALL_RADIUS or ball_pos[1] >= HEIGHT - BALL_RADIUS):
ball_vel[1] = -ball_vel[1]

# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "White", "White")

# update paddle's vertical position, keep paddle on the screen
paddle1_pos = paddle1_pos + paddle1_vel
paddle2_pos = paddle2_pos + paddle2_vel
if(paddle1_pos < HALF_PAD_HEIGHT): paddle1_pos = HALF_PAD_HEIGHT
elif(paddle1_pos > HEIGHT - HALF_PAD_HEIGHT): paddle1_pos = HEIGHT - HALF_PAD_HEIGHT
if(paddle2_pos < HALF_PAD_HEIGHT): paddle2_pos = HALF_PAD_HEIGHT
elif(paddle2_pos > HEIGHT - HALF_PAD_HEIGHT): paddle2_pos = HEIGHT - HALF_PAD_HEIGHT

# draw paddles
canvas.draw_line([HALF_PAD_WIDTH, paddle1_pos - HALF_PAD_HEIGHT],[HALF_PAD_WIDTH, paddle1_pos + HALF_PAD_HEIGHT], PAD_WIDTH, "White")
canvas.draw_line([WIDTH - HALF_PAD_WIDTH, paddle2_pos - HALF_PAD_HEIGHT],[WIDTH - HALF_PAD_WIDTH, paddle2_pos + HALF_PAD_HEIGHT], PAD_WIDTH, "White")

# determine whether paddle and ball collide
if(ball_pos[0] <= PAD_WIDTH + BALL_RADIUS):
if(ball_pos[1] >= paddle1_pos - HALF_PAD_HEIGHT and ball_pos[1] <= paddle1_pos + HALF_PAD_HEIGHT):
ball_vel[0] = -ball_vel[0]
ball_vel[0] = 1.1 * ball_vel[0]
ball_vel[1] = 1.1 * ball_vel[1]
else:
score2 = score2 + 1
spawn_ball(RIGHT)

elif(ball_pos[0] >= WIDTH - PAD_WIDTH - BALL_RADIUS):
if(ball_pos[1] >= paddle2_pos - HALF_PAD_HEIGHT and ball_pos[1] <= paddle2_pos + HALF_PAD_HEIGHT):
ball_vel[0] = -ball_vel[0]
ball_vel[0] = 1.1 * ball_vel[0]
ball_vel[1] = 1.1 * ball_vel[1]
else:
score1 = score1 + 1
spawn_ball(LEFT)

# draw scores
canvas.draw_text(str(score1), ((PAD_WIDTH + WIDTH / 2) / 2, 40), 30, 'White')
canvas.draw_text(str(score2), ((WIDTH / 2 + WIDTH - PAD_WIDTH) / 2, 40), 30, 'White')

def keydown(key):
global paddle1_vel, paddle2_vel
if(key == simplegui.KEY_MAP['w']): paddle1_vel = -10
elif(key == simplegui.KEY_MAP['s']): paddle1_vel = 10
elif(key == simplegui.KEY_MAP['up']): paddle2_vel = -10
elif(key == simplegui.KEY_MAP['down']): paddle2_vel = 10

def keyup(key):
global paddle1_vel, paddle2_vel
paddle1_vel = 0
paddle2_vel = 0

def restart_btn_hanler():
new_game()


# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button('Restart', restart_btn_hanler, 100)


# start frame
new_game()
frame.start()