python 贪吃蛇--懒人舒适版

不会死亡,碰壁自动转弯,可随意转向

# -*- coding: UTF-8 -*-
# animation.py
 
# 导入需要的模块
import pygame, sys
import random
import time
from pygame.locals import *
 
# 初始化pygame
pygame.init()
 
# 设置帧率(屏幕每秒刷新的次数)
FPS = 10

# 获得pygame的时钟
fpsClock = pygame.time.Clock()

# 设置窗口大小
screen = pygame.display.set_mode((500, 400), 0, 32)
 
# 设置标题
pygame.display.set_caption('贪吃蛇')
 
# 定义颜色
black=(0,0,0)
black=(0,0,0)
color0=(200,200,0)
color1=(0,250,255)
color2=(250,100,100)
 
# 初始化移动方向
direction = '0'
 
def randFoodPos():
    return [random.randint(0,49),random.randint(0,39)]
rf=[10,10]
x=0;y=0
snake=[[100,100,10,10],[90,100,10,10],[80,100,10,10]]   #初始化蛇身
head=[100,100,10,10]
# 程序主循环
ate=0
while True:
  # 每次都要重新绘制背景
  screen.fill(black)
  # 判断移动的方向,并对相应的坐标做加减
  if direction == 'right' and head[0]<490:
    head[0] += 10
    if head[0] == 490:
      direction = 'down'
  elif direction == 'down' and head[1]<390:
    head[1] += 10
    if head[1] == 390:
      direction = 'left'
  elif direction == 'left' and head[0]>0:
    head[0] -= 10
    if head[0] == 0:
      direction = 'up'
  elif direction == 'up' and head[1]>0:
    head[1]-= 10
    if head[1] == 0:
      direction = 'right'
  h=list(head)  #不解此处为何必须用list  ???????????????????
  snake.insert(0,h)
  if head[0]==rf[0]*10 and head[1]==rf[1]*10:
      ate=1
  else:
      snake.pop()
  
  if ate==1:
      rf=randFoodPos()
      ate=0
  for k in snake:
      if k==head:
          pygame.draw.rect(screen,color0,k)
          pygame.draw.line(screen,black,[k[0],k[1]],[k[0],k[1]+10],1)
          pygame.draw.line(screen,black,[k[0],k[1]],[k[0]+10,k[1]],1)
          pygame.draw.line(screen,black,[k[0]+10,k[1]],[k[0]+10,k[1]+10],1)
          pygame.draw.line(screen,black,[k[0],k[1]+10],[k[0]+10,k[1]+10],1)
      else:
          pygame.draw.rect(screen,color1,k)
          pygame.draw.line(screen,black,[k[0],k[1]],[k[0],k[1]+10],1)
          pygame.draw.line(screen,black,[k[0],k[1]],[k[0]+10,k[1]],1)
          pygame.draw.line(screen,black,[k[0]+10,k[1]],[k[0]+10,k[1]+10],1)
          pygame.draw.line(screen,black,[k[0],k[1]+10],[k[0]+10,k[1]+10],1)
      pygame.draw.rect(screen,color2,[rf[0]*10,rf[1]*10,10,10])
 
  for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    elif event.type==KEYDOWN:
        if event.key==K_a:
            direction='left'
        elif event.key==K_s:
            direction='down'
        elif event.key==K_w:
            direction='up'
        elif event.key==K_d:
            direction='right'
        elif event.key==K_SPACE:
            time.sleep(8)

  # 刷新屏幕
  pygame.display.update()
 
  # 设置pygame时钟的间隔时间
  fpsClock.tick(FPS)

在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值