Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
pygame_lesson8_diy1
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
f5b09c5c
authored
May 01, 2022
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
6483ae7d
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
29 additions
and
8 deletions
my_game.py
my_game.py
View file @
f5b09c5c
...
...
@@ -3,6 +3,18 @@ from pygame import locals
import
random
pygame
.
init
()
# 初始化
class
Block
(
pygame
.
sprite
.
Sprite
):
# 创建障碍物精灵类,类名为Block首字母大写
# def定义 __init__()函数加上参数,形参123为障碍物123
def
__init__
(
self
,
image1
,
image2
,
image3
):
super
()
.
__init__
()
# 调用super()函数继承父类属性
# 加载障碍物图片
self
.
image
=
random
.
choice
([
image1
,
image2
,
image3
])
# 随机选择一种作为障碍物
# 根据障碍物位图的宽高设置矩形
self
.
rect
=
self
.
image
.
get_rect
()
# 障碍物绘制坐标
self
.
rect
.
x
=
100
self
.
rect
.
y
=
500
-
self
.
rect
.
height
# 创建一个窗口
screen
=
pygame
.
display
.
set_mode
((
1000
,
600
))
FPS
=
pygame
.
time
.
Clock
()
# pygame时钟,控制游戏速度(帧数)
...
...
@@ -24,6 +36,9 @@ jumpState = "runing"
t
=
30
rect_x
=
0
# 设置道路x坐标为0并赋值给变量road_x
bg_x
=
0
# 设置远景坐标为0并赋值给变量bg_x
time
=
0
# 给变量time赋值为0
block_list
=
pygame
.
sprite
.
Group
()
# 创建精灵组
while
True
:
for
event
in
pygame
.
event
.
get
():
...
...
@@ -65,15 +80,20 @@ while True:
road_x
=
0
# 道路x坐标回到0
screen
.
blit
(
road
,
(
road_x
,
500
))
# 道路背景代码中x坐标改为变量road_x
screen
.
blit
(
wukong
,
(
150
,
y
))
# 悟空
if
rect
.
x
<=
0
-
rect
.
width
:
# 障碍物消失
# 创建障碍物对象
obstacle
=
random
.
choice
([
bush
,
stone
,
cacti
])
rect
=
obstacle
.
get_rect
()
rect
.
x
=
1000
rect
.
y
=
500
-
rect
.
height
rect
.
x
-=
8
screen
.
blit
(
obstacle
,
(
rect
.
x
,
rect
.
y
))
time
+=
1
# 将time值+1
if
time
>=
60
:
# if判断time值达到60
r
=
random
.
randint
(
0
,
100
)
# 随机数0,100并赋值给变量r
if
r
>
40
:
# if判断变量r>40
obstacle
=
Blcok
(
bush
,
cacti
,
stone
)
# 创建障碍物精灵
block_list
.
add
(
obstacle
)
# 将精灵添加进精灵组
time
=
0
# 将变量time设为0
for
prop
in
block_list
:
# for循环,遍历、展示障碍物
prop
.
rect
.
x
-=
8
# 将精灵的x坐标-8
# 将程序渲染出来
screen
.
blit
(
prop
.
image
,(
prop
.
rect
.
x
,
prop
.
rect
.
y
))
if
prop
.
rect
.
x
<=
0
-
prop
.
rect
.
width
:
# if判断精灵是否完全消失在窗口左边
prop
.
kill
()
# 使用kill()方法将自己清除
# 刷新画面
pygame
.
display
.
update
()
FPS
.
tick
(
60
)
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment