Python 在Pygame中单击堆叠图像时出错
我做了一些代码,点击并拖动图像到堆栈的某个点。它在最初的几次点击中工作得很好,但当我把它放在同一个地方好几次时,它突然变得不可接近。我如何修复它,如果你还好,你能让它更紧凑吗Python 在Pygame中单击堆叠图像时出错,python,pygame,Python,Pygame,我做了一些代码,点击并拖动图像到堆栈的某个点。它在最初的几次点击中工作得很好,但当我把它放在同一个地方好几次时,它突然变得不可接近。我如何修复它,如果你还好,你能让它更紧凑吗 import pygame from pygame import * import sys import os pygame.init() s_width = 640 s_height = 480 screen = pygame.display.set_mode((s_width, s_height)) pygame.
import pygame
from pygame import *
import sys
import os
pygame.init()
s_width = 640
s_height = 480
screen = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption("TITLE")
bigfont = pygame.font.SysFont(None, 50)
smallfont = pygame.font.SysFont(None, 25)
title = bigfont.render("TITLE", True, (0,0,0))
current_path = os.path.dirname(__file__)
img_path = os.path.join(current_path, "images")
img_list = []
place_list = []
temp = []
class Img_Set:
def __init__(self, path, x_pos, y_pos):
self.image = pygame.image.load(path)
self.x_pos = x_pos
self.y_pos = y_pos
self.rect = self.image.get_rect()
self.rect.left = self.x_pos
self.rect.top = self.y_pos
img_list.append(self)
self.click = False
def offset(self):
self.offset_len_x = event.pos[0] - self.x_pos
self.offset_len_y = event.pos[1] - self.y_pos
def drag(self):
self.x_pos = event.pos[0] - self.offset_len_x
self.y_pos = event.pos[1] - self.offset_len_y
self.rect.left = self.x_pos
self.rect.top = self.y_pos
class Place_Set:
def __init__(self, path, x_pos, y_pos):
self.image = pygame.image.load(path)
self.x_pos = x_pos
self.y_pos = y_pos
self.rect = self.image.get_rect()
self.rect.left = self.x_pos
self.rect.top = self.y_pos
place_list.append(self)
self.click = False
img1 = Img_Set("images/80x80_blueball.png", s_width/3, s_height/3)
img2 = Place_Set("images/80x80_ball.png", s_width/2, s_height/3)
img3 = Place_Set("images/80x80_greenball.png", s_width/3*2, s_height/3)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
for x in img_list:
if x.rect.collidepoint(event.pos):
temp.append(x)
if len(temp) > 0:
temp[-1].offset()
temp[-1].click = True
img_list.remove(temp[-1])
img_list.append(temp[-1])
temp = []
elif event.type == MOUSEMOTION:
for x in img_list:
if x.click:
x.drag()
elif event.type == MOUSEBUTTONUP:
for x in img_list:
for y in place_list:
if x.rect.colliderect(y.rect):
x.x_pos = y.x_pos
x.y_pos = y.y_pos
for x in img_list:
x.click = False
screen.fill((255, 255, 255))
for x in place_list:
screen.blit(x.image, (x.x_pos, x.y_pos))
for x in img_list:
screen.blit(x.image, (x.x_pos, x.y_pos))
pygame.display.update()
下面是运行gif的代码
松开鼠标按钮时,您没有更新
rect
属性。拖动图像时,这会导致x
、y
和rect
属性之间的错误偏移:
为True时:
对于pygame.event.get()中的事件:
# [...]
elif event.type==MOUSEBUTTONUP:
对于img_列表中的x:
对于y就地_列表:
如果x.rect.collide rect(y.rect):
x、 x_位置=y.x_位置
x、 y_pos=y.y_pos
x、 rect.left=y.x_pos#谢谢,所以忘记rect属性只是个错误+不知道rect.x,rect.y的用法。我会试着把它们放进去!