Commit 5bad56c2 by BellCodeEditor

save project

parent 52f26819
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
from pygame import locals
import random
# 初始化pygame,为使用硬件做准备
pygame.init()
# 创建一个窗口
screen = pygame.display.set_mode((660, 480))
FPSCLOCK=pygame.time.Clock()
# 背景
background = pygame.image.load('bg.png')
right = pygame.image.load('right.png')
food = pygame.image.load('apple.png')
body = pygame.image.load('body.png')
left = pygame.image.load('left.png')
up = pygame.image.load('up.png')
down = pygame.image.load('down.png')
my_font = pygame.font.Font("neuropol.ttf",18)
x = 240
y = 120
apple_x = 360
apple_y = 300
list = [(180,90),(180,120),(210,120),(x,y)]
heading = 'right'
score = 0
while True:
for event in pygame.event.get():
if event.type == locals.KEYDOWN:
if event.key==locals.K_UP and heading != 'down': #向上
heading='up'
if event.key==locals.K_LEFT and heading != 'right': #向左
heading='left'
if event.key==locals.K_RIGHT and heading != 'left': #向右
heading='right'
if event.key==locals.K_DOWN and heading != 'up': #向下
heading='down'
if event.type == locals.QUIT:
# 接收到退出事件后退出程序
exit()
# 将背景图画上去
screen.blit(background, (0, 0))
# 将贪吃蛇画上去
if heading=='up':
y-=30
if y<0:
y=480
if y>480:
y=0
if x>660:
x=0
if x<0:
x=660
if heading=='down':
y+=30
if y<0:
y=480
if y>480:
y=0
if x>660:
x=0
if x<0:
x=660
if heading=='right':
x+=30
if y<0:
y=480
if y>480:
y=0
if x>660:
x=0
if x<0:
x=660
if heading=='left':
x-=30
if y<0:
y=480
if y>480:
y=0
if x>660:
x=0
if x<0:
x=660
#增加坐标
if apple_x==x and apple_y==y:
list.append((x,y))
list2=list
else:
list.append((x,y))
list2=list
list.pop(0)
#判断头是否碰到身体
for i in range(len(list)-1):
if list[i]==(x,y):
exit()
#判断方向
if heading=='up':
screen.blit(up, (x, y))
if heading=='down':
screen.blit(down, (x, y))
if heading=='right':
screen.blit(right, (x, y))
if heading=='left':
screen.blit(left, (x, y))
# 将贪吃蛇的身体画上去
for cs in range(len(list)-1):
screen.blit(body, list[cs])
#贪吃蛇的头碰到苹果
if apple_x==x and apple_y==y:
apple_x=random.randint(0,21)*30
apple_y=random.randint(0,15)*30
score+=5
if (apple_x,apple_y) in list:
apple_x=random.randint(0,21)*30
apple_y=random.randint(0,15)*30
# print(list) 用于检测错误
# 将果实画上去
screen.blit(food, (apple_x, apple_y))
# 分数
info="score:" + str(score)
font=my_font.render(info,True,(0,0,0))
screen.blit(font,(540,10))
# 刷新画面
pygame.display.update()
zhenlv=len(list)/4
FPSCLOCK.tick(zhenlv+1)
\ No newline at end of file
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