在前一篇文章《python小欢喜(六)动画 (1) pygame的安装与初步使用》中介绍了如何安装pygame。接下来咱们用pygame做一些有趣的动画效果
显示笑脸图片
# -*- coding:utf-8 -*-
# showPic.py
# 显示笑脸图处
import
pygame
# 导入pygame模块
pygame
.
init
(
)
screen
=
pygame
.
display
.
set_mode
(
[
800
,
600
]
)
keep_going
=
True
pic
=
pygame
.
image
.
load
(
"CrazySmile.bmp"
)
#加载当前目录下的图片文件 CrazySmile.bmp
while
keep_going
:
# 事件处理循环
for
event
in
pygame
.
event
.
get
(
)
:
if
event
.
type
==
pygame
.
QUIT
:
keep_going
=
False
screen
.
blit
(
pic
,
(
100
,
100
)
)
pygame
.
display
.
update
(
)
pygame
.
quit
(
)
# 退出
从源码可知,该程序要能够正确执行,当前目录下需要有一个图片文件 CrazySmile.bmp
以上只是显示了一副静止的图片,接下要让图片动起来
弹跳的笑脸
python代码如下:
# -*- coding:utf-8 -*-
# 移动的笑脸
import
pygame
# 导入pygame模块
pygame
.
init
(
)
screen
=
pygame
.
display
.
set_mode
(
[
600
,
600
]
)
keep_going
=
True
pic
=
pygame
.
image
.
load
(
"CrazySmile.bmp"
)
#加载当前目录下的图片文件 CrazySmile.bmp
colorkey
=
pic
.
get_at
(
(
0
,
0
)
)
pic
.
set_colorkey
(
colorkey
)
picx
=
0
picy
=
0
BLACK
=
(
0
,
0
,
0
)
timer
=
pygame
.
time
.
Clock
(
)
speed
=
5
while
keep_going
:
# 事件处理循环
for
event
in
pygame
.
event
.
get
(
)
:
if
event
.
type
==
pygame
.
QUIT
:
keep_going
=
False
picx
+=
speed
# 当speed大于0时,增加图片的X坐标值,否则减少
picy
+=
speed
# 当speed大于0时,增加图片的Y坐标值,否则减少
if
picx
<=
0
or
picx
+
pic
.
get_width
(
)
>=
600
:
speed
=
-
speed
#当到达窗口边缘时,速度取反
screen
.
fill
(
BLACK
)
screen
.
blit
(
pic
,
(
picx
,
picy
)
)
pygame
.
display
.
update
(
)
timer
.
tick
(
60
)
pygame
.
quit
(
)
# 退出
带尾巴的移动的笑脸
实现效果如下:
python代码如下:
# -*- coding:utf-8 -*-
# 带尾巴的移动的笑脸
import
pygame
# 导入pygame模块
pygame
.
init
(
)
screen
=
pygame
.
display
.
set_mode
(
[
800
,
600
]
)
keep_going
=
True
pic
=
pygame
.
image
.
load
(
"CrazySmile.bmp"
)
#加载当前目录下的图片文件 CrazySmile.bmp
colorkey
=
pic
.
get_at
(
(
0
,
0
)
)
pic
.
set_colorkey
(
colorkey
)
picx
=
0
picy
=
0
BLACK
=
(
0
,
0
,
0
)
timer
=
pygame
.
time
.
Clock
(
)
speedx
=
5
speedy
=
5
while
keep_going
:
# 事件处理循环
for
event
in
pygame
.
event
.
get
(
)
:
if
event
.
type
==
pygame
.
QUIT
:
keep_going
=
False
picx
+=
speedx
# 当speedx大于0时,增加图片的X坐标值,否则减少
picy
+=
speedy
# 当speedy大于0时,增加图片的Y坐标值,否则减少
if
picx
<=
0
or
picx
+
pic
.
get_width
(
)
>=
800
:
speedx
=
-
speedx
#当到达窗口边缘时,速度取反
if
picy
<=
0
or
picy
+
pic
.
get_height
(
)
>=
600
:
speedy
=
-
speedy
#当到达窗口边缘时,速度取反
#screen.fill(BLACK) # 不做"擦黑板"的操作,达到累加效果,显示出尾巴
screen
.
blit
(
pic
,
(
picx
,
picy
)
)
pygame
.
display
.
update
(
)
timer
.
tick
(
60
)
pygame
.
quit
(
)
# Exit
以上动画效果的实现原理,请查看源码及注释,应该不难理解。