12-1蓝色天空
代码:
import pygame
import sys
pygame.
init
()
screen
= pygame.display.
set_mode
((
1280
,
720
))
while
True:
for event
in pygame.event.
get
():
if event.type
== pygame.
QUIT:
sys.
exit
()
screen.
fill
((
0
,
0
,
255
))
pygame.display.
flip
()
输出结果:
12-2游戏角色:
代码:
import pygame
import sys
pygame.
init
()
screen
= pygame.display.
set_mode
((
1280
,
720
))
bg_image
= pygame.image.
load
(
"
bg.png
"
)
my_role
= pygame.image.
load
(
"
role.png
"
)
screen_rect
= screen.
get_rect
()
while
True:
for event
in pygame.event.
get
():
if event.type
== pygame.
QUIT:
sys.
exit
()
screen.
blit
(bg_image,screen_rect)
screen.
blit
(my_role, (
int
(screen.
get_width
()
/
2
),
int
(screen.
get_height
()
/
2
)))
pygame.display.
flip
()
输出结果:
12-3火箭:
代码:
import pygame
import sys
pygame.
init
()
screen
= pygame.display.
set_mode
((
1280
,
720
))
bg_color
= (
0,
0,
255)
my_role
= pygame.image.
load
(
"
role.png
"
)
screen_rect
= screen.
get_rect
()
class
Rocket():
"""
创建一个小火箭
"""
def
__init__(
self,
screen):
self.screen
= screen
self.screen_height
= screen.
get_height
()
self.screen_width
= screen.
get_width
()
self.my_role
= pygame.image.
load
(
"
role.png
"
)
self.rect
=
self.my_role.
get_rect
()
self.x
=
float
(
self
.screen_width
/
2
)
self.y
=
float
(
self
.screen_height
/
2
)
self.rect.centerx
=
self.x
self.rect.centery
=
self.y
self.moving_right
=
False
self.moving_left
=
False
self.moving_up
=
False
self.moving_down
=
False
def
update(
self):
if
self.moving_right
and
self.rect.right
<
self.screen_width:
self.x
+=
3
if
self.moving_left
and
self.rect.left
>
0 :
self.x
-=
3
if
self.moving_down
and
self.rect.bottom
<
self.screen_height:
self.y
+=
3
if
self.moving_up
and
self.rect.top
>
0 :
self.y
-=
3
self.rect.centerx
=
self.x
self.rect.centery
=
self.y
def
biltme(
self):
self.screen.
blit
(
self
.my_role,
self
.rect)
def
check_keydown_events(
event,
r):
if event.key
== pygame.
K_RIGHT:
#向右移动飞船
r.moving_right
=
True
elif event.key
== pygame.
K_LEFT:
#向左移动飞船
r.moving_left
=
True
elif event.key
== pygame.
K_UP:
#向上移动飞船
r.moving_up
=
True
elif event.key
== pygame.
K_DOWN:
#向下移动飞船
r.moving_down
=
True
#按下q的时候结束游戏
if event.key
== pygame.K_q:
sys.
exit
()
def
check_keyup_events(
event,
r):
if event.key
== pygame.
K_RIGHT:
r.moving_right
=
False
elif event.key
== pygame.
K_LEFT:
r.moving_left
=
False
elif event.key
== pygame.
K_UP:
r.moving_up
=
False
elif event.key
== pygame.
K_DOWN:
r.moving_down
=
False
def
check_events(
r ):
"""
响应按键和鼠标事件
"""
for event
in pygame.event.
get
():
if event.type
== pygame.
QUIT:
sys.
exit
()
elif event.type
== pygame.
KEYDOWN:
check_keydown_events
(event, r)
elif event.type
== pygame.
KEYUP:
check_keyup_events
(event,r)
#创建小火煎
r
=
Rocket
(screen)
while
True:
check_events
(r)
screen.
fill
(bg_color)
r.
update
()
r.
biltme
()
pygame.display.
flip
()
输出结果:
初始位置:
移动后: