Commit ff781594 by BellCodeEditor

auto save

parent 16f0d60e
Showing with 75 additions and 6 deletions
import pygame
import random
from pygame import locals
# 初始化pygame,为使用硬件做准备
......@@ -7,26 +8,93 @@ pygame.init()
# 创建一个窗口
screen = pygame.display.set_mode((660, 480))
#pygame时钟,控制游戏速度(帧数)
FPSCLOCK = pygame.time.Clock()
#刷新速度n,默认为1
n=1
#改变速度特征s
s=0
# 背景
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')
snakeHead = right
my_font=pygame.font.Font('neuropol.ttf',18) #创建字体对象
score=0 #分数
x = 240
y = 120
position = [(180,90),(180,120),(210,120),(x,y)]
food_x = 360
food_y = 300
setheading = "right"
while True:
for event in pygame.event.get():
if event.type == locals.QUIT:
# 接收到退出事件后退出程序
exit()
if event.type == locals.KEYDOWN:
if event.key == locals.K_RIGHT and setheading != "left":
setheading = "right"
snakeHead = right
if event.key == locals.K_LEFT and setheading != "right":
setheading = "left"
snakeHead = left
if event.key == locals.K_UP and setheading != "down":
setheading = "up"
snakeHead = up
if event.key == locals.K_DOWN and setheading != "up":
setheading = "down"
snakeHead = down
#实现贪吃蛇移动,新增一个坐标,删除最先的坐标
if setheading=="right":
x=x+30
if setheading == "left":
x= x-30
if setheading == "up":
y=y-30
if setheading == "down":
y = y+30
if (x,y) in position: #如果吃到自己,游戏结束
exit()
position.append((x,y))
if x<0 or x>630 or y<0 or y>450: #如果碰到墙,游戏结束
exit()
if food_x == x and food_y == y:
food_x = random.randint(5,15)*30
food_y = random.randint(5,10)*30
score = score + 10 #分数增加
else:
position.pop(0)
#根据蛇身体长度,改变刷新速度
# if n>4:
# n=4
# else:
# n = len(position)//5+1
# 将背景图画上去
screen.blit(background, (0, 0))
# 将贪吃蛇画上去
screen.blit(right, (240, 120))
# 将贪吃蛇的头画上去
screen.blit(snakeHead, position[-1])
# 将贪吃蛇的身体画上去
screen.blit(body, (210, 120))
screen.blit(body, (180, 120))
screen.blit(body, (180, 90))
for i in range(len(position)-1):
screen.blit(body, position[i])
# 将果实画上去
screen.blit(food, (360, 300))
screen.blit(food, (food_x, food_y))
info='Score: '+str(score) #分数信息
text=my_font.render(info,True,(0,0,0)) #展示分数信息
screen.blit(text,(500,30)) #刷新分数信息
# 刷新画面
pygame.display.update()
FPSCLOCK.tick(n)
\ No newline at end of file
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