博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
pygame 笔记-4 代码封装&发射子弹
阅读量:4703 次
发布时间:2019-06-10

本文共 4575 字,大约阅读时间需要 15 分钟。

,随着游戏的内容越来越复杂,有必要把代码优化一下,可以参考OOP的做法,把人物类抽象出来,弄成一个单独的类,这们便于代码维护,同时我们给小人儿,加个发射子弹的功能,代码如下:(看上去略长,但是绝大多数,都是上节的代码)

import pygameimport ospygame.init()WIN_WIDTH, WIN_HEIGHT = 500, 500win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))  # 画布窗口的大小pygame.display.set_caption("first game")  # 窗口标题img_base_path = os.getcwd() + '/img/'bg = pygame.image.load(img_base_path + 'bg.jpg')char = pygame.image.load(img_base_path + 'standing.png')bullet_right = pygame.image.load(img_base_path + 'r_bullet.png')bullet_left = pygame.image.load(img_base_path + 'l_bullet.png')clock = pygame.time.Clock()# 将主角人物抽象成1个类class Player(object):    # 向右走的图片数组    walkRight = [pygame.image.load(img_base_path + 'actor/R1.png'),                 pygame.image.load(img_base_path + 'actor/R2.png'),                 pygame.image.load(img_base_path + 'actor/R3.png'),                 pygame.image.load(img_base_path + 'actor/R4.png'),                 pygame.image.load(img_base_path + 'actor/R5.png'),                 pygame.image.load(img_base_path + 'actor/R6.png'),                 pygame.image.load(img_base_path + 'actor/R7.png'),                 pygame.image.load(img_base_path + 'actor/R8.png'),                 pygame.image.load(img_base_path + 'actor/R9.png')]    # 向左走的图片数组    walkLeft = [pygame.image.load(img_base_path + 'actor/L1.png'),                pygame.image.load(img_base_path + 'actor/L2.png'),                pygame.image.load(img_base_path + 'actor/L3.png'),                pygame.image.load(img_base_path + 'actor/L4.png'),                pygame.image.load(img_base_path + 'actor/L5.png'),                pygame.image.load(img_base_path + 'actor/L6.png'),                pygame.image.load(img_base_path + 'actor/L7.png'),                pygame.image.load(img_base_path + 'actor/L8.png'),                pygame.image.load(img_base_path + 'actor/L9.png')]    def __init__(self, x, y, width, height):        self.x = x        self.y = y        self.width = width        self.height = height        self.speed = 5        self.left = False        self.right = True        self.isJump = False        self.walkCount = 0        self.t = 10        self.speed = 5    def draw(self, win):        if self.walkCount >= 27:            self.walkCount = 0        if self.left:            win.blit(self.walkLeft[self.walkCount // 3], (self.x, self.y))            self.walkCount += 1        elif self.right:            win.blit(self.walkRight[self.walkCount // 3], (self.x, self.y))            self.walkCount += 1        else:            win.blit(char, (self.x, self.y))# 子弹类class Bullet(object):    global man    def __init__(self, x, y, radius, color, facing):        self.x = x        self.y = y        self.radius = radius        self.color = color        self.facing = facing        self.vel = 8 * facing    def draw(self, win):        # 根据人物的朝向,要切换不同的子弹图片        if man.left:            win.blit(bullet_left, (self.x, self.y))        else:            win.blit(bullet_right, (self.x, self.y))def redraw_game_window():    win.blit(bg, (0, 0))    man.draw(win)    for bullet in bullets:        bullet.draw(win)    pygame.display.update()# mainman = Player(200, 410, 64, 64)run = Truebullets = []while run:    clock.tick(27)    for event in pygame.event.get():        if event.type == pygame.QUIT:            run = False    for bullet in bullets:        if WIN_WIDTH > bullet.x > 0:            bullet.x += bullet.vel        else:            bullets.pop(bullets.index(bullet))    keys = pygame.key.get_pressed()    if keys[pygame.K_SPACE]:        if man.left:            facing = -1        else:            facing = 1        if len(bullets) < 5:            # 子弹不足5个时,自动填充            bullets.append(Bullet(round(man.x + man.width // 2), round(man.y + man.height // 2), 6, (0, 0, 0), facing))    if keys[pygame.K_LEFT] and man.x > 0:        man.x -= man.speed        man.left = True        man.right = False    elif keys[pygame.K_RIGHT] and man.x < win.get_size()[0] - man.width:        man.x += man.speed        man.left = False        man.right = True    else:        man.walkCount = 0    # 方向箭头响应    if not man.isJump:        if keys[pygame.K_UP]:            man.isJump = True            man.walkCount = 0    else:        if man.t >= -10:            a = 1  # 前半段减速上跳            if man.t < 0:                a = -1  # 后半段加速下落            man.y -= 0.5 * a * (man.t ** 2)  # 匀加速直线运动的位移公式            man.t -= 1        else:            man.isJump = False            man.t = 10    redraw_game_window()pygame.quit()

效果:

转载于:https://www.cnblogs.com/yjmyzz/p/pygame-tutorial-4-oop-optimize-and-bullet-emit.html

你可能感兴趣的文章
C#dataset中数据导出到excel
查看>>
node和yarn
查看>>
Java连接MySQL数据库——含详细步骤和代码
查看>>
fast-json 内幕
查看>>
固定导航栏demo
查看>>
前端通信、跨域
查看>>
MD5加密
查看>>
如何向ASP.NET Web 服务器控件添加客户端脚本事件
查看>>
quick check
查看>>
陶瓷天线
查看>>
Android 环信聊天头像昵称显示解决方案
查看>>
Android 快速开发系列 ORMLite 框架最佳实践
查看>>
设计模式 单例模式
查看>>
springmvc返回值、数据写到页面、表单提交、ajax、重定向
查看>>
JQuery插件使用小结
查看>>
C#:String.Format数字格式化输出
查看>>
ubuntu下安装pdo和pdo_mysql扩展
查看>>
AngularJS 出现 Uncaught Error: [$injector:modulerr] 的解决办法
查看>>
JavaScript实现Apache .htaccess 转化nginx生成器工具-toolfk程序员工具网
查看>>
Linux 下安装nginx的总结 (之前写的有问题))
查看>>