Commit 6580073d by BellCodeEditor

auto save

parent 7236d2d5
apple.png

2.05 KB

bg.png

22.5 KB

body.png

1.4 KB

down.png

2.01 KB

left.png

2.07 KB

File added
right.png

2.05 KB

import pygame
import random
from pygame import locals
# 初始化pygame,为使用硬件做准备
pygame.init()
# 创建一个窗口
screen = pygame.display.set_mode((660, 480))
pygame.display.set_caption('贪吃蛇')
FPSCLOCK=pygame.time.Clock()
# 背景
background = pygame.image.load('bg.png')
#导入图片
right = pygame.image.load('right.png')
left=pygame.image.load('left.png')
up=pygame.image.load('up.png')
down=pygame.image.load('down.png')
food = pygame.image.load('apple.png')
body = pygame.image.load('body.png')
#导入字体
my_font=pygame.font.Font('neuropol.ttf',25)
x,y=240,120
position=[(180,90),(180,120),(210,120),(x,y)]
direction='right'
snake_head=right
food_x=0
food_y=0
food_x=random.randint(2,21)*30
food_y=random.randint(2,15)*30
score=0
while True:
if x>630 or x<0 or y<0 or y>450:
exit()
elif (x,y) in position[0:-1]:
exit()
for event in pygame.event.get():
if event.type == locals.QUIT:
# 接收到退出事件后退出程序
exit()
if event.type==pygame.KEYDOWN:
if event.key==locals.K_UP and direction != 'down':
direction='up'
snake_head=up
if event.key==locals.K_DOWN and direction != 'up':
direction='down'
snake_head=down
if event.key==locals.K_LEFT and direction != 'right':
direction='left'
snake_head=left
if event.key==locals.K_RIGHT and direction != 'left':
direction='right'
snake_head=right
info='score:'+str(score)
text=my_font.render(info,True,(0,0,0))
if direction=='left':
x-=30
elif direction=='right':
x+=30
elif direction=='up':
y-=30
else:
y+=30
# 将背景图画上去
screen.blit(background, (0, 0))
# 将贪吃蛇画上去
screen.blit(snake_head,position[-1])
# 将贪吃蛇的身体画上去
for i in range(len(position)-1):
screen.blit(body,position[i])
# 将果实画上去
screen.blit(food, (food_x, food_y))
screen.blit(text,(530,10))
if (x,y) == (food_x,food_y):
food_x=random.randint(2,21)*30
food_y=random.randint(2,15)*30
position.append((x,y))
score+=1
else:
position.append((x,y))
position.pop(0)
#检测是否碰到边界
# 刷新画面
pygame.display.update()
FPSCLOCK.tick(5)
up.png

2.05 KB

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment