Python贪吃蛇双人大战
晚上家里小朋友要玩贪吃蛇游戏,还要跟我对战,一时半会我没想到去哪里下这样一个游戏,忽然灵机一动,可以自己写一个,顺便还可以跟小朋友展示一下程序员的厉害,于是开工。
原始版本
这是一个很基础的程序,自然不用从头写,在网上随便一搜,找到有人共享的代码,链接如下:https://www.cnblogs.com/qiu2013/p/6087627.html,据说是来源于《Raspberry Pi 用户指南》的代码,我也没有去查。代码如下:
#!/usr/bin/env python
import pygame,sys,time,random
from pygame.locals import *
# 定义颜色变量
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)
# 定义gameOver函数
def gameOver(playSurface):
gameOverFont = pygame.font.Font('arial.ttf',72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
# 定义main函数
def main():
# 初始化pygame
pygame.init()
fpsClock = pygame.time.Clock()
# 创建pygame显示层
playSurface = pygame.display.set_mode((640,480))
pygame.display.set_caption('Raspberry Snake')
# 初始化变量
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
while True:
# 检测例如按键等pygame事件
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 == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# 判断是否输入了反方向
if changeDirection ==