python贪吃蛇编程代码大全_200行python代码实现贪吃蛇游戏

python贪吃蛇编程代码大全_200行python代码实现贪吃蛇游戏本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下这次我们来写一个贪吃蛇游戏下面贴出具体代码importpygameimporttimeimportnumpyasnp#此模块包含游戏所需的常量frompygame.localsimport*#设置棋盘的长宽BOARDWIDTH=48BOARDHEIGHT=28#分数score=0cl…

大家好,又见面了,我是你们的朋友全栈君。

本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

这次我们来写一个贪吃蛇游戏

下面贴出具体代码

import pygame

import time

import numpy as np

# 此模块包含游戏所需的常量

from pygame.locals import *

# 设置棋盘的长宽

BOARDWIDTH = 48

BOARDHEIGHT = 28

# 分数

score = 0

class Food(object):

def __init__(self):

self.item = (4, 5)

# 画出食物

def _draw(self, screen, i, j):

color = 255, 0, 255

radius = 10

width = 10

# i:1—34 j:1—25

position = 10 + 20 * i, 10 + 20 * j

# 画出半径为 10 的粉色实心圆

pygame.draw.circle(screen, color, position, radius, width)

# 随机产生食物

def update(self, screen, enlarge, snack):

if enlarge:

self.item = np.random.randint(1, BOARDWIDTH – 2), np.random.randint(1, BOARDHEIGHT – 2)

while self.item in snack.item:

self.item = np.random.randint(1, BOARDWIDTH – 2), np.random.randint(1, BOARDHEIGHT – 2)

self._draw(screen, self.item[0], self.item[1])

# 贪吃蛇

class Snack(object):

def __init__(self):

# self.item = [(3, 25), (2, 25), (1, 25), (1,24), (1,23),

# (1,22), (1,21), (1,20), (1,19), (1,18), (1,17), (1,16)]

# x 水平方向 y 竖直方向

# 初始方向竖直向上

self.item = [(3, 25), (2, 25), (1, 25), (1, 24), ]

self.x = 0

self.y = -1

def move(self, enlarge):

# enlarge 标记贪吃蛇有没有吃到食物

if not enlarge:

# 吃到食物删除尾部元素

self.item.pop()

# 新蛇头的坐标为旧蛇头坐标加上移动方向的位移

head = (self.item[0][0] + self.x, self.item[0][1] + self.y)

# 将新的蛇头坐标插入在 list 最前面

self.item.insert(0, head)

def eat_food(self, food):

global score

# snack_x,snack_y 蛇头坐标

# food_x, food_y 食物坐标

snack_x, snack_y = self.item[0]

food_x, food_y = food.item

# 比较蛇头坐标与食物坐标

if (food_x == snack_x) and (food_y == snack_y):

score += 100

return 1

else:

return 0

def toward(self, x, y):

# 改变蛇头朝向

if self.x * x >= 0 and self.y * y >= 0:

self.x = x

self.y = y

def get_head(self):

# 获取蛇头坐标

return self.item[0]

def draw(self, screen):

# 画出贪吃蛇

# 蛇头为半径为 15 的红色实心圆

radius = 15

width = 15

# i:1—34 j:1—25

color = 255, 0, 0

# position 为图形的坐标

position = 10 + 20 * self.item[0][0], 10 + 20 * self.item[0][1]

pygame.draw.circle(screen, color, position, radius, width)

# 蛇身为半径为 10 的黄色实心圆

radius = 10

width = 10

color = 255, 255, 0

for i, j in self.item[1:]:

position = 10 + 20 * i, 10 + 20 * j

pygame.draw.circle(screen, color, position, radius, width)

# 初始界面

def init_board(screen):

board_width = BOARDWIDTH

board_height = BOARDHEIGHT

color = 10, 255, 255

width = 0

# width:x, height:y

# 左右边框占用了 X: 0 35*20

for i in range(board_width):

pos = i * 20, 0, 20, 20

pygame.draw.rect(screen, color, pos, width)

pos = i * 20, (board_height – 1) * 20, 20, 20

pygame.draw.rect(screen, color, pos, width)

# 上下边框占用了 Y: 0 26*20

for i in range(board_height – 1):

pos = 0, 20 + i * 20, 20, 20

pygame.draw.rect(screen, color, pos, width)

pos = (board_width – 1) * 20, 20 + i * 20, 20, 20

pygame.draw.rect(screen, color, pos, width)

# 游戏失败

def game_over(snack):

broad_x, broad_y = snack.get_head()

flag = 0

old = len(snack.item)

new = len(set(snack.item))

# 游戏失败的两种可能

# 咬到自身

if new < old:

flag = 1

# 撞到边框

if broad_x == 0 or broad_x == BOARDWIDTH – 1:

flag = 1

if broad_y == 0 or broad_y == BOARDHEIGHT – 1:

flag = 1

if flag:

return True

else:

return False

# 打印字符

def print_text(screen, font, x, y, text, color=(255, 0, 0)):

# 在屏幕上打印字符

# text是需要打印的文本,color为字体颜色

# (x,y)是文本在屏幕上的位置

imgText = font.render(text, True, color)

screen.blit(imgText, (x, y))

# 按键

def press(keys, snack):

global score

# K_w 为 pygame.locals 中的常量

# keys[K_w] 返回 True or False

# 上移

if keys[K_w] or keys[K_UP]:

snack.toward(0, -1)

# 下移

elif keys[K_s] or keys[K_DOWN]:

snack.toward(0, 1)

# 左移

elif keys[K_a] or keys[K_LEFT]:

snack.toward(-1, 0)

# 右移

elif keys[K_d] or keys[K_RIGHT]:

snack.toward(1, 0)

# 重置游戏

elif keys[K_r]:

score = 0

main()

# 退出游戏

elif keys[K_ESCAPE]:

exit()

# 游戏初始化

def game_init():

# pygame 初始化

pygame.init()

# 设置游戏界面大小

screen = pygame.display.set_mode((BOARDWIDTH * 20, BOARDHEIGHT * 20))

# 设置游戏标题

pygame.display.set_caption(‘贪吃蛇游戏’)

# sound = pygame.mixer.Sound(AUDIONAME)

# channel = pygame.mixer.find_channel(True)

# channel.play(sound)

return screen

# 开始游戏

def game(screen):

snack = Snack()

food = Food()

# 设置中文字体和大小

font = pygame.font.SysFont(‘SimHei’, 20)

is_fail = 0

while True:

for event in pygame.event.get():

if event.type == QUIT:

exit()

# 填充屏幕

screen.fill((0, 0, 100))

init_board(screen=screen)

# 获得用户按键命令

keys = pygame.key.get_pressed()

press(keys, snack)

# 游戏失败打印提示

if is_fail:

font2 = pygame.font.Font(None, 40)

print_text(screen, font2, 400, 200, “GAME OVER”)

# 游戏主进程

if not is_fail:

enlarge = snack.eat_food(food)

food.update(screen, enlarge, snack)

snack.move(enlarge)

is_fail = game_over(snack=snack)

snack.draw(screen)

# 游戏刷新

pygame.display.update()

time.sleep(0.1)

# 主程序

def main():

screen = game_init()

game(screen)

if __name__ == ‘__main__’:

main()

程序运行效果

简单截图了一下

可以按住方向键移动蛇的运动方向

202042490007109.gif

更多有趣的经典小游戏实现专题,分享给大家:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

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

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

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


相关推荐

  • 热血传奇服务端源码(传奇类 手游源码)

    缘起因由在一个无所事事的周末下午,突然想起魔兽世界,官方的账号很久没有上了,里面的大小号现在连满级都不是。以前曾经搭过传奇和星际争霸战网的私服自娱自乐,也听说过魔兽世界有开源的服务端模拟,既然兴致来了就小小的研究一下。目前魔兽世界的私服比较流行的是MaNGOS和Trinity,二者都是模拟魔兽世界服务端。MaNGOS“号称”是一个研究型项目,目的是为了学习大规模的C++项目开发,有

    2022年4月16日
    119
  • cdn加速以及前后分离SpringBoot+Vue 配置https及SSL证书「建议收藏」

    cdn加速以及前后分离SpringBoot+Vue 配置https及SSL证书「建议收藏」配置方法同上篇文章一样CDN加速配置,阿里云cdn内配置好以后即可剩下把前端服务器nginx内的证书文件上传以及配置写好即可。后端服务器也同上配置证书下载上传服务器配置好nginx即可。如果都配置好以后,不可以访问时,注意查看前端请求接口是否为https方式。如果为http时,检查是否更新服务器成功,如果成功后还不可以正常访问时,前端修改代码如下:vue.config.js内添加下行代码。index.html下添加代码:https:true完毕!…

    2022年8月19日
    7
  • MongoDB和MySQL和Redis的区别

    MongoDB和MySQL和Redis的区别MongoDB和MySQL和Redis的区别MySQL1、在不同的引擎上有不同的存储方式。2、查询语句是使用传统的sql语句,拥有较为成熟的体系,成熟度很高。3、开源数据库的份额在不断增加,mysql的份额页在持续增长。4、缺点就是在海量数据处理的时候效率会显著变慢。MongoDBMongodb是非关系型数据库(nosql),属于文档型数据库。文档是mongoDB中数据的基本单元,类似关系数据库的行,多个键值对有序地放置在一起便是文档,语法有点类似javascript面向对象的查询语言,

    2022年6月26日
    26
  • 漏洞扫描 渗透测试_什么是渗透

    漏洞扫描 渗透测试_什么是渗透渗透测试阶段信息收集完成后,需根据所收集的信息,扫描目标站点可能存在的漏洞,包括SQL注入漏洞、跨站脚本漏洞、文件上传漏洞、文件包含漏洞及命令执行漏洞等,然后通过这些已知的漏洞,寻找目标站点存在攻击的入口。那么今天我们就介绍几款常用的WEB应用漏洞扫描工具。一、AWVSAcunetixWebVulnerabilityScanner(简称AWVS)是一款知名的网络漏洞扫描工具,它通过网络爬虫测试你的网站安全,检测流行安全漏洞。在漏洞扫描实战过程中,一般会首选AWVS,因为这个能扫描出来的漏洞很多,而

    2025年11月4日
    4
  • macbook双系统文件共享_华为双系统短信共享吗

    macbook双系统文件共享_华为双系统短信共享吗MacBook安装双系统多分区共享访问解决方案1.   需求在MacBook中安装Win7,mac双系统。磁盘分区为4个(A,B,C,D),其中A(300G),B(400G)存放个人和系统无关的东西并实现两个系统都能访问A、B;C(150G)安装Win764位系统;D(150G)安装MacOS系统。双系统之间互不影响,也就是说如果Win7

    2022年10月5日
    3
  • jupyter的代码能用pycharm运行吗_win10安装jupyter

    jupyter的代码能用pycharm运行吗_win10安装jupyter在Pycharm中安装及使用Jupyter(图文详解)文章目录在Pycharm中安装及使用Jupyter(图文详解)一、材料二、安装Jupyter三、配置Jupyter四、使用Jupyter1.使用Cell2.使用jupyterMarkdownPycharm更新了对Jupyter的功能支持,结合IntelliJ的自动补全代码,自动格式化代码,执行调试…

    2022年8月26日
    7

发表回复

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

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