pygame学习教程(四)屏幕显示多个按钮

前一篇
说明我写这个系列是为了给初学者展示一些思路和技巧,很多代码不是最优的。如果有朋友对构架有不同看法,欢迎指正。
这里,继续上个例子展示一些python的技巧。
首先,我们修改Jbutton()类。需要涉及很多的向量计算,这里引入
DVerctor。需要将这个文件考到执行文件相同的目录,import。
DVerctor.py ,可以运行测试一下

################## http://www.pygame.org/wiki/2DVectorClass ##################
import operator
import math

class Vec2d(object):
    """2d vector class, supports vector and scalar operators,
       and also provides a bunch of high level functions
       """
    __slots__ = ['x', 'y']

    def __init__(self, x_or_pair, y = None):
        if y == None:
            self.x = x_or_pair[0]
            self.y = x_or_pair[1]
        else:
            self.x = x_or_pair
            self.y = y

    def __len__(self):
        return 2

    def __getitem__(self, key):
        if key == 0:
            return self.x
        elif key == 1:
            return self.y
        else:
            raise IndexError("Invalid subscript "+str(key)+" to Vec2d")

    def __setitem__(self, key, value):
        if key == 0:
            self.x = value
        elif key == 1:
            self.y = value
        else:
            raise IndexError("Invalid subscript "+str(key)+" to Vec2d")

    # String representaion (for debugging)
    def __repr__(self):
        return 'Vec2d(%s, %s)' % (self.x, self.y)

    # Comparison
    def __eq__(self, other):
        if hasattr(other, "__getitem__") and len(other) == 2:
            return self.x == other[0] and self.y == other[1]
        else:
            return False

    def __ne__(self, other):
        if hasattr(other, "__getitem__") and len(other) == 2:
            return self.x != other[0] or self.y != other[1]
        else:
            return True

    def __nonzero__(self):
        return bool(self.x or self.y)

    # Generic operator handlers
    def _o2(self, other, f):
        "Any two-operator operation where the left operand is a Vec2d"
        if isinstance(other, Vec2d):
            return Vec2d(f(self.x, other.x),
                         f(self.y, other.y))
        elif (hasattr(other, "__getitem__")):
            return Vec2d(f(self.x, other[0]),
                         f(self.y, other[1]))
        else:
            return Vec2d(f(self.x, other),
                         f(self.y, other))

    def _r_o2(self, other, f):
        "Any two-operator operation where the right operand is a Vec2d"
        if (hasattr(other, "__getitem__")):
            return Vec2d(f(other[0], self.x),
                         f(other[1], self.y))
        else:
            return Vec2d(f(other, self.x),
                         f(other, self.y))

    def _io(self, other, f):
        "inplace operator"
        if (hasattr(other, "__getitem__")):
            self.x = f(self.x, other[0])
            self.y = f(self.y, other[1])
        else:
            self.x = f(self.x, other)
            self.y = f(self.y, other)
        return self

    # Addition
    def __add__(self, other):
        if isinstance(other, Vec2d):
            return Vec2d(self.x + other.x, self.y + other.y)
        elif hasattr(other, "__getitem__"):
            return Vec2d(self.x + other[0], self.y + other[1])
        else:
            return Vec2d(self.x + other, self.y + other)
    __radd__ = __add__

    def __iadd__(self, other):
        if isinstance(other, Vec2d):
            self.x += other.x
            self.y += other.y
        elif hasattr(other, "__getitem__"):
            self.x += other[0]
            self.y += other[1]
        else:
            self.x += other
            self.y += other
        return self

    # Subtraction
    def __sub__(self, other):
        if isinstance(other, Vec2d):
            return Vec2d(self.x - other.x, self.y - other.y)
        elif (hasattr(other, "__getitem__")):
            return Vec2d(self.x - other[0], self.y - other[1])
        else:
            return Vec2d(self.x - other, self.y - other)
    def __rsub__(self, other):
        if isinstance(other, Vec2d):
            return Vec2d(
### Pygame 教程概述 Pygame 是一个用于创建视频游戏的 Python 库,它提供了丰富的功能来处理图形、声音和其他多媒体资源。以下是关于 Pygame 的详细教程,涵盖了安装过程、基础概念以及示例代码。 #### 安装 Pygame 要开始使用 Pygame,首先需要安装该库。可以使用 pip 工具轻松完成这一操作: ```bash pip install pygame ``` 这将下载并安装最新版本的 Pygame 到当前环境中[^1]。 #### 基础概念介绍 ##### 初始化模块 在编写任何 Pygame 程序之前,必须初始化所有必要的子模块。通常情况下只需要调用 `pygame.init()` 函数即可完成此工作: ```python import pygame pygame.init() ``` ##### 创建窗口 为了能够绘制图像或显示文字等内容,需先建立一个可视化的表面——即所谓的“屏幕”。下面这段简单的代码展示了如何设置宽度为800像素高600像素的游戏窗口: ```python screen = pygame.display.set_mode((800, 600)) ``` ##### 处理事件循环 事件处理是 Pygame 中的核心部分之一。程序会持续监听来自用户的输入(比如按下某个键),并通过遍历事件列表来进行响应。当检测到退出请求时,则终止应用程序运行: ```python for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() import sys sys.exit() ``` 以上代码片段实现了基本的关闭按钮功能[^3]。 ##### 显示图像与动画 除了静态图片外,还可以利用 Pygame 来制作动态效果。例如加载多张连续变化的画面作为角色的动作序列,并按照一定频率更新它们的位置以实现流畅过渡。更多细节可以在官方文档中找到进一步说明。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值