小学生python游戏开发pygame5--title地图调用

  • 前言
  • 文件夹目录
    • pytmx模块安装
    • 实现效果
    • 代码实现

前言

文件夹目录

pytmx模块安装

实现效果

代码实现

import loggingimport pygame
from pygame.locals import *import pytmx
from pytmx import TiledImageLayer
from pytmx import TiledObjectGroup
from pytmx import TiledTileLayer
from pytmx.util_pygame import load_pygamelogger = logging.getLogger(__name__)def init_screen(width, height):""" Set the screen modeThis function is used to handle window resize events"""return pygame.display.set_mode((width, height), pygame.RESIZABLE)class TiledRenderer(object):"""Super simple way to render a tiled map"""def __init__(self, filename):tm = load_pygame(filename)# self.size will be the pixel size of the map# this value is used later to render the entire map to a pygame surfaceself.pixel_size = tm.width * tm.tilewidth, tm.height * tm.tileheightself.tmx_data = tmdef render_map(self, surface):""" Render our map to a pygame surfaceFeel free to use this as a starting point for your pygame app.This method expects that the surface passed is the same pixelsize as the map.Scrolling is a often requested feature, but pytmx is a maploader, not a renderer!  If you'd like to have a scrolling maprenderer, please see my pyscroll project."""# fill the background color of our render surfaceif self.tmx_data.background_color:surface.fill(pygame.Color(self.tmx_data.background_color))# iterate over all the visible layers, then draw themfor layer in self.tmx_data.visible_layers:# each layer can be handled differently by checking their typeif isinstance(layer, TiledTileLayer):self.render_tile_layer(surface, layer)elif isinstance(layer, TiledObjectGroup):self.render_object_layer(surface, layer)elif isinstance(layer, TiledImageLayer):self.render_image_layer(surface, layer)def render_tile_layer(self, surface, layer):""" Render all TiledTiles in this layer"""# deref these heavily used references for speedtw = self.tmx_data.tilewidthth = self.tmx_data.tileheightsurface_blit = surface.blit# iterate over the tiles in the layer, and blit themfor x, y, image in layer.tiles():surface_blit(image, (x * tw, y * th))def render_object_layer(self, surface, layer):""" Render all TiledObjects contained in this layer"""# deref these heavily used references for speeddraw_lines = pygame.draw.linessurface_blit = surface.blit# these colors are used to draw vector shapes,# like polygon and box shapesrect_color = (255, 0, 0)# iterate over all the objects in the layer# These may be Tiled shapes like circles or polygons, GID objects, or Tiled Objectsfor obj in layer:logger.info(obj)# objects with points are polygons or linesif obj.image:# some objects have an image; Tiled calls them "GID Objects"surface_blit(obj.image, (obj.x, obj.y))else:# use `apply_transformations` to get the points after rotationdraw_lines(surface, rect_color, obj.closed, obj.apply_transformations(), 3)def render_image_layer(self, surface, layer):if layer.image:surface.blit(layer.image, (0, 0))class SimpleTest(object):""" Basic app to display a rendered Tiled map"""def __init__(self, filename):self.renderer = Noneself.running = Falseself.dirty = Falseself.exit_status = 0self.load_map(filename)def load_map(self, filename):""" Create a renderer, load data, and print some debug info"""self.renderer = TiledRenderer(filename)logger.info("地图中的对象:")for obj in self.renderer.tmx_data.objects:logger.info(obj)for k, v in obj.properties.items():logger.info("%s\t%s", k, v)logger.info("GID(磁贴)属性:")for k, v in self.renderer.tmx_data.tile_properties.items():logger.info("%s\t%s", k, v)logger.info("碰撞体:")for k, v in self.renderer.tmx_data.get_tile_colliders():logger.info("%s\t%s", k, list(v))def draw(self, surface):""" Draw our map to some surface (probably the display)"""# first we make a temporary surface that will accommodate the entire# size of the map.# because this demo does not implement scrolling, we render the# entire map each frametemp = pygame.Surface(self.renderer.pixel_size)# render the map onto the temporary surfaceself.renderer.render_map(temp)# now resize the temporary surface to the size of the display# this will also 'blit' the temp surface to the displaypygame.transform.smoothscale(temp, surface.get_size(), surface)# display a bit of use info on the displayf = pygame.font.Font(pygame.font.get_default_font(), 20)i = f.render('press any key for next map or ESC to quit',1, (180, 180, 0))surface.blit(i, (0, 0))def handle_input(self):try:event = pygame.event.wait()if event.type == QUIT:self.exit_status = 0self.running = Falseelif event.type == KEYDOWN:if event.key == K_ESCAPE:self.exit_status = 0self.running = Falseelse:self.running = Falseelif event.type == VIDEORESIZE:init_screen(event.w, event.h)self.dirty = Trueexcept KeyboardInterrupt:self.exit_status = 0self.running = Falsedef run(self):""" This is our app main loop"""self.dirty = Trueself.running = Trueself.exit_status = 1while self.running:self.handle_input()# we don't want to constantly draw on the display, as that is way# inefficient.  so, this 'dirty' values is used.  If dirty is True,# then re-render the map, display it, then mark 'dirty' False.if self.dirty:self.draw(screen)self.dirty = Falsepygame.display.flip()return self.exit_statusif __name__ == '__main__':import os.pathimport globpygame.init()pygame.font.init()screen = init_screen(600, 600)pygame.display.set_caption('地图浏览器')logging.basicConfig(level=logging.DEBUG)logger.info(pytmx.__version__)  # '版本',# loop through a bunch of maps in the maps foldertry:SimpleTest('家.tmx').run()# for filename in glob.glob(os.path.join('data', '*.tmx')):#     print(filename)#     logger.info("Testing %s", filename)#     if not SimpleTest(filename).run():#         breakexcept:pygame.quit()raise

注:部分代码及资源来自网络,如有不当,请联系我删除,此处仅供大家学习参考


## 总结
python游戏开发,现从简单到稍微复杂些,已试过了pyzero,pygame,通过对比,pygame在处理图片上比pyzero更进一步,灵活性更大些,今天又试了pygame调用图块地图的功能,后期会解始arcade模块,感到比pygame又有一些优点。
## 源码获取
可**关注**博主后,*私聊博主*免费获取
需要技术指导,育娃新思考,企业软件合作等更多服务请联系博主今天是以此模板持续更新此育儿专栏的第 11 /50次。
可以**关注**我,**点赞**我、**评论**我、**收藏**我啦。

小学生python游戏开发pygame5--title地图调用相关推荐

  1. 小学生python游戏开发pygame--初始及基础知识

    #1024程序员节|用代码,改变世界# 小学生python游戏开发pygame1--基础知识 前言 知识点 1.python知识点 1.1 RGB 颜色表示 1.2 类 2.3 pygame.disp ...

  2. 小学生python游戏开发pygame--设置内容整理

    游戏开发,相关设置内容单独放在一个文件中 如长宽,大小,颜色等起名shezhi.py,如下: # _*_ coding: UTF-8 _*_ # 开发团队: 信息化未来 # 开发人员: Adminis ...

  3. 小学生python游戏编程arcade----excel调用

    小学生python游戏编程arcade----excel调用 前言 小学生python游戏编程arcade----excel调用 1.excel文件 1.1 excel表头 1.2 excel文件 1 ...

  4. 小学生python游戏编程arcade----基本知识3

    小学生python游戏编程arcade----基本知识3 前言 多摄象头显得分,title地图加载,精灵分层管理,移动精灵 1.多摄象头显得分 1.1得分 1.2 两个摄象机的绘制 1.3 效果图 1 ...

  5. 小学生python游戏编程arcade----坦克大战2

    小学生python游戏编程arcade----坦克大战2 前言 多摄象头显得分,title地图加载,精灵分层管理,移动精灵 1.提示框制作 1.1养眼绿色 1.2 画距形提示框 1.3 效果图 1.4 ...

  6. 小学生python游戏编程4----拼图游戏

    小学生python游戏编程4----拼图游戏 主要设计 应用知识点 1.python知识点 1.1 函数定义与使用 1.2 random 2.pygamezero知识点 2.1 基本框架,取上节中讲到 ...

  7. python游戏开发的五个案例分享

    本文给大家分享了作者整理的五个python游戏开发的案例,通过具体设计思路,代码等方面详细了解python游戏开发的过程,非常的详细,希望大家能够喜欢 一.序列应用--猜单词游戏 1. 游戏介绍 猜单 ...

  8. 小学生python游戏编程arcade----坦克大战4

    小学生python游戏编程arcade----坦克大战4 前言 坦克大战4 1.1 每单元英语单词学完升级效果 1.2 单词调用及敌坦克随机问题 1.3 效果图 1.4 代码实现 源码获取 前言 接上 ...

  9. 小学生python游戏编程2----飞机大战1

    小学生python游戏编程2----飞机大战1 前言 主要设计 1.界面设计 2.动态背景 3.记分的实现 4.射击游戏功能的实现 5.声音的实现 应用知识点 1.python知识点 1.1 角色创建 ...

最新文章

  1. 通用窗口类 Inventory Pro 2.1.2 Demo1(下)
  2. 2016c语言模拟试卷一,2016年9月计算机二级C语言考试预测试题及答案(4)
  3. Linux web服务器初始化设置
  4. 带你了解FPGA(2)--逻辑设计基础
  5. mysql5.7.29下载与安装并设置密码
  6. 关闭主窗口,启动另一个窗口
  7. 第一次作业_U201410737 _万学远
  8. t3-财务通计算机名称,用友T3用友通财务软件操作方法
  9. win10打开计算机黑屏怎么办,win10系统重启黑屏怎么办
  10. 老徐WEB:CSS伪类和伪元素详解
  11. 计算机应用研究中的文章见刊后,什么时候能在知网中查询到,论文网络首发后会被收录吗...
  12. 双向链表的插入及删除图解
  13. [C++] 栈的压入、弹出序列
  14. 北航计算机学院教授马帅,北航离散数学大一课件(马帅)指南.pdf
  15. fw_setenv的配置及使用
  16. HTML5中新增的元素有哪些
  17. 六、Quartz-配置详解
  18. 【MATLAB】用地图表白:绘制Bonne投影下的世界地图
  19. 直播数据采集的10个经典方法
  20. ES地理范围查询第一讲:Java操作地理位置信息(geo_point)

热门文章

  1. HAL库-us级延时函数实现
  2. UE5 tiles 材质缩放平铺
  3. 免费顶级域名.OVH注册申请全过程附成功注册小技
  4. 开会没带纸和笔?按下手机这个按钮,一键完成会议纪要
  5. 华为云视频点播服务全面开放公测!限量发放VIP免费名额中...
  6. 开源企业内部文档共享平台(mm-wiki)
  7. 挺带劲!这款开源数据库迁移工具超牛逼
  8. 文字生成视频,清华出品
  9. 利用matlab批量修改文件名称或后缀
  10. PHP开发阿里云短信服务接口