pygame 文字输入交互_如何在pygame中创建交互式对象?

该博客介绍了如何在pygame中创建交互式对象,特别是如何通过键盘控制选择器矩形来实现文字输入交互。通过创建不同选项的矩形并检测它们与选择器矩形的碰撞,实现了模拟器、测验和退出等操作。当按下回车键时,根据选择的矩形执行相应功能,例如打印提示信息。
摘要由CSDN通过智能技术生成

您可以使用pygame的colliderect检查冲突

首先,创建三个矩形,表示三个选项矩形:simulator_rect = pygame.Rect(600, 125, 30, 30)

quiz_rect = pygame.Rect(225, 125, 30, 30)

quit_rect = pygame.Rect(375, 425, 30, 30)

接下来,我们将创建一个表示蓝色选择器rect的rect:

^{pr2}$

现在你得到了只创建一次的矩形,而不是每次都创建的未命名矩形

现在,对于实际的碰撞检测:

^{3}$

最终代码:import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))

done = False

x = 30

y = 30

clock = pygame.time.Clock()

# RGB values for red

red = (255, 0 ,0)

# Your three button rects :

simulator_rect = pygame.Rect(225, 125, 30, 30)

quiz_rect = pygame.Rect(600, 125, 30, 30)

quit_rect = pygame.Rect(375, 425, 30, 30)

# These represent your three option rects

option_rects = [simulator_rect, quiz_rect, quit_rect]

# Your blue selector rect

selector_rect = pygame.Rect(50, 50, 60, 60)

# The 50, 50 xy coords are temporary

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

pressed = pygame.key.get_pressed()

if pressed[pygame.K_UP] and y > 0: y -= 5

if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5

if pressed[pygame.K_LEFT] and x > 0: x -= 5

if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

# Set the slector rect's coords to x/y

selector_rect.x, selector_rect.y = x, y

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

color = (0, 128, 255)

pygame.draw.rect(screen, color, selector_rect)

myfont = pygame.font.SysFont("monospace", 15)

label = myfont.render("Start the experiment simulator", 1, (255,255,255))

screen.blit(label, (100, 100))

label2 = myfont.render("Start the quiz", 1, (255,255,255))

screen.blit(label2, (550, 100))

label3 = myfont.render("Quit game", 1, (255,255,255))

screen.blit(label3, (350, 400))

# Use our created rects

pygame.draw.rect(screen, red, simulator_rect)

pygame.draw.rect(screen, red, quiz_rect)

pygame.draw.rect(screen, red, quit_rect)

# Check to see if the user presses the enter key

if pressed[pygame.K_RETURN]:

# Check to see if the selection rect

# collides with any other rect

for rect in option_rects:

# Add rects as needed

if selector_rect.colliderect(rect):

if rect == simulator_rect:

# Do simulations stuff!

print('Simulating!')

elif rect == quiz_rect:

# Do quizzing stuff!

print('Quizzing!')

elif rect == quit_rect:

# Quit!

done = True

pygame.display.flip()

clock.tick(60)

这确实给你的程序增加了一些复杂度,但至少这是一个坚如磐石的方法,你也可以添加一些特性,而且这将保持健壮。在

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值