import sys
import pygame
import random
pygame.init()
size=width,height=800,600
screen=pygame.display.set_mode(size)
pygame.display.set_caption("贪吃蛇")
logo=pygame.image.load("gem5.png")
pygame.display.set_icon(logo)
white=(255,255,255)
black=(0,0,0)
red=(255,0,0)
blue=(0,0,255)
unit=50
fps=5
clock=pygame.time.Clock()
font=pygame.font.SysFont(None,25)
sound_Back=pygame.mixer.Sound("eat.wav")
sound_Over=pygame.mixer.Sound("gameover.wav")
def snake(body,unit):
for seat in body:
pygame.draw.rect(screen,red,[seat[0],seat[1],unit,unit])
def end():
pygame.quit()
sys.exit()
def message(msg,color):
text=font.render(msg,True,color)
screen.blit(text,[width/2,height/2])
def loop():
pygame.mixer.Sound.play(sound_Back,loops=-1)
Over=False
lead_x=width/2
lead_y=height/2
lead_x_change=0
lead_y_change=0
food_x=round((random.randrange(unit,width-unit))/unit)*unit
food_y=round((random.randrange(unit,height-unit))/unit)*unit
body=[]
length=1
while Over==False:
for event in pygame.event.get():
if event.type==pygame.QUIT:
end()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
lead_x_change=-unit
lead_y_change=0
elif event.key==pygame.K_RIGHT:
lead_x_change=unit
lead_y_change=0
elif event.key==pygame.K_UP:
lead_y_change=-unit
lead_x_change=0
elif event.key==pygame.K_DOWN:
lead_y_change=unit
lead_x_change=0
lead_x+=lead_x_change
lead_y+=lead_y_change
screen.fill(white)
pygame.draw.rect(screen,blue,[food_x,food_y,unit,unit])
head=[]
head.append(lead_x)
head.append(lead_y)
body.append(head)
if len(body)>length:
del body[0]
snake(body,unit)
pygame.display.update()
if lead_x==food_x and lead_y==food_y:
food_x=round((random.randrange(unit,width-unit))/unit)*unit
food_y=round((random.randrange(unit,height-unit))/unit)*unit
length+=1
clock.tick(fps)
if lead_x>=width or lead_x<=0 or lead_y>=height or lead_y<=0:
Over=True
while Over==True:
pygame.mixer.Sound.stop(sound_Back)
pygame.mixer.Sound.play(sound_Over,loops=0)
screen.fill(white)
message("game over,press C to continue or Q to quit",red)
pygame.display.update()
for event in pygame.event.get():
if event.type==pygame.QUIT:
end()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_q:
end()
if event.key==pygame.K_c:
loop()
loop()
这段代码不是完美的贪吃蛇。这个蛇可以往回走,并且碰到自己身体不会死亡,并且开局只有一格身体。(不过碰墙会死亡,而且这段代码有背景音乐、结束音乐、独立图标。但在不同电脑使用时需要先下载三组双引号中的文件,那是一个图标和两个音乐)
我再想想怎么让这个蛇不能往回走……