Commit 895f95cd by BellCodeEditor

auto save

parent c6188a1e
Showing with 84 additions and 5 deletions
#学习pygame
#导入游戏窗口
import pygame
pygame.init() #初始化pygame环境
from pygame import locals #从pygame中导入子模块locals
screen = pygame.display.set_mode((660,480)) #创建窗口
# 初始化pygame,为使用pygame做准备
pygame.init()
#创建计时器
FPSClock = pygame.time.Clock()
# 创建一个窗口
??
\ No newline at end of file
#载入图片
background = pygame.image.load('bg.png') #上传背景图片
headright = pygame.image.load('right.png') #上传右蛇头
headup = pygame.image.load('up.png') #上传上蛇头
headleft = pygame.image.load('left.png') #上传左蛇头
headdown = pygame.image.load('down.png') #上传下蛇头
food = pygame.image.load('apple.png') #上传苹果
body = pygame.image.load('body.png')#上传身体
my_font = pygame.font.Font('neuropol.ttf',18) #上传字体对象
head = headright #初始化蛇头朝向
#位置坐标
x = 300 #蛇头初始x坐标
y = 120 #蛇头初始y坐标
position = [(240,90),(240,120),(270,120),(x,y)] #将贪吃蛇的身体每一节的坐标存入列表
setheading = "right" #设置贪吃蛇初始朝向,朝右
#设置苹果坐标
food_x = 360
food_y = 300
#设置分数
score = 0
import random
while True:
for event in pygame.event.get(): #pygame.event.get(),获取pygame中发生的事件
# print(event)
if event.type == locals.QUIT:
#接收到退出事件后即点击窗口关闭,退出程序
exit()
if event.type == locals.KEYDOWN:
if event.key == locals.K_LEFT and setheading != 'right': #设置朝左方向
setheading = 'left'
head = headleft #设置蛇头左方向
if event.key == locals.K_RIGHT and setheading != 'left': #设置朝右方向
setheading = 'right'
head = headright #设置蛇头右方向
if event.key == locals.K_UP and setheading != 'down': #设置朝上方向
setheading = 'up'
head = headup #设置蛇头上方向
if event.key == locals.K_DOWN and setheading != 'up': #设置朝下方向
setheading = 'down'
head = headdown #设置蛇头下方向
#先往前走,再扔掉旧坐标
if setheading == 'left': #按下左键,向左移动
x -= 30
elif setheading == 'right': #按下右键,向右移动
x += 30
elif setheading == 'up': #按下上键,向上移动
y -= 30
else: #按下下键,向下移动
y += 30
position.append((x,y)) #将蛇头的新坐标存入position列表
#贪吃蛇吃到苹果,苹果随机刷新,身体变长
if x == food_x and y == food_y:
num1 = random.randint(1,22) #x轴的格子
num2 = random.randint(1,16) #y轴的格子
food_x = num1*30 - 30 #x坐标
food_y = num2*30 - 30 #y坐标
score += 10
else: #如果没吃到苹果,就将身体最后一节删掉
position.pop(0) #将身体最后一节的旧坐标删掉
if x>630 or x<0 or y<0 or y>450: #检测是否撞墙
exit()
screen.blit(background,(0,0)) #渲染背景。screen为被渲染的对象,blit中,第一个参数为渲染的图片,第二个为坐标
screen.blit(food,(food_x,food_y))#渲染苹果。
#绘制分数
score1 = 'score:'+ str(score) #信息内容
text = my_font.render(score1,True,(0,0,0)) #字体设置
screen.blit(text,(540,10)) #将文本信息渲染到窗口
screen.blit(head,position[-1])#渲染右蛇头。
for i in range(len(position)-1): #使身体遍历position列表的元素
screen.blit(body,position[i]) #让身体一次渲染列表中的坐标
pygame.display.update() #刷新渲染效果,进行展示
FPSClock.tick(3) #限制帧数每秒不超过3
\ 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