贪吃蛇程序代码python_python 贪吃蛇

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

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java 拉姆达表达式_一看就懂之java8新特性函数式编程:我是拉姆达表达式lambda…

    java 拉姆达表达式_一看就懂之java8新特性函数式编程:我是拉姆达表达式lambda…我们都知道,java8之后增加了很多新特性,大大的简化了代码的编写、阅读的负担。先发个牢骚:今天up主根据自己的理解跟大家说说新特性之一的lambdaexpress(拉姆达表达式),每当看到新的语法改动,内心我都是拒绝的。因为又要学习、又要适应、又要改变真烦人,可是没办法现在这几乎是所有大厂必须的操作。总不能看不懂人家写的代码吧,做IT行业尤其是软件工程师必须要保证自己的知识及时更新、知识面不…

    2022年9月19日
    3
  • Landsat8卫星介绍[通俗易懂]

    Landsat8卫星介绍[通俗易懂]2013年2月11号,NASA成功发射了Landsat8卫星,为走过了四十年辉煌岁月的Landsat计划重新注入新鲜血液,设计使用寿命为至少5年。Landsat8上携带有两个主要载荷:OLI和TIRS,其中OLI(全称:OperationalLandImager,陆地成像仪)由卡罗拉多州的鲍尔航天技术公司研制;TIRS(全称:ThermalInfraredSensor,热红外传感器

    2022年7月23日
    11
  • 快速排序(Python实现)

    一、算法介绍快速排序是经常考查到的排序算法,这里对快排算法做一下总结。快速排序是“交换”类的排序,它通过多次划分操作实现排序!以升序为例,其执行流程可以概括为:每一趟排序选择当前所有子序列的一个关键字(通常是第一个)作为枢轴量,将子序列中比枢轴量小的移到枢轴前边,比枢轴大的移到枢轴后边,具体过程是一个交替扫描和交换的过程。当本趟所有子序列都被枢轴以上述规则划分完毕后会得到新的一组更短的子序列,…

    2022年4月6日
    51
  • clion 2022.01.13激活码【中文破解版】「建议收藏」

    (clion 2022.01.13激活码)好多小伙伴总是说激活码老是失效,太麻烦,关注/收藏全栈君太难教程,2021永久激活的方法等着你。https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~0HKLM1UCCY-eyJsaWNlbnNlSWQiOi…

    2022年3月31日
    163
  • 高级C/C++编译技术之读书笔记(二)之库的概念

    本节思维导图1.位置无关代码(PIC)首先,需要理解加载域与运行域的概念。加载域是代码存放的地址,运行域是代码运行时的地址。为什么会产生这2个概念?这2个概念的实质意义又是什么呢?在一些场合,

    2021年12月28日
    38
  • Dataway让 Spring Boot 开发变得更高效!

    Dataway让 Spring Boot 开发变得更高效!

    2020年11月14日
    220

发表回复

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

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