python贪吃蛇源代码
短信预约 -IT技能 免费直播动态提醒
import pygame, sys, random
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
rectLength = 18
windowSurface = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),0,32)
pygame.display.set_caption('Snake')
BLACK = (0,0,0)
GREEN = (0,255,0)
snakeRect = []
for i in range(7,10):
snakeRect.append(pygame.Rect(i*(rectLength+2)+1,0+1,rectLength,rectLength))
food = pygame.Rect(5*(rectLength+2),5*(rectLength+2),rectLength+2,rectLength+2)
moveLeft = True
moveRight = False
moveUp = False
moveDown = False
direction = 1
foodImage = pygame.image.load('cherry.png')
pygame.mixer.music.load('background.mid')
pygame.mixer.music.play(-1,0.0)
pickUpSound = pygame.mixer.Sound('pickup.wav')
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT and moveRight==False:
moveLeft = True
moveRight = False
moveUp = False
moveDown = False
if event.key == K_RIGHT and moveLeft==False:
moveLeft = False
moveRight = True
moveUp = False
moveDown = False
if event.key == K_UP and moveDown==False:
moveLeft = False
moveRight = False
moveUp = True
moveDown = False
if event.key == K_DOWN and moveUp==False:
moveLeft = False
moveRight = False
moveUp = False
moveDown = True
head = pygame.Rect(snakeRect[0].left,snakeRect[0].top,snakeRect[0].width,snakeRect[0].height)
if moveLeft == True:
head.right = head.left-2
if moveRight == True:
head.left = head.right+2
if moveUp == True:
head.bottom = head.top-2
if moveDown == True:
head.top = head.bottom+2
snakeRect.insert(0,head);
if head.right<0 or head.left>WINDOWWIDTH or head.bottom<0 or head.top>WINDOWHEIGHT:
break
if food.left == snakeRect[0].left-1 and food.top == snakeRect[0].top-1:
food.left = random.randint(0,WINDOWWIDTH/20-1)*(rectLength+2)
food.top = random.randint(0,WINDOWHEIGHT/20-1)*(rectLength+2)
pickUpSound.play()
else:
snakeRect.pop(len(snakeRect)-1)
windowSurface.fill(BLACK)
for i in range(len(snakeRect)):
pygame.draw.rect(windowSurface,GREEN,snakeRect[i])
windowSurface.blit(foodImage,food)
if food.left == 0 and food.right == 0:
i = 3
pygame.display.update()
mainClock.tick(10)
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341