gpt4 book ai didi

python - 如何更新我的矩形的位置坐标?

转载 作者:行者123 更新时间:2023-12-04 08:37:28 24 4
gpt4 key购买 nike

我正在创建一个存储卡游戏,但很难更新每个盒子的 rect 起始位置。第一 for循环加载每个图像,第二个 get 是每个图像的起始位置。当我进行碰撞测试时,它只回答 <0,125,0,175> 因为我的矩形位置没有更新。我该如何更新?

import pygame, sys
from pygame.locals import *

screen_height = 800
screen_width = 800
card_x_size = 125
card_y_size = 175
marginx = 45
marginy = 25

class Box():
def __init__(self,image):
self.image = image
self.rect = image.get_rect()

def draw(self,screen):
screen.blit(self.image, self.rect)

def play_game():
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))

back_images = ['back.jpg']*16
back_image_list = []
for back_image in back_images:
back_pic = pygame.image.load(back_image)
back_pic = pygame.transform.scale(back_pic, (card_x_size,card_y_size))
back_image_list.append(back_pic)
rect = back_pic.get_rect()

boxes = [Box(img) for img in back_image_list]


for j, box in enumerate(boxes):
pos_x = marginx + j % 4 * available_spacex
pos_y = marginy + j // 4 * available_spacey
box.rect.topleft = (pos_x, pos_y)
print(pos_x,pos_y)


while True:
mouse_clicked = False
clicked_card = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mouse_clicked = True
print(mousex, mousey)
if rect.collidepoint(mousex,mousey):
clicked_card = True
print("hit")

for b in boxes:
b.draw(screen)

pygame.display.update()

play_game()

最佳答案

您必须评估鼠标单击是否位于 box 之一上。对象:

for box in boxes:
if box.rect.collidepoint(mousex, mousey):
clicked_card = True
print("hit")

功能 play_game :
def play_game():
# [...]

while True:
mouse_clicked = False
clicked_card = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouse_clicked = True
print(mousex, mousey)
for box in boxes:
if box.rect.collidepoint(mousex, mousey):
clicked_card = True
print("hit")

for b in boxes:
b.draw(screen)

pygame.display.update()

关于python - 如何更新我的矩形的位置坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64732366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com