使用 pygame 单击按钮时启动事件

2024-03-17

大家好,我是 pygame 的新手。我开发了一个简单的游戏,其中球相互弹跳。效果很好。

我添加了一个带有按钮的用户界面,其中包含以下选项new game,loadgame,options.

我需要的是,当用户点击new game button他必须看到球弹跳。我的代码是

import pygame
import math
from itertools import cycle

def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
return [ u[i]-v[i] for i in range(len(u)) ]    

def dot(u, v):
return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
vmag = magnitude(v)
return [ v[i]/vmag  for i in range(len(v)) ]

screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()  



class Ball(object):
def __init__(self, path):
    self.x, self.y = (0, 0)
    self.img = pygame.image.load('ball.jpg')
    self.speed = 2.5
    self.color = (200, 200, 200)
    self.path = cycle(path)
    self.set_target(next(self.path))
    self.sound = pygame.mixer.music.load('yeah.mp3')


@property
def pos(self):
    return self.x, self.y

# for drawing, we need the position as tuple of ints
# so lets create a helper property
@property
def int_pos(self):
    return map(int, self.pos)

@property
def target(self):
    return self.t_x, self.t_y

@property
def int_target(self):
    return map(int, self.target)   

def next_target(self):
    self.set_target(self.pos)
    self.set_target(next(self.path))

def set_target(self, pos):
    self.t_x, self.t_y = pos

def update(self):
    # if we won't move, don't calculate new vectors
    if self.int_pos == self.int_target:
        return self.next_target()

    target_vector = sub(self.target, self.pos) 

    # a threshold to stop moving if the distance is to small.
    # it prevents a 'flickering' between two points
    if magnitude(target_vector) < 2: 
        return self.next_target()

    # apply the balls's speed to the vector
    move_vector = [c * self.speed for c in normalize(target_vector)]

    # update position
    self.x, self.y = add(self.pos, move_vector)

def draw(self):
    screen.blit(self.img, self.int_pos)
    pygame.mixer.music.play()

class Option:


hovered = False

def __init__(self, text, pos):
    self.text = text
    self.pos = pos
    self.set_rect()
    self.draw()

def draw(self):
    self.set_rend()
    screen.blit(self.rend, self.rect)

def set_rend(self):
    self.rend = menu_font.render(self.text, True, self.get_color())

def get_color(self):
    if self.hovered:
        return (255, 255, 255)
    else:
        return (100, 100, 100)

def set_rect(self):
    self.set_rend()
    self.rect = self.rend.get_rect()
    self.rect.topleft = self.pos

pygame.init()
quit = False
path = [(26, 43),(105, 110),(45, 225),(145, 295),(266, 211),(178, 134),(250,5)(147,12)] 

path2 = [(26, 43),(105, 10),(45, 125),(150, 134),(150, 26),(107, 12)]


ball = Ball(path)

ball.speed = 1.9

ball2 = Ball(path2)

ball2.color = (200, 200, 0)

balls = [ball, ball2]


screen = pygame.display.set_mode((480, 320))

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

options = [Option("NEW GAME", (140, 105)), Option("LOAD GAME", (135, 155)),
       Option("OPTIONS", (145, 205))]

while not quit:

pygame.event.pump()
screen.fill((0, 0, 0))
for option in options:
    if option.rect.collidepoint(pygame.mouse.get_pos()):
        option.hovered = True
    else:
        option.hovered = False
    option.draw()
pygame.display.update()

quit = pygame.event.get(pygame.QUIT)
pygame.event.poll()

map(Ball.update, balls)

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

map(Ball.draw, balls)

pygame.display.flip()
clock.tick(60)

当我尝试这段代码时,球弹跳和起始用户界面工作正常,但当我单击新按钮图标时,它没有显示任何内容。

我需要的是当用户点击时new game按钮它必须重定向到球弹跳屏幕。

我已经尝试过pygame.mouse.get_pressed但这并没有帮助我。

希望你们能帮助我。

提前感谢


所以你的问题是,首先你总是画球,其次你不检查鼠标点击。进行此检查的一个简单方法是调用pygame.event.get([pygame.MOUSEBUTTONDOWN])就在您检查鼠标位置是否位于选项之一上方的位置。如果它返回的内容不是None停止显示选项并开始显示球。

所以你会做类似的事情: 导入pygame 导入数学 来自 itertools 导入周期

OPTIONS = 0
BALLS = 1

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]    

def dot(u, v):
    return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()  



class Ball(object):
    def __init__(self, path):
        self.x, self.y = (0, 0)
        self.img = pygame.image.load('/home/wastl/Documents/DSC_0051.JPG')
        self.speed = 2.5
        self.color = (200, 200, 200)
        self.path = cycle(path)
        self.set_target(next(self.path))
        #self.sound = pygame.mixer.music.load('yeah.mp3')


    @property
    def pos(self):
        return self.x, self.y

# for drawing, we need the position as tuple of ints
# so lets create a helper property
    @property
    def int_pos(self):
        return map(int, self.pos)

    @property
    def target(self):
        return self.t_x, self.t_y

    @property
    def int_target(self):
        return map(int, self.target)   

    def next_target(self):
        self.set_target(self.pos)
        self.set_target(next(self.path))

    def set_target(self, pos):
        self.t_x, self.t_y = pos

    def update(self):
    # if we won't move, don't calculate new vectors
        if self.int_pos == self.int_target:
            return self.next_target()

        target_vector = sub(self.target, self.pos) 

    # a threshold to stop moving if the distance is to small.
    # it prevents a 'flickering' between two points
        if magnitude(target_vector) < 2: 
            return self.next_target()

    # apply the balls's speed to the vector
        move_vector = [c * self.speed for c in normalize(target_vector)]

    # update position
        self.x, self.y = add(self.pos, move_vector)

    def draw(self):
        screen.blit(self.img, self.int_pos)
        #pygame.mixer.music.play()

class Option:



    def __init__(self, text, pos):
        self.hovered = False
        self.text = text
        self.pos = pos
        self.set_rect()
        self.draw()

    def draw(self):
        self.set_rend()
        screen.blit(self.rend, self.rect)

    def set_rend(self):
        self.rend = menu_font.render(self.text, True, self.get_color())

    def get_color(self):
        if self.hovered:
            return (255, 255, 255)
        else:
            return (100, 100, 100)

    def set_rect(self):
        self.set_rend()
        self.rect = self.rend.get_rect()
        self.rect.topleft = self.pos

pygame.init()
quit = False
path = [(26, 43),(105, 110),(45, 225),(145, 295),(266, 211),(178, 134),(250,5),(147,12)] 

path2 = [(26, 43),(105, 10),(45, 125),(150, 134),(150, 26),(107, 12)]


ball = Ball(path)

ball.speed = 1.9

ball2 = Ball(path2)

ball2.color = (200, 200, 0)

balls = [ball, ball2]


screen = pygame.display.set_mode((480, 320))

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

options = [Option("NEW GAME", (140, 105)), Option("LOAD GAME", (135, 155)),
       Option("OPTIONS", (145, 205))]

STATE = OPTIONS

while not quit:

    pygame.event.pump()
    screen.fill((0, 0, 0))

    if STATE == OPTIONS:

        for option in options:
            if option.rect.collidepoint(pygame.mouse.get_pos()):
                option.hovered = True
                if pygame.event.get([pygame.MOUSEBUTTONDOWN]) and option.text == "NEW GAME":
                    STATE = BALLS
            else:
                option.hovered = False
            option.draw()
            pygame.display.update()

    elif STATE == BALLS:
        map(Ball.update, balls)

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

        map(Ball.draw, balls)

        pygame.display.flip()


    quit = pygame.event.get(pygame.QUIT)
    pygame.event.poll()

    clock.tick(60)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pygame 单击按钮时启动事件 的相关文章

随机推荐

  • Apache JMeter 的 Cookie 管理器未将 cookie 添加到 POST 请求

    我制定了非常简单的测试计划 登录 POST 返回会话cookie 获取状态 GET 返回用户状态 创建资源 POST 为资源提供 JSON 正文 所以我的 测试计划 如下所示 Test Plan Thread Group HTTP 请求默认
  • $_SESSION 设置为有效登录后 isset() 不起作用

    我有这个 loginform php 和这部分代码 这是从带有登录表单的 index php 调用的 include config php if isset POST submit username POST username passwo
  • UIViewControllerHierarchyInconsistency 仅在 iOS 8 和 Xcode 6 中导致应用程序崩溃

    我有一个在 iOS 7 和 Xcode 5 中运行良好的应用程序 当我将其更新到 iOS 8 和 Xcode 6 时 当点击文本字段时应用程序尝试在视图中向上滑动 UIDatePicker 时 它会崩溃 我正在使用故事板 有人知道为什么吗
  • C++ 中的等效 LinkedHashmap?

    我有一个 Java 程序 我想将其转换为 C 所以 有一个LinkedhashmapJava代码中使用的数据结构 我想将其转换为C 是否有等效的数据类型LinkedHashmap in C 我尝试使用std unordered map但是
  • 使用 NumPy reduceat 计算基于组的平均值

    import numpy as np import pandas as pd dummies np array pd get dummies list abdccadab categorical IV groupIDs np array 1
  • Protractor 和 Cucumber:使用 async/await 函数超时

    我正在使用 Angular 5 Protractor 和 Cucumber 进行 e2e 和 bdd 测试 当我在终端上运行时ng e2e我收到以下错误 当我打开页面 e2e steps home steps ts 15 错误 函数超时 确
  • 带 SwiftUI 的旋钮

    因此 我尝试使用旋钮复制正常的 SwiftUI 滑块功能 我已经对 UI 进行了编码 并且当前已连接到标准 SwiftUI 滑块以便旋转它 现在我需要添加其余的滑块功能 即 value range stride 和触摸功能 即上下左右拖动时
  • 作为安装过程的一部分,如何让 WiX 调用 .NET 程序集中的方法?

    我正在迁移一些现有产品以使用 WiX 3 5 我正在使用 Votive VS 集成 我正在安装的一些项目需要向第三方框架注册 要求是我必须在第三方 NET 程序集中调用 Register 方法来通知它我正在安装的项目是否存在 它需要一个 C
  • 如何在 Chapel 中附加稀疏域

    我正在使用读取 CSV 的循环填充 Chapel 中的稀疏数组 我想知道最好的模式是什么 var dnsDom 1 n dims 1 n dims var spsDom sparse subdomain dnsDom for line in
  • Tomcat 应用程序没有响应且没有日志

    我已经配置apache将请求转发到tomcat 以下是我的配置
  • VBA - 如何将 Excel 中的行从一个工作簿复制到另一个工作簿?

    尽管我浏览了许多与我的问题相同的帖子 但没有一个答案满足我的需求 如果您能给我链接 我很乐意阅读 我有一本带有工作表的工作簿 为简单起见 假设我的工作簿有一个工作表 在我的工作表 Sheet1 中 单元格 A1 到 A4 中有数据 我想要我
  • 无效的工会成员

    Visual Studio 中有没有一种方法可以处理非平凡的联合 以下代码运行良好g std c 11但 VS 抱怨 无效的联合成员 类 Foo 具有不允许的成员函数 代码如下 struct Foo int value Foo int in
  • 无法从 NSString 转换为 NSDate

    我无法将 NSString 转换为 NSDate 这是代码 NSDate stringToNSDate NSString dateString NSDateFormatter setDefaultFormatterBehavior NSDa
  • 将精灵旋转到鼠标位置

    我一直在使用 SFML 1 6 库 我想知道 如何旋转精灵 使其始终转向鼠标在屏幕上的位置 Thanks SFML具体代码优先 如果你有精灵的位置 S Sx Sy 和光标的位置 C Cx Cy You can calculate the a
  • mySQL 查找重复项并删除它们

    我想知道是否有一种方法可以通过一个查询来完成此操作 似乎当我最初用虚拟数据填充数据库以处理 10k 条记录时 在混乱的某个地方 所有脚本转储了额外的 1 044 行 其中行是重复的 我用以下方法确定了这一点 SELECT x ID x fi
  • Win10 64位上CUDA 12的PyTorch安装

    我需要在我的 PC 上安装 PyTorch 其 CUDA 版本 12 0 pytorch 2 的表 https i stack imgur com X13oS png in In 火炬网站 https pytorch org get sta
  • 命令源禁用和启用

    我阅读了有关 WPF 命令的所有内容 并且了解 GoF 命令模式 但仍然认为 我对这个过程有一个问题 命令目标 例如文本框 如何告诉命令源 例如按钮 它有更改状态 例如 插入文本框中的某些文本 以便源可以禁用或启用自身或执行其希望执行的任何
  • 使用 Java 和观察者模式使用 Jersey 的 RESTful Web 服务

    我正在尝试为学校项目实现一个 n 层架构应用程序 客户端和服务器之间的通信是通过 RESTful Web 服务完成的 我用了Jersey来实现这一点Java 我唯一的问题是 如何register服务器上的客户端接收更改通知 就像通常使用观察
  • Ruby on Rails:=> 符号是什么意思?

    我正在努力学习 Head First Rails 并且我不断看到 gt 它在路线中 map connect marmots new controller gt marmots action gt new 它在渲染部分 render part
  • 使用 pygame 单击按钮时启动事件

    大家好 我是 pygame 的新手 我开发了一个简单的游戏 其中球相互弹跳 效果很好 我添加了一个带有按钮的用户界面 其中包含以下选项new game loadgame options 我需要的是 当用户点击new game button他