from sys import exit
import pygame
from pygame.locals import *
class snake(object):
def __init__(self,x,y):
self.pos=[x/2,y-20]
self.body=[]
self.direct=0
self.len=6
self.alive=True
self.vflag=False
self.hflag=True
self.speedflag=True
self.speed=1
def control1 (self,event):
if event.key == K_LEFT and self.hflag:
self.direct = 270
self.hflag = False
self.vflag = True
if event.key == K_RIGHT and self.hflag:
self.direct = 90
self.hflag = False
self.vflag = True
if event.key == K_UP and self.vflag:
self.direct = 0
self.vflag = False
self.hflag = True
print "a1"
if event.key == K_DOWN and self.vflag:
self.direct = 180
self.vflag = False
self.hflag = True
print "a2"
def control2 (self,event):
if event.key == K_a and self.hflag:
self.direct = 270
self.hflag = False
self.vflag = True
if event.key == K_d and self.hflag:
self.direct = 90
self.hflag = False
self.vflag = True
if event.key == K_w and self.vflag:
self.direct = 0
self.vflag = False
self.hflag = True
if event.key == K_s and self.vflag:
self.direct = 180
self.vflag = False
self.hflag = True
def update(self,size):
self.body.insert(0,list(self.pos))
self.body=self.body[0:self.len]
if self.direct == 0:
self.pos[1]-=10
if self.direct == 180:
self.pos[1]+=10
if self.direct == 90:
self.pos[0] +=10
if self.direct == 270:
self.pos[0] -=10
if self.pos in self.body:
self.alive=False
print "s1"
if self.pos[0] not in range(size[0]):
self.alive=False
print "s2"
if self.pos[1] not in range(size[1]):
self.alive=False
print "s3"
def draw1(self,screen):
for b in self.body :
screen.fill( (255,0,0) , (b[0],b[1],10,10) )
if len(self.body)==self.len:
screen.fill( (0,255,0) , (self.body[-1][0],self.body[-1][1],10,10) )
def draw2(self,screen):
for b in self.body :
screen.fill( (255,255,0) , (b[0],b[1],10,10) )
if len(self.body)==self.len:
screen.fill( (0,255,255) , (self.body[-1][0],self.body[-1][1],10,10) )
def main():
pygame.init()
SCREEN_SIZE = (640,480)
screen =pygame.display.set_mode(SCREEN_SIZE,0,32)
p1=snake( SCREEN_SIZE[0] , SCREEN_SIZE[1] )
p2=snake(0,SCREEN_SIZE[1])
time=0
p1.speed=10
pause=pygame.event.wait()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
return
if event.type == KEYDOWN:
p1.control1(event)
p2.control2(event)
if event.key == K_ESCAPE:
little = pygame.event.wait()
while little.type != KEYDOWN :
little = pygame.event.wait()
if time%p1.speed==0:
p1.update( SCREEN_SIZE )
if time%p2.speed==0:
p2.update( SCREEN_SIZE )
if p1.body[0] == p2.body[-1]:
p2.alive=False
if p2.body[0] == p1.body[-1]:
p1.alive=False
if not p1.alive:
print "p1 died"
p1 = snake( SCREEN_SIZE[0] , SCREEN_SIZE[1] )
if not p2.alive:
print "p2 died"
p2=snake(0,SCREEN_SIZE[1])
screen.fill((255,255,255))#清空页面
p1.draw1( screen )
p2.draw2( screen )
pygame.display.flip()
time += 1
pygame.time.wait(100)
if __name__== "__main__":
main()