贪吃蛇程序代码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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Python 递归的多种写法

    Python 递归的多种写法题目背景:让我们来看一些例子。要对一个数字列表(或者其他序列)求和,我们可以使用内置的sum函数,或者自己编写一个更加定制化的版本。这里是用递归编写的一个定制求和函数的示例defmysum(L): ifnotL: return0 else: returnL[0]+mysum(L[1:])这是一种最基本的递归写法,通过递归的方式将列表中的所有进行相加,典型的鸭子类型…

    2022年6月16日
  • winform界面美化

    winform界面美化 介绍如下:1.这是DELPHI的换肤软件的DOTNET版,使用简单并有皮肤编辑工具,可到官方网站去下,当前版本为:1.20.1,更新时间:2008-04-202.这次发布的版本包括了DotNetSkin的ForVS2003和VS2005两个版本。3.未破解前,如果要显示标题栏,则标题标显示的是Logo图片,样式请看官方的DEMO程序;如果不显示标题栏,则在程序启动的时候提示一个对话框(T

    2022年5月8日
  • mshta简介

    mshta简介mshta.exe,HTMLApplicationHOST,HTML应用程序主机,hta文件解释器(也能解释html),就如同IE是html的解释器,CMD是批处理文件的解释器,WScript.exe、CScript.exe是vbs/js脚本的解释器。mshta的命令行参数似乎并未公开,mshta/?等方式得不到任何帮助信息。大家如果感兴趣可以去csdn或微软的msdn查查。从网上我仅找到…

    2022年7月15日
  • 使用SecureCRTPortable的过程中出现的乱码问题解决方式

    使用SecureCRTPortable的过程中出现的乱码问题解决方式各位小伙伴好:可能大家都遇到过使用SecureCRTPortable【以下简称CRT】查日志的过程中出现乱码问题,下面超哥给各位普及下对于乱码的处理方式:1,有可能是当前连接的服务器显示的编码不是utf-8的编码,那样的话就直接修改字符编码就好了,2,当上面的方式不起作用的时候你需要检查下你服务器里的配置喽,第一:执行命令:more…

    2022年5月2日
  • qsqlquery查询到的数据个数_获取sequence的当前值

    qsqlquery查询到的数据个数_获取sequence的当前值publicintselectAll(finalStringtime1, finalStringtime2,finalintcityname,finalStringairstatus){ finalStringBufferhql=newStringBuffer( “selectcount(air)fromTableNameair

    2022年9月26日
  • 【ubuntu修改密码】ubuntu忘记密码,修改密码[通俗易懂]

    【ubuntu修改密码】ubuntu忘记密码,修改密码[通俗易懂]ubuntu忘记密码,修改密码在启动ubuntu时,迅速按下shift键,进入grub启动菜单界面,选中高级选项,回车;选择recoverymode模式,即系统和密码恢复模式。然后按e启动编辑上下移动光标到recoverynomodeset位置,删除recoverynomodeset删除之后,在该位置添加quietsplashrwinit=/bin/bash,然后按f10按下f10后,进入编辑页面,在这里可以通过输入passwd来重置root账户密码,也可以通过输入passw

    2022年9月29日

发表回复

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

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