Python 如何更新我的矩形的位置坐标?
我正在创建一个记忆卡游戏,但很难更新每个盒子的矩形起始位置。第一个Python 如何更新我的矩形的位置坐标?,python,pygame,rect,Python,Pygame,Rect,我正在创建一个记忆卡游戏,但很难更新每个盒子的矩形起始位置。第一个for循环加载每个图像,第二个get是每个图像的起始位置。当我做碰撞测试时,它只会回答,因为我的直肠位置没有更新。我如何更新这个 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 cl
for
循环加载每个图像,第二个get是每个图像的起始位置。当我做碰撞测试时,它只会回答,因为我的直肠位置没有更新。我如何更新这个
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()
您必须评估鼠标单击是否位于
框中的一个对象上:
对于框中框:
if box.rect.collidepoint(mousex,mousey):
单击\u卡=真
打印(“点击”)
功能玩游戏
:
def play_game():
# [...]
尽管如此:
鼠标单击=错误
单击\u卡=错误
对于pygame.event.get()中的事件:
如果event.type==退出:
pygame.quit()
sys.exit()
elif event.type==MOUSEMOTION:
mousex,mousey=event.pos
elif event.type==MOUSEBUTTONUP:
mousex,mousey=event.pos
鼠标单击=真
打印(mousex,mousey)
对于盒子中的盒子:
if box.rect.collidepoint(mousex,mousey):
单击\u卡=真
打印(“点击”)
对于盒子中的b:
b、 绘图(屏幕)
pygame.display.update()
我想我的问题是如何将其放入第一个循环中?第一个循环遍历我的字符串列表元素,第二个循环遍历int以获得位置我想我只需要更新rect位置,这样当我调用冲突测试时,它就会按照我想要的方式运行。只是不确定如何从box.rect.topleft
获取位置以更新到rect请提供一个。您当前的代码包含许多未定义的变量,并且不包含您在问题文本中提到的print(rect)
语句。@代码学徒感谢您指出,我已经更新了Hey@rabbi76是的,我已经尝试过了,它现在正在更新rect位置(谢谢!)但现在屏幕上的绘图不正确,碰撞测试也不起作用。谢谢你回答了我的主要问题question@doulikepeaches所以你做错了。当然,你必须事先设定好位置。您必须在第二次循环后执行此代码。