#!/usr/bin/python

# -*- coding: UTF-8 -*-

#作者:黄哥

#链接:https://www.zhihu.com/question/55873159/answer/146647646

#来源:知乎

#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

import random

import pygame

import sys

from pygame.locals import *

Snakespeed = 17

Window_Width = 800

Window_Height = 500

Cell_Size = 20 # Width and height of the cells

# Ensuring that the cells fit perfectly in the window. eg if cell size was

# 10 and window width or windowheight were 15 only 1.5 cells would

# fit.

assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."

# Ensuring that only whole integer number of cells fit perfectly in the window.

assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."

Cell_W = int(Window_Width / Cell_Size) # Cell Width

Cell_H = int(Window_Height / Cell_Size) # Cellc Height

White = (255, 255, 255)

Black = (0, 0, 0)

Red = (255, 0, 0) # Defining element colors for the program.

Green = (0, 255, 0)

DARKGreen = (0, 155, 0)

DARKGRAY = (40, 40, 40)

YELLOW = (255, 255, 0)

Red_DARK = (150, 0, 0)

BLUE = (0, 0, 255)

BLUE_DARK = (0, 0, 150)

BGCOLOR = Black # Background color

UP = 'up'

DOWN = 'down' # Defining keyboard keys.

LEFT = 'left'

RIGHT = 'right'

HEAD = 0 # Syntactic sugar: index of the snake's head

def main():

global SnakespeedCLOCK, DISPLAYSURF, BASICFONT

pygame.init()

SnakespeedCLOCK = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))

BASICFONT = pygame.font.Font('freesansbold.ttf', 18)

pygame.display.set_caption('Snake')

showStartScreen()

while True:

runGame()

showGameOverScreen()

def runGame():

# Set a random start point.

startx = random.randint(5, Cell_W - 6)

starty = random.randint(5, Cell_H - 6)

wormCoords = [{'x': startx, 'y': starty},

{'x': startx - 1, 'y': starty},

{'x': startx - 2, 'y': starty}]

direction = RIGHT

# Start the apple in a random place.

apple = getRandomLocation()

while True: # main game loop

for event in pygame.event.get(): # event handling loop

if event.type == QUIT:

terminate()

elif event.type == KEYDOWN:

if (event.key == K_LEFT) and direction != RIGHT:

direction = LEFT

elif (event.key == K_RIGHT) and direction != LEFT:

direction = RIGHT

elif (event.key == K_UP) and direction != DOWN:

direction = UP

elif (event.key == K_DOWN) and direction != UP:

direction = DOWN

elif event.key == K_ESCAPE:

terminate()

# check if the Snake has hit itself or the edge

if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:

return # game over

for wormBody in wormCoords[1:]:

if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:

return # game over

# check if Snake has eaten an apply

if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:

# don't remove worm's tail segment

apple = getRandomLocation() # set a new apple somewhere

else:

del wormCoords[-1] # remove worm's tail segment

# move the worm by adding a segment in the direction it is moving

if direction == UP:

newHead = {'x': wormCoords[HEAD]['x'],

'y': wormCoords[HEAD]['y'] - 1}

elif direction == DOWN:

newHead = {'x': wormCoords[HEAD]['x'],

'y': wormCoords[HEAD]['y'] + 1}

elif direction == LEFT:

newHead = {'x': wormCoords[HEAD][

'x'] - 1, 'y': wormCoords[HEAD]['y']}

elif direction == RIGHT:

newHead = {'x': wormCoords[HEAD][

'x'] + 1, 'y': wormCoords[HEAD]['y']}

wormCoords.insert(0, newHead)

DISPLAYSURF.fill(BGCOLOR)

drawGrid()

drawWorm(wormCoords)

drawApple(apple)

drawScore(len(wormCoords) - 3)

pygame.display.update()

SnakespeedCLOCK.tick(Snakespeed)

def drawPressKeyMsg():

pressKeySurf = BASICFONT.render('Press a key to play.', True, White)

pressKeyRect = pressKeySurf.get_rect()

pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)

DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

def checkForKeyPress():

if len(pygame.event.get(QUIT)) > 0:

terminate()

keyUpEvents = pygame.event.get(KEYUP)

if len(keyUpEvents) == 0:

return None

if keyUpEvents[0].key == K_ESCAPE:

terminate()

return keyUpEvents[0].key

def showStartScreen():

titleFont = pygame.font.Font('freesansbold.ttf', 100)

titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)

degrees1 = 0

degrees2 = 0

while True:

DISPLAYSURF.fill(BGCOLOR)

rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)

rotatedRect1 = rotatedSurf1.get_rect()

rotatedRect1.center = (Window_Width / 2, Window_Height / 2)

DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)

drawPressKeyMsg()

if checkForKeyPress():

pygame.event.get() # clear event queue

return

pygame.display.update()

SnakespeedCLOCK.tick(Snakespeed)

degrees1 += 3 # rotate by 3 degrees each frame

degrees2 += 7 # rotate by 7 degrees each frame

def terminate():

pygame.quit()

sys.exit()

def getRandomLocation():

return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}

def showGameOverScreen():

gameOverFont = pygame.font.Font('freesansbold.ttf', 100)

gameSurf = gameOverFont.render('Game', True, White)

overSurf = gameOverFont.render('Over', True, White)

gameRect = gameSurf.get_rect()

overRect = overSurf.get_rect()

gameRect.midtop = (Window_Width / 2, 10)

overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)

DISPLAYSURF.blit(gameSurf, gameRect)

DISPLAYSURF.blit(overSurf, overRect)

drawPressKeyMsg()

pygame.display.update()

pygame.time.wait(500)

checkForKeyPress() # clear out any key presses in the event queue

while True:

if checkForKeyPress():

pygame.event.get() # clear event queue

return

def drawScore(score):

scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)

scoreRect = scoreSurf.get_rect()

scoreRect.topleft = (Window_Width - 120, 10)

DISPLAYSURF.blit(scoreSurf, scoreRect)

def drawWorm(wormCoords):

for coord in wormCoords:

x = coord['x'] * Cell_Size

y = coord['y'] * Cell_Size

wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)

pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)

wormInnerSegmentRect = pygame.Rect(

x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)

pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)

def drawApple(coord):

x = coord['x'] * Cell_Size

y = coord['y'] * Cell_Size

appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)

pygame.draw.rect(DISPLAYSURF, Red, appleRect)

def drawGrid():

for x in range(0, Window_Width, Cell_Size): # draw vertical lines

pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))

for y in range(0, Window_Height, Cell_Size): # draw horizontal lines

pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))

if __name__ == '__main__':

try:

main()

except SystemExit:

pass

start

game over

python贪吃蛇小游戏代码_python 贪吃蛇小游戏代码相关推荐

  1. 编写五子棋的完整python代码_python制作简单五子棋游戏

    本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 #五子棋 '" 矩阵做棋盘 16*16 "+" 打印棋盘 for for 游戏是否结束 开 ...

  2. python打地鼠游戏代码_Python 0基础开发游戏:打地鼠(详细教程)VS code版本

    如果你没有任何编程经验,而且想尝试一下学习编程开发,这个系列教程一定适合你,它将带你学习最基本的Python语法,并让你掌握小游戏的开发技巧.你所需要的,就是付出一些时间和耐心来尝试这些代码和操作.文 ...

  3. python打地鼠游戏教程_Python 0基础开发游戏:打地鼠(详细教程)VS code版本

    如果你没有任何编程经验,而且想尝试一下学习编程开发,这个系列教程一定适合你,它将带你学习最基本的Python语法,并让你掌握小游戏的开发技巧.你所需要的,就是付出一些时间和耐心来尝试这些代码和操作.文 ...

  4. python能不能开发游戏脚本_Python脚本如何保证游戏正常开发

    Python脚本如何保证游戏正常开发 Python脚本是一种广泛应用于玩游戏开发的通信语言,在实际应用的过程中还是有不少的问题困扰着开发人员,下面是Python脚本在实际应用中的具体问题解决方案.希望 ...

  5. python小工具脚本_python实现倒计时小工具

    本文实例为大家分享了python实现倒计时小工具的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # coding=utf-8 import threading imp ...

  6. python制作飞机大战代码_python实现飞机大战完整代码,可运行

    我发现很多python代码飞机大战在互联网上,但几乎没有一个是完整的.所以我做了一个完整的人.python代码分为两个文件,工具类和主类.python版本,pygame模块需要安装.完整的代码如下.1 ...

  7. python怎么清除代码_python的shell中的代码怎么清理?

    python shell是Python的命令行. 交互模式下使用Python很方便,如果想清除显示过的信息,有两种方法可以采用. 方法一.针对Python命令行(python shell) 直接使用下 ...

  8. python制作图片拼图游戏下载_Python图像处理——人物拼图游戏

    游戏介绍: 拼图游戏将一幅图片分割咸若干拼块并将它们随机打乱顺序,当将所有拼块都放回原位置时,就完成了拼图(游戏结束).本人物拼图游戏为3行3列,拼块以随机顺序排列,玩家用鼠标单击空白块四周的交换它们 ...

  9. 贪吃蛇python语言代码_Python贪吃蛇简单的代码

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 在自学Python的过程中在网上查询资料时发现了一些好玩的东西,python的游戏库模块,它可以自己弄一个小游戏来玩玩,然后我在网上找了一些游戏的代码,, ...

最新文章

  1. C1之路 | 备考C1
  2. Docker环境运行SpringBoot项目
  3. 3.15计算机网络原理与技术笔记
  4. 初入前端,面对一个项目应注意哪些?
  5. 树状数组,Fenwick Tree
  6. java-JSON: Expected value at 1:0 错误
  7. 网络html代码是什么问题,html代码问题
  8. 全球通用头像gravatar介绍
  9. 通达OA2019安装教程
  10. 嵌入式应用软件开发的步骤流程
  11. 手机safari导入html书签,苹果手机safari书签及其历史记录怎么恢复
  12. Linux入门基础——常用命令(四)
  13. JSON.stringify(value[, replacer[, space]])中三个参数详解
  14. 地毯店人员告诉你如何正确选购合适地毯
  15. 奇想大白话之《羊了个羊》为何火,技术很厉害吗?
  16. 绵阳南山中学计算机老师邱浩,还原“博士论文走红”的中科院博士:学成还乡衣着朴素...
  17. 扫雷游戏 (15 分)
  18. 计算机一级考试内容有哪些?
  19. android物理键盘灯控制,Android按键灯流程分析
  20. 团体程序设计天梯赛-练习集 L2-028 秀恩爱分得快 (25 分) (详细解法)

热门文章

  1. java socket一直得不到返回值
  2. signature=694cde3d7f2450116894167453553a22,FIDO-U2F-Ledger 注册和登录过程中chrome和后台交互log分析...
  3. SQL代码——数据库,数据表代码操作
  4. 排序算法之一 冒泡排序(Bubble Sort)
  5. 解决adb输入中文以及乱码的问题
  6. 基于Mirai框架的QQ机器人使用文档----郑大科协2021招新群
  7. Visual Studio 2019版本运行报错解决方案
  8. MySql 笛卡儿积
  9. #2020寒假集训#二分入门(Binary Search)代码笔记
  10. 有个定时任务突然不执行了,别急,原因可能在这