斑斓贪吃蛇"/>
python实现五彩斑斓贪吃蛇
import pygame,sys,randomfrom pygame.locals import*
redColor=pygame.Color(255,0,0)
black=0,0,0
white=255,255,255
screen=pygame.display.set_mode((1000,600))
pygame.display.set_caption("super 贪吃蛇")
def gameover():
pygame.quit()
sys.exit()
def main():
pygame.init()
fpsclock=pygame.time.Clock()
#起始位置
snakeposition=[100,100]
snakebody=[[100,100],[800,100],[60,100]]
targetposition=[300,300]
targetflag=1
direction='right'
changeDirection=direction
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==KEYDOWN:
if event.key==K_RIGHT:
changeDirection="right"
if event.key==K_LEFT:
changeDirection="left"
if event.key==K_UP:
changeDirection="up"
if event.key==K_DOWN:
changeDirection="down"
# if event.key==K_SPACE:
# pygame.event.post(pygame.event.Event(QUIT))
if changeDirection=="left" and not direction=='right':
direction=changeDirection
if changeDirection=="right" and not direction=='left':
direction=changeDirection
if changeDirection == "up" and not direction == 'down':
direction = changeDirection
if changeDirection=="down" and not direction=='up':
direction=changeDirection
if direction == "right":
snakeposition[0]+=20
if direction == "left":
snakeposition[0] -= 20
if direction == "up":
snakeposition[1] -= 20
if direction == "down":
snakeposition[1] += 20
snakebody.insert(0, list(snakeposition))
if snakeposition[0]==targetposition[0] and snakeposition[1]==targetposition[1]:
targetflag=0
snakebody.insert(0, list(snakeposition))
else :
snakebody.pop()
if targetflag==0:
x=random.randrange(1,50)
y=random.randrange(1,30)
targetposition=[int(x*20),int(y*20)]
targetflag=1
screen.fill(black)
snakehead=snakebody[0]
for pos in snakebody[2:]:
if pos==snakehead:
gameover()
for position in snakebody:
x=random.randrange(0,255)
y = random.randrange(0, 255)
z = random.randrange(0, 255)
pygame.draw.rect(screen,(x,y,z),Rect(position[0],position[1],20,20))
pygame.draw.rect(screen,redColor,Rect(targetposition[0],targetposition[1],20,20))
#更新显示到屏幕
pygame.display.flip()
if snakeposition[0]> 980:
snakeposition[0]=0
elif snakeposition[1]>580:
snakeposition[1]=0
elif snakeposition[0]<1:
snakeposition[0]=1000
elif snakeposition[1]<1:
snakeposition[1]=600
fpsclock.tick(10)
main()
更多推荐
python实现五彩斑斓贪吃蛇
发布评论