简单的用python写的贪吃蛇
(我是菜鸟)学python的我学了下pygame,试着写了写贪吃蛇,下面是代码,有问题也可以问我
QQ2036693779,废话不多说上代码
#贪吃蛇简单版
import pygame,sys,time,random
from pygame.locals import *
from PIL import Image
class Snake():
def __init__(self,x,y):
self.x=x
self.y=y
def drawpic(screen,self):
pic=pygame.image.load('snake.png')
screen.blit(pic,(self.x,self.y))
def drawmap(screen):
for i in range(25):
pygame.draw.line(screen,(0,0,0),(0,i*20),(500,i*20))
for j in range(25):
pygame.draw.line(screen,(0,0,0),(j*20,0),(j*20,500))
def drawfood(screen):
x=random.randint(0,25)*20
y=random.randint(0,25)*20
pygame.draw.rect(screen,(255,0,0),(x,y,20,20))
return (x+10,y+10)
def drawfood_1(screen,x,y):
pygame.draw.rect(screen,(255,0,0),(x,y,20,20))
def move(screen,manyske):#蛇头前进方向
direction='right'
head=manyske[0]
newx=head.x
newy=head.y
screen.fill((255,255,255))
fx,fy=drawfood(screen)
while True:
if direction=='left':
newx=head.x-20
elif direction=='right':
newx=head.x+20
elif direction=='up':
newy=head.y-20
elif direction=='down':
newy=head.y+20
screen.fill((255,255,255))
drawmap(screen)
if (fx,fy)==(newx+10,newy+10):
fx,fy=drawfood(screen)
snake=Snake(manyske[-1].x,manyske[-1].y)
manyske.append(snake)
else:
pygame.draw.rect(screen,(255,0,0),(fx-10,fy-10,20,20))
j=len(manyske)-1
for i in range(len(manyske)):
manyske[j].x=manyske[j-1].x
manyske[j].y=manyske[j-1].y
j-=1;
head.x=newx
head.y=newy
for i in range(len(manyske)):
drawpic(screen,manyske[i])
event=pygame.event.poll()
if event.type==KEYDOWN:
if event.key==pygame.K_LEFT and direction!='right':
direction='left'
elif event.key==pygame.K_RIGHT and direction!='left':
direction='right'
elif event.key==pygame.K_DOWN and direction!='up':
direction='down'
elif event.key==pygame.K_UP and direction!='down':
direction='up'
elif event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
time.sleep(0.25)
#全局变量
pygame.init()
screen=pygame.display.set_mode((500,500))
pygame.display.set_caption('贪吃蛇')
screen.fill((255,255,255))
drawmap(screen)
#食物
manyske=[]
head=Snake(0,0)
manyske.append(head)
move(screen,manyske)