1.
import pygame,sys,random
from pygame.locals import *
2.
print("控制你的蛇,按↑↓←→控制")
print("左右边 如撞上去,将退出")
print("上下边 如撞上去,将无影无踪")
DISPLAY=pygame.display.set_mode((1080,650))
pygame.display.set_caption('贪吃蛇3.0')
icon = pygame.image.load("E:无标题.png")
pygame.display.set_icon(icon)
FPSCLOCK=pygame.time.Clock()
BLACK=pygame.Color(0,0,0)
WHITE=pygame.Color(255,255,255)
RED=pygame.Color(255,0,0)
green=pygame.Color(0,128,0)
blue = 0, 0, 225
snake_Head=[100,100]
snake_Body=[[80,100], [60,100],[40,100]]
direction="right"
changeDirection = direction
food_Postion = [300,300]
food_Total = 1
def drawSnake(snake_Body):
for i in snake_Body:
pygame.draw.rect(DISPLAY,WHITE,Rect(i[0],i[1],20,20))
def drawFood(food_Postion):
pygame.draw.rect(DISPLAY,RED,Rect(food_Postion[0],food_Postion[1],20,20))
def gameover():
pygame.quit()
sys.exit()
game_flag=True
while game_flag:
DISPLAY.fill(blue)
drawSnake(snake_Body)
drawFood(food_Postion)
game_speed=1+len(snake_Body)//3
pygame.display.flip()
FPSCLOCK.tick(game_speed)
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == K_d:
changeDirection = 'right'
if event.key == K_LEFT or event.key == K_a:
changeDirection = 'left'
if event.key == K_UP or event.key == K_w:
changeDirection = 'up'
if event.key == K_DOWN or event.key == K_s:
changeDirection = 'down'
if event.key == KSCAN_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction=='right':
snake_Head[0]+=20
if direction=='left':
snake_Head[0]-=20
if direction=='up':
snake_Head[1]-=20
if direction=='down':
snake_Head[1]+=20
snake_Body.insert(0,list(snake_Head))
if snake_Head[0] == food_Postion[0] and snake_Head[1] == food_Postion[1]:
food_Total = 0
else:
snake_Body.pop()
if food_Total == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
food_Postion = [int(x * 20), int(y * 20)]
food_Total = 1
if snake_Head[0] > 800 or snake_Head[0] < 0:
gameover()
elif snake_Head[0] > 800 or snake_Head[0] < 0:
gameover()
for body in snake_Body[1:]:
if snake_Head[0] == body[0] and snake_Head[1] == body[1]:
gameover()
运行: 注意 需要画图
放E盘 (下载上图)保存为 无题标 (格式为:.png)