Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
pygame_lesson1_3
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
3937fc10
authored
Nov 09, 2024
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
save project
parent
d363cf32
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
45 additions
and
7 deletions
snake.py
snake.py
View file @
3937fc10
import
pygame
import
pygame
import
random
WINDOW_WIDTH
=
800
WINDOW_HEIGHT
=
600
SNAKE_SIZE
=
20
pygame
.
init
()
screen
=
pygane
.
display
.
set_mode
((
660
,
480
))
while
True
:
for
phgane
.
event
.
egt
()
locals
(
event
.
type
)
\ No newline at end of file
window
=
pygame
.
display
.
set_mode
((
WINDOW_WIDTH
,
WINDOW_HEIGHT
))
pygame
.
display
.
set_caption
(
"贪吃蛇游戏"
)
snake_x
=
WINDOW_WIDTH
//
2
snake_y
=
WINDOW_HEIGHT
//
2
snake_length
=
1
snake_body
=
[[
snake_x
,
snake_y
]]
food_x
=
random
.
randint
(
0
,
(
WINDOW_WIDTH
-
SNAKE_SIZE
)
//
SNAKE_SIZE
)
*
SNAKE_SIZE
food_y
=
random
.
randint
(
0
,
(
WINDOW_HEIGHT
-
SNAKE_SIZE
)
//
SNAKE_SIZE
)
*
SNAKE_SIZE
clock
=
pygame
.
time
.
Clock
()
game_over
=
False
while
not
game_over
:
for
event
in
pygame
.
event
.
get
():
if
event
.
type
==
pygame
.
QUIT
:
game_over
=
True
keys
=
pygame
.
key
.
get_pressed
()
if
keys
[
pygame
.
K_UP
]:
snake_y
-=
SNAKE_SIZE
elif
keys
[
pygame
.
K_DOWN
]:
snake_y
+=
SNAKE_SIZE
elif
keys
[
pygame
.
K_LEFT
]:
snake_x
-=
SNAKE_SIZE
elif
keys
[
pygame
.
K_RIGHT
]:
snake_x
+=
SNAKE_SIZE
if
snake_x
==
food_x
and
snake_y
==
food_y
:
snake_length
+=
1
food_x
=
random
.
randint
(
0
,
(
WINDOW_WIDTH
-
SNAKE_SIZE
)
//
SNAKE_SIZE
)
*
SNAKE_SIZE
food_y
=
random
.
randint
(
0
,
(
WINDOW_HEIGHT
-
SNAKE_SIZE
)
//
SNAKE_SIZE
)
*
SNAKE_SIZE
snake_body
.
append
([
snake_x
,
snake_y
])
if
len
(
snake_body
)
>
snake_length
:
del
snake_body
[
0
]
if
snake_x
<
0
or
snake_x
>=
WINDOW_WIDTH
or
snake_y
<
0
or
snake_y
>=
WINDOW_HEIGHT
or
[
snake_x
,
snake_y
]
in
snake_body
[:
-
1
]:
game_over
=
True
window
.
fill
((
0
,
0
,
0
))
for
body_part
in
snake_body
:
pygame
.
draw
.
rect
(
window
,
(
0
,
255
,
0
),
(
body_part
[
0
],
body_part
[
1
],
SNAKE_SIZE
,
SNAKE_SIZE
))
pygame
.
draw
.
rect
(
window
,
(
255
,
0
,
0
),
(
food_x
,
food_y
,
SNAKE_SIZE
,
SNAKE_SIZE
))
pygame
.
display
.
update
()
clock
.
tick
(
10
)
pygame
.
quit
()
\ 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