#导入相关模块与函数importrandom, pygame, sys
frompygame.locals import*
globalSpeed,Trackingtime, Displayobject, WindowTypeface
pygame.init() #初始化pygame,为使用硬件做准备Speed = 8Trackingtime = pygame.time.Clock() #创建一个对象来帮助跟踪时间Displayobject = pygame.display.set_mode((640,480))
WindowTypeface = pygame.font.SysFont('Calibri.ttf', 25) #从一个字体文件创建一个Typeface对象pygame.display.set_caption('贪吃蛇') #设置窗口标题cellsize = 20backgroundcolor = (255,255,255) #白色#侦测操作defCheckKeyboardPress():
iflen(pygame.event.get(QUIT)) > 0:
pygame.quit()
sys.exit()
keyUpEvents = pygame.event.get(KEYUP)
iflen(keyUpEvents) == 0:
return NonereturnkeyUpEvents[0].key
#游戏开始界面设计defDesignStartScreen():
globalSpeed
titleTypeface1 = pygame.font.SysFont('Calibri.ttf', 200)
titleTypeface2 = pygame.font.SysFont('Calibri.ttf', 60)
KeyboardTypeface= pygame.font.SysFont('Calibri.ttf', 15)
titleContent1 = titleTypeface1.render('RETRO SNAKER', True, (0,0,0),(0,0,0))
titleContent2 = titleTypeface2.render('RETRO SNAKER', True, (255,0,0))
KeyboardContent = WindowTypeface.render('Press any key to start', True, (0,0,0))
Displayobject.fill(backgroundcolor)
revolveContent1 = pygame.transform.rotate(titleContent1, 0)
revolveRect1 = revolveContent1.get_rect()
revolveRect1.center = (640/ 2, 480/ 2)
Displayobject.blit(revolveContent1, revolveRect1)
revolveContent2 = pygame.transform.rotate(titleContent2, 0)
revolveRect2 = revolveContent2.get_rect()
revolveRect2.center = (640/ 2, 480/ 2)
Displayobject.blit(revolveContent2, revolveRect2)
KeyboardRect = KeyboardContent.get_rect() #获得一个对象的rect,以便于设置其坐标位置KeyboardRect.topleft = (640- 200, 480- 30)
Displayobject.blit(KeyboardContent, KeyboardRect.topleft)
pygame.display.update()
Trackingtime.tick(Speed)
while True:
ifCheckKeyboardPress():
pygame.event.get() #清除事件队列return#游戏结束界面设计defDesignGameOverScreen():
gameOverTypeface = pygame.font.SysFont('Calibri.ttf', 100)
KeyboardTypeface= pygame.font.SysFont('Calibri.ttf', 20)#freesansboldgameoverContent = gameOverTypeface.render('Game Over', True, (0,0,0))
KeyboardContent = WindowTypeface.render('Press any key to restart', True, (0,0,0))
gameoverRect = gameoverContent.get_rect()
gameoverRect.center = (640/ 2, 480/ 2)
Displayobject.blit(gameoverContent,gameoverRect)
KeyboardRect = KeyboardContent.get_rect() #获得一个对象的rect,以便于设置其坐标位置KeyboardRect.topleft = (640- 220, 480- 30)
Displayobject.blit(KeyboardContent, KeyboardRect.topleft)
pygame.display.update()
pygame.time.wait(600)
while True:
ifCheckKeyboardPress():
pygame.event.get() #清除事件队列return#贪吃蛇蛇身设计defDesignRetroSnaker(RetroSnakerCoords):
forcoord inRetroSnakerCoords:
x = coord['x'] * 20#规定每行单元格的大小为20y = coord['y'] * 20RetroSnakerSegmentRect = pygame.Rect(x, y, 20, 20)
pygame.draw.rect(Displayobject, (0,0,255), RetroSnakerSegmentRect)
RetroSnakerInnerSegmentRect = pygame.Rect(x + 4, y + 4, 20- 8, 20- 8)
pygame.draw.rect(Displayobject, (173, 216, 230), RetroSnakerInnerSegmentRect)
#苹果设计defDesignApple(coord):
x = coord['x'] * 20y = coord['y'] * 20appleRect = pygame.Rect(x, y, 20, 20)
pygame.draw.rect(Displayobject, (255,0,0), appleRect)
#分数设计defDesignScore(score):
scoreContent = WindowTypeface.render('Score: %s'% (score), True, (0,0,0))
scoreRect = scoreContent.get_rect()
scoreRect.topleft = (640- 100, 10)
Displayobject.blit(scoreContent, scoreRect)
#边框线设计defDesignBorderline():
forx inrange(0, 640, 640-1): #绘制垂直线pygame.draw.line(Displayobject, (0,0,0), (x, 0), (x, 480),5)
fory inrange(0, 480, 480-1):#绘制平行线pygame.draw.line(Displayobject, (0,0,0), (0, y), (640, y),5)
#设置游戏主要运行机制defGameRunning():
globalSpeed
#设置随机起点startx = random.randint(5, 26) #初始单元格位置横向在(5, 26)范围中选一个随机数starty = random.randint(5, 18) #初始单元格位置纵向在(5, 18)范围中选一个随机数RetroSnakerCoords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]#RetroSnakerCoords:列表,贪吃蛇坐标位置direction = 'right'#初始方向朝右#设置苹果在一个随机位置apple = {'x':random.randint(0,31),'y':random.randint(0,23)}
while True: #游戏主循环#判断键盘事件forevent inpygame.event.get(): #事件处理循环ifevent.type == KEYDOWN:
ifevent.key == K_LEFT anddirection != 'right':
direction = 'left'elifevent.key == K_RIGHT anddirection != 'left':
direction = 'right'elifevent.key == K_UP anddirection != 'down':
direction = 'up'elifevent.key == K_DOWN anddirection != 'up':
direction = 'down'#根据方向改变蛇头的坐标ifdirection == 'up':
m = {'x': RetroSnakerCoords[0]['x'], 'y': RetroSnakerCoords[0]['y'] - 1}
elifdirection == 'down':
m = {'x': RetroSnakerCoords[0]['x'], 'y': RetroSnakerCoords[0]['y'] + 1}
elifdirection == 'left':
m = {'x': RetroSnakerCoords[0]['x'] - 1, 'y': RetroSnakerCoords[0]['y']}
elifdirection == 'right':
m = {'x': RetroSnakerCoords[0]['x'] + 1, 'y': RetroSnakerCoords[0]['y']}
#通过向贪吃蛇移动的方向添加一个单元格来加长贪吃蛇RetroSnakerCoords.insert(0, m)
#侦测贪吃蛇是否吃到苹果ifRetroSnakerCoords[0]['x'] == apple['x'] andRetroSnakerCoords[0]['y'] == apple['y']:
apple = {'x':random.randint(0,31),'y':random.randint(0,23)}#在随机位置放置一个苹果Speed = Speed + 0.2else:
delRetroSnakerCoords[-1] #去除贪吃蛇的尾段#侦测贪吃蛇是否触碰到窗口边缘或自身ifRetroSnakerCoords[0]['x'] == -1orRetroSnakerCoords[0]['x'] == 32orRetroSnakerCoords[0]['y'] == -1orRetroSnakerCoords[0]['y'] == 24:
return#游戏结束forRetroSnakerBody inRetroSnakerCoords[1:]:
ifRetroSnakerCoords[0]['x'] == RetroSnakerBody['x'] andRetroSnakerCoords[0]['y'] == RetroSnakerBody['y']:
return#游戏结束#绘制相关角色在窗口中Displayobject.fill(backgroundcolor)
DesignRetroSnaker(RetroSnakerCoords)
DesignApple(apple)
DesignScore(len(RetroSnakerCoords) - 3)
DesignBorderline()
pygame.display.update() #让绘制的东西显示在屏幕上Trackingtime.tick(Speed)
if__name__ == '__main__':
DesignStartScreen()
while True:
GameRunning()
DesignGameOverScreen(