贪吃蛇程序代码python_python 贪吃蛇

贪吃蛇程序代码python_python 贪吃蛇Python贪吃蛇源代码Python代码狂人Python代码大全程序运行截图如下:importpygameaspgfromrandomimportrandintimportsysfrompygame.localsimport*FPS=6#画面帧数,代表蛇的移动速率window_width=600window_height=500cellsize=20c…


Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

Python贪吃蛇源代码

Python代码狂人 Python代码大全

程序运行截图如下:

贪吃蛇程序代码python_python 贪吃蛇

贪吃蛇程序代码python_python 贪吃蛇

import pygame as pg

from random import randint

import sys

from pygame.locals import *

FPS = 6 # 画面帧数,代表蛇的移动速率

window_width = 600

window_height = 500

cellsize = 20

cell_width = int(window_width / cellsize)

cell_height = int(window_height / cellsize)

BGcolor = (0, 0, 0)

BLUE = (0, 0, 255)

RED = (255, 0, 0)

apple_color = (255, 0, 0)

snake_color = (0, 150, 0)

GREEN = (0, 255, 0)

WHITE = (255, 255, 255)

DARKGRAY = (40, 40, 40)

UP = “up”

DOWN = “down”

LEFT = “left”

RIGHT = “right”

HEAD = 0

def main(): # 有函数

global FPSclock, window, BASICFONT

pg.init()

FPSclock = pg.time.Clock()

window = pg.display.set_mode((window_width, window_height))

BASICFONT = pg.font.Font(“freesansbold.ttf”, 18)

pg.display.set_caption(“贪吃蛇”)

showStartScreen()

while True:

runGame()

showGameOverScreen()

def runGame(): # 运行游戏函数

startx = randint(5, cell_width – 6)

starty = randint(5, cell_height – 6)

snakeCoords = [{“x”: startx, “y”: starty}, {“x”: startx – 1, “y”: starty}, {“x”: startx – 2, “y”: starty}]

direction = RIGHT

apple = getRandomLocation()

while True:

for event in pg.event.get():

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()

if snakeCoords[HEAD][“x”] == -1 or snakeCoords[HEAD][“x”] == cell_width or snakeCoords[HEAD][“y”] == -1 or \

snakeCoords[HEAD][“y”] == cell_height:

return

for snakeBody in snakeCoords[1:]:

if snakeBody[“x”] == snakeCoords[HEAD][“x”] and snakeBody[“y”] == snakeCoords[HEAD][“y”]:

return

if snakeCoords[HEAD][“x”] == apple[“x”] and snakeCoords[HEAD][“y”] == apple[“y”]:

apple = getRandomLocation()

else:

del snakeCoords[-1]

if direction == UP:

newHead = {“x”: snakeCoords[HEAD][“x”], “y”: snakeCoords[HEAD][“y”] – 1}

elif direction == DOWN:

newHead = {“x”: snakeCoords[HEAD][“x”], “y”: snakeCoords[HEAD][“y”] + 1}

elif direction == LEFT:

newHead = {“x”: snakeCoords[HEAD][“x”] – 1, “y”: snakeCoords[HEAD][“y”]}

elif direction == RIGHT:

newHead = {“x”: snakeCoords[HEAD][“x”] + 1, “y”: snakeCoords[HEAD][“y”]}

snakeCoords.insert(0, newHead)

window.fill(BGcolor)

drawGrid()

drawSnake(snakeCoords)

drawApple(apple)

drawScore(len(snakeCoords) – 3)

pg.display.update()

FPSclock.tick(FPS)

def drawPressKeyMsg(): # 游戏开始提示信息

pressKeySurf = BASICFONT.render(“press a key to play”, True, BLUE)

pressKeyRect = pressKeySurf.get_rect()

pressKeyRect.topleft = (window_width – 200, window_height – 30)

window.blit(pressKeySurf, pressKeyRect)

def checkForKeyPress(): # 检查是否触发按键

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

terminate()

keyUpEvents = pg.event.get(KEYUP)

if len(keyUpEvents) == 0:

return None

if keyUpEvents[0].key == K_ESCAPE:

terminate()

return keyUpEvents[0].key

def showStartScreen(): # 开始画面

window.fill(BGcolor)

titleFont = pg.font.Font(“freesansbold.ttf”, 100)

titleSurf = titleFont.render(“snake!”, True, RED)

titleRect = titleSurf.get_rect()

titleRect.center = (window_width / 2, window_height / 2)

window.blit(titleSurf, titleRect)

drawPressKeyMsg()

pg.display.update()

while True:

if checkForKeyPress():

pg.event.get()

return

def terminate(): # 退出

pg.quit()

sys.exit()

def getRandomLocation(): # 出现位置

return {“x”: randint(0, cell_width – 1), “y”: randint(0, cell_height – 1)}

def showGameOverScreen(): # 游戏结束

gameOverFont = pg.font.Font(“freesansbold.tff”, 150)

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.height10 + 25)

window.blit(gameSurf, gameRect)

window.blit(overSurf, overRect)

drawPressKeyMsg()

pg.display.update()

pg.time.wait(500)

checkForKeyPress()

while True:

if checkForKeyPress():

pg.event.get()

return

def drawScore(score): # 显示分数

scoreSurf = BASICFONT.render(“Score:%s” % (score), True, WHITE)

scoreRect = scoreSurf.get_rect()

scoreRect.topleft = (window_width – 120, 10)

window.blit(scoreSurf, scoreRect)

def drawSnake(snakeCoords): # 画蛇

for coord in snakeCoords:

x = coord[“x”] * cellsize

y = coord[“y”] * cellsize

snakeSegmentRect = pg.Rect(x, y, cellsize, cellsize)

pg.draw.rect(window, snake_color, snakeSegmentRect)

snakeInnerSegmentRect = pg.Rect(x + 4, y + 4, cellsize – 8, cellsize – 8)

pg.draw.rect(window, GREEN, snakeInnerSegmentRect)

def drawApple(coord):

x = coord[“x”] * cellsize

y = coord[“y”] * cellsize

appleRect = pg.Rect(x, y, cellsize, cellsize)

pg.draw.rect(window, apple_color, appleRect)

def drawGrid(): # 画方格

for x in range(0, window_width, cellsize):

pg.draw.line(window, DARKGRAY, (x, 0), (x, window_height))

for y in range(0, window_height, cellsize):

pg.draw.line(window, DARKGRAY, (0, y), (window_width, y))

if __name__ == “__main__”:

main()

程序调试过程中遇到问题,欢迎在本文后留言。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/169553.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Git clone的使用方法[通俗易懂]

    Git clone的使用方法[通俗易懂]使用Gitclone项目1.首先我们要确保我们的电脑上已经安装Git。桌面点击右键出现如下图所示的两个Git即Git已经安装。2.在电脑的任意一个磁盘里新建一个本地文件夹作为clone项目的保存文件夹。3.在码云上面打开我们要clone的项目。4.点击克隆/下载按钮出现项目地址的连接,点击后面的复制。5.进入我们创建的本地文件夹内,右击选择GitBash…

    2022年7月21日
  • python的常见矩阵除法_Python矩阵除法

    python的常见矩阵除法_Python矩阵除法我有一个关于按元素划分矩阵的问题,我的意思是我想要第一个矩阵的元素[I,j]除以第二个矩阵(Q)的元素[I,j]。在一些背景信息:我从我的存储器加载了一个图像。我把每个像素的单色值存储在一个叫做“pixelMatrix”的矩阵中此命令将大矩阵(128×128)转换为较小的矩阵(8×8)foto_dct=skimage.util.view_as_blocks(pixelMatrix,block…

    2022年6月14日
  • 【C++】volatile关键字的作用「建议收藏」

    【C++】volatile关键字的作用「建议收藏」volatile的作用volatile关键字是防止在共享的空间发生读取的错误。只保证其可见性,不保证原子性;使用volatile指每次从内存中读取数据,而不是从编译器优化后的缓存中读取数据,简单来讲就是防止编译器优化。在单任务环境中,如果在两次读取变量之间不改变变量的值,编译器就会发生优化,会将RAM中的值赋值到寄存器中;由于访问寄存器的效率要高于RAM,所以在需要读取变量时,直接寄存器中…

    2022年5月31日
  • sql注入orderby子句的功能_sql order by

    sql注入orderby子句的功能_sql order byuniqueidentifier全局唯一标识符(GUID)。注释uniqueidentifier数据类型的列或局部变量可用两种方法初始化为一个值:使用NEWID函数。将字符串常量转换为如下形式(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,其中

    2022年10月31日
  • 2021电赛F题智能送药小车方案分析(openMV数字识别,红线循迹,STM32HAL库freeRTOS,串级PID快速学习,小车自动返回)[通俗易懂]

    2021电赛F题智能送药小车方案分析(openMV数字识别,红线循迹,STM32HAL库freeRTOS,串级PID快速学习,小车自动返回)[通俗易懂]2021电赛F题智能送药小车方案分析(openARTmini数字识别加循迹融合代码,STM32HAL库freeRTOS,串级PID快速学习,小车自动返回)附有工程代码链接,分析详细,工程完善

    2022年8月31日
  • 华为模拟器ensp怎么安装_华为游戏模拟器电脑版

    华为模拟器ensp怎么安装_华为游戏模拟器电脑版ENSP(EnterpriseNetworkSimulationPlatform)是一个图形化网络仿真平台,该平台通过对真实网络设备的仿真模拟,帮助广大ICT从业者和客户快速熟悉华为数通系列产品,了解并掌握相关产品的操作和配置、提升对企业ICT网络的规划、建设、运维能力,从而帮助企业构建更高效,更优质的企业ICT网络。操作环境:Win10专业工作站版、VirtualBox-5.2.26-128414、WinPcap_4_1_3、Wireshark-win64-1.12.4文章目录一、详..

    2022年10月10日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号