python - 如何在pygame中插入url链接
问题描述
我可以在 Pygame 中添加链接吗?就像在 HTML 中一样;一旦它被点击,我们将被重定向到 URL。我有游戏“回合制战斗”-> https://www.pygame.org/project/5492/7939 我想在屏幕上的某处添加一个文本,并带有他们可以按下的链接。如果你想看代码你可以在创作者的 Github 页面上查看,它和我现在的游戏基本一样。-> https://github.com/russs123/Battle
解决方案
您所要做的就是检查鼠标按下事件是否发生在文本的矩形内。然后您可以使用webbrowser.open()
在浏览器中打开链接。
示例代码:
import pygame
import webbrowser
pygame.init()
screen = pygame.display.set_mode((1000, 800))
link_font = pygame.font.SysFont('Consolas', 50)
link_color = (0, 0, 0)
running = True
while running:
screen.fill((255, 255, 255))
rect = screen.blit(link_font.render("Sample Link", True, link_color), (50, 50))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
if rect.collidepoint(pos):
webbrowser.open(r"https://stackoverflow.com/")
if rect.collidepoint(pygame.mouse.get_pos()):
link_color = (70, 29, 219)
else:
link_color = (0, 0, 0)
pygame.display.update()
推荐阅读
- java - 是否可以通过改造在 listView 中获取 Double 值数组?
- python - 使用范围和列表方法构造列表
- flutter - Flutter 中的 setState() 方法直到 for 循环中的最后一次调用才更新视图
- django - 我想向 django html 中的按钮添加一个函数,这样当我单击该按钮时,它会将 +1 添加到现有数据
- c++ - C++中条件运算符的使用
- or-tools - VRP:可以检测具有空域的变量吗?
- javascript - JS浏览器游戏——避免初始化所有对象
- javascript - 如何在前端使角色有条件?
- javascript - 使用 jQuery 修改 DOM 元素后如何重新加载函数(tempus dominus)
- javascript - 在css中做一个下拉按钮