一.写程序
# -*- coding:utf-8 -*-
import random
import pygame
import sys
from pygame.locals import *
pygame.init()
pygame.mixer.init()
#创建窗口
ScreenX = 800
ScreenY = 800
ScreenSize = (ScreenX, ScreenY)
Screen = pygame.display.set_mode(ScreenSize, 0, 32)
pygame.display.set_caption("楚楚的 small snake")
Difficulty = 11
#背景音乐
pygame.time.delay(100)#等待1秒让mixer完成初始化
pygame.mixer.music.load('D://game//a.mp3')
pygame.mixer.music.play(-1, 0.0) #第一个参数为播放次数,如果是-1表示循环播放,省略表示只播放1次。第二个参数和第三个参数分别表示播放的起始和结束位置。
# 蛇
class snake():
def __init__(self):
self.Direction = K_RIGHT
self.Body = []
self.AddBody()
self.AddBody()
def AddBody(self):
NewAddLeft, NewAddTop = (0, 0)
if self.Body:
NewAddLeft, NewAddTop = (self.Body[0].left, self.Body[0].top)
NewAddBody = pygame.Rect(NewAddLeft, NewAddTop, 20, 20)
if self.Direction == K_LEFT:
if NewAddBody.left == 0:
NewAddBody.left = 780
else:
NewAddBody.left -= 20
elif self.Direction == K_RIGHT:
if NewAddBody.left == 780:
NewAddBody.left = 0
else:
NewAddBody.left += 20
elif self.Direction == K_UP:
if NewAddBody.top == 0:
NewAddBody.top = 780
else:
NewAddBody.top -= 20
elif self.Direction == K_DOWN:
if NewAddBody.top == 780:
NewAddBody.top = 0
else:
NewAddBody.top += 20
self.Body.insert(0, NewAddBody)
def DelBody(self):
self.Body.pop()
def IsDie(self):
if self.Body[0] in self.Body[1:]:
return True
return False
def Move(self):
self.AddBody()
self.DelBody()
def ChangeDirection(self, Curkey):
LR = [pygame.K_LEFT, pygame.K_RIGHT]
UD = [pygame.K_UP, pygame.K_DOWN]
if Curkey in LR + UD:
if (Curkey in LR) and (self.Direction in LR):
return
if (Curkey in UD) and (self.Direction in UD):
return
self.Direction = Curkey
# 食物
class food():
def __init__(self):
self.Obj = pygame.Rect(-20, 0, 20, 20)
def Remove(self):
self.Obj.x = -20
def SendFood(self