python 贪吃蛇小游戏代码
#!/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 HeightWhite = (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 colorUP = 'up'
DOWN = 'down' # Defining keyboard keys.
LEFT = 'left'
RIGHT = 'right'HEAD = 0 # Syntactic sugar: index of the snake's headdef main():global SnakespeedCLOCK, DISPLAYSURF, BASICFONTpygame.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 loopfor event in pygame.event.get(): # event handling loopif event.type == QUIT:terminate()elif event.type == KEYDOWN:if (event.key == K_LEFT) and direction != RIGHT:direction = LEFTelif (event.key == K_RIGHT) and direction != LEFT:direction = RIGHTelif (event.key == K_UP) and direction != DOWN:direction = UPelif (event.key == K_DOWN) and direction != UP:direction = DOWNelif event.key == K_ESCAPE:terminate()# check if the Snake has hit itself or the edgeif wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:return # game overfor 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 applyif wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:# don't remove worm's tail segmentapple = getRandomLocation() # set a new apple somewhereelse:del wormCoords[-1] # remove worm's tail segment# move the worm by adding a segment in the direction it is movingif 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 Noneif keyUpEvents[0].key == K_ESCAPE:terminate()return keyUpEvents[0].keydef showStartScreen():titleFont = pygame.font.Font('freesansbold.ttf', 100)titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)degrees1 = 0degrees2 = 0while 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 queuereturnpygame.display.update()SnakespeedCLOCK.tick(Snakespeed)degrees1 += 3 # rotate by 3 degrees each framedegrees2 += 7 # rotate by 7 degrees each framedef 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 queuewhile True:if checkForKeyPress():pygame.event.get() # clear event queuereturndef 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_Sizey = coord['y'] * Cell_SizewormSegmentRect = 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_Sizey = coord['y'] * Cell_SizeappleRect = 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 linespygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))for y in range(0, Window_Height, Cell_Size): # draw horizontal linespygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))if __name__ == '__main__':try:main()except SystemExit:pass
start
game over
python 贪吃蛇小游戏代码相关推荐
- python 贪吃蛇小游戏代码_10分钟再用Python编写贪吃蛇小游戏
Python编写贪吃蛇 前不久我们公众号发布了一篇C++编写贪吃蛇小游戏的推文,反响空前.看来大家对这类简单易上手小游戏还是很喜爱的. 恰逢2018年IEEE Spectrum编程语言排行榜新鲜出炉, ...
- python贪吃蛇小游戏代码_python 贪吃蛇小游戏代码
#!/usr/bin/python # -*- coding: UTF-8 -*- #作者:黄哥 #链接:https://www.zhihu.com/question/55873159/answer/ ...
- Python贪吃蛇小游戏_完整源码免费分享
文章目录 Python 贪吃蛇小游戏 1. 导包 2. 配置初始化参数 3. 主函数及运行主体 4. 画食物的函数 5. 画贪吃蛇的函数 6. 画网格的函数(非必选,觉得多余的可以忽略此项) 7. 操 ...
- python贪吃蛇小游戏_python开发贪吃蛇小游戏
3.概要设计 3.1 程序功能模块 由设计应解决的问题可知,本次的设计是使用用方向键来实现一个简易的贪吃蛇小游戏的程序,具体的功能模块如图3-1所示. 图3-1 程序功能模块 Fig.3-1 prog ...
- python贪吃蛇小游戏制作思路详解
很多时候,游戏都是一种可以发泄自己内心情绪的工具,在游戏中,我们可以忘记经历过的很多不快.如今呢,随着软硬件的不断提高,游戏市场越来越繁华红火,很多游戏都动辄好几个G.让人不得不感叹啊,以前那种玩贪吃 ...
- 贪吃蛇小游戏代码html,自制贪吃蛇小游戏代码
package game; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Game_St ...
- Python贪吃蛇小游戏教程
今天教大家使用pygame编一个简单贪吃蛇小游戏. 1.导库 import pygame, sys, time, random, zt """ zt库是用来搞游戏暂停的 ...
- python小游戏代码大全-【程序源代码】python贪吃蛇小游戏
关键字:python 游戏 贪吃蛇 正文 | 内容 在网络还不发达,没有平板电脑和手机的童年;电视机里的动画片和小游戏曾经陪伴我们度过了欢乐的时光.扫雷.贪吃蛇.俄罗斯方块.58坦克大战.超级玛丽.魂 ...
- 用Python做贪吃蛇小游戏
用Python做贪吃蛇小游戏 简介 引言 游戏预览 结构图 代码框架图 代码讲解 main主函数-开始工作 show_start_info()欢迎进入游戏 running_game-让我们开始游戏吧 ...
- Python 简单实现贪吃蛇小游戏
文章目录 1. pygame库的简介2. pygame库的安装3. python代码实现贪吃蛇小游戏4. pyinstaller打包成exe 很多人学习python,不知道从何学起. 很多人学习pyt ...
最新文章
- (Oracle)PL SQL的相关知识与实例
- 成功网页设计师的七大必备技能
- 设计模式复习-职责链模式
- 计算机视觉的基石-滤波
- Process Hacker 一个系统监视工具
- UI体系的本质是结构化存在
- 糖果(信息学奥赛一本通-T1299)
- android 底部黑边,android – 截屏周围的黑色边缘
- Ripple_vJZ
- 红橙Darren视频笔记 一个控件显示两种颜色的文字 画笔的使用
- java ssm框架调用微信,微信小程序实现前后台交互(后台使用ssm框架)
- C# 读取Excel表格中的数据
- UVa 400 Unix Is
- 配置centOS下的Python
- ai人工智能_古典AI的简要史前
- 如何把qq挂到云服务器,云服务器挂QQ软件常用方法和注意问题
- 如何使用ESP8266、ESP8285做一个WiFi中继(WiFi信号放大器)
- android youtube免谷歌,youtube免谷歌框架
- 掌握五个元组的用法,让python代码飞得更快
- 炸裂!前浪老狗工作这5年遇到的面试题们,建议老铁们收藏研读