python pygame - how to create a drag and drop with multiple images?

2024/11/16 4:33:08

So I've been trying to create a jigsaw puzzle using pygame in python.The only problem is that I'm having trouble creating the board with multiple images that i can drag along the screen (no need to connect the images like a puzzle what so ever just a simple drag and drop). I'm loading my images from a local folder on my computer. Can someone please help me?

This is what i have tried so far but the images start at the same postion and pygame recognize them all as one image

import socket
import os
import shutil
import pygame
from pygame.locals import*def dragdrop(path):dirs = os.listdir(path)def load_image(name, colorkey=None):fullname=os.path.join("data", name)try:image=pygame.image.load(fullname)except pygame.error, message:print "Impossible de charger l'image:",nameraise SystemExit, messageimage = image.convert()if colorkey is not None:if colorkey is -1:colorkey = image.get_at((0, 0))image.set_colorkey(colorkey, RLEACCEL)return image, image.get_rect()class Ichrom(pygame.sprite.Sprite):def __init__(self,image,initpos):pygame.sprite.Sprite.__init__(self)self.pos = initposself.image, self.rect=imageself.button=(0,0,0)#mouse buttons not pressedself.selected = 0self.mouseover=Falseself.focused=Falseprint "init chrom at ",self.posdef rollover(self):"""Test if the mouse fly over the chromosome self.mouseover==True if mouse flying over the chrom,False if not"""mpos=pygame.mouse.get_pos()#mouseposition#test if mouse roll over the spriteif self.rect.collidepoint(mpos):self.mouseover=Trueelse:self.mouseover=Falsedef update(self):self.button=pygame.mouse.get_pressed()mpos = pygame.mouse.get_pos()self.selected=self.rect.collidepoint(mpos)#the mouse flies over a chromosomeif (self.mouseover):#print "mouse pos:",mposif self.button==(1,0,0):     # )  pos = pygame.mouse.get_pos()self.rect.midtop = posdef main():pygame.init()screen = pygame.display.set_mode((1000,1000))pygame.display.set_caption("Karyotyper")pygame.mouse.set_visible(True)background = pygame.Surface(screen.get_size())background = background.convert()background.fill((0, 0, 0))screen.blit(background,(0, 0))pygame.display.flip()"""i1=load_image('C:/Users/Yonatan/Desktop/House.png', -1)i2=load_image('C:/Users/Yonatan/Desktop/US.jpeg', -1)i3=load_image('C:\Users\Yonatan\Desktop\imgres.jpg', -1)fuck= [i1, i2, i3]"""img=[]count=0for i in dirs:spr = Ichrom(load_image(path + "/" +i,-1),(count,count))count = count+30img.append(spr)allsprites = pygame.sprite.RenderPlain((fck))clock = pygame.time.Clock()while 1:clock.tick(60)for event in pygame.event.get():if event.type == QUIT:returnelif event.type == KEYDOWN and event.key == K_ESCAPE:returnif event.type ==pygame.MOUSEBUTTONDOWN:#need to be modified to handle a list of chromosomesfor i in fck:i.rollover()allsprites.update()screen.blit(background,(0,0))allsprites.draw(screen)pygame.display.flip()main()
Answer

You pass a position to your sprites and store it in self.pos, but to draw a Sprite a sprite group uses the rect attribute:

From pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.

https://en.xdnf.cn/q/119229.html

Related Q&A

Efficiently append an element to each of the lists in a large numpy array

I have a really large numpy of array of lists, and I want to append an element to each of the arrays. I want to avoid using a loop for the sake of performance. The following syntax is not working. a=np…

How to traverse a high-order range in Python? [duplicate]

This question already has answers here:Equivalent Nested Loop Structure with Itertools(2 answers)Closed 4 years ago.In python, we can use range(x) to traverse from 0 to x-1. But what if I want to trave…

How to send eth_requestAccounts to Metamask in PyScript?

I am trying to get address from installed MetaMask on the browser. We used to do this in JS as follow:const T1 = async () => {let Address = await window.ethereum.request({method: "eth_requestAc…

Extract strings that start with ${ and end with }

Im trying to extract the strings from a file that start with ${ and ends with } using Python. I am using the code below to do so, but I dont get the expected result.My input file looks like this:Click …

Weibull distribution and the data in the same figure (with numpy and scipy) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

python: use agg with more than one customized function

I have a data frame like this.mydf = pd.DataFrame({a:[1,1,3,3],b:[np.nan,2,3,6],c:[1,3,3,9]})a b c 0 1 NaN 1 1 1 2.0 3 2 3 3.0 3 3 3 6.0 9I would like to have a resulting dataframe like…

sending multiple images using socket python get sent as one to client

I am capturing screenshots from the server, then sending it to the client, but the images get all sent as one big file to the client that keeps expanding in size. This only happens when i send from one…

What are the different methods to retrieve elements in a pandas Series?

There are at least 4 ways to retrieve elements in a pandas Series: .iloc, .loc .ix and using directly the [] operator.Whats the difference between them ? How do they handle missing labels/out of range…

Speaker recognition - Bad Request error on microsoft oxford

I am using the python wrapper that has been given in the SDK section. Ive been trying to enroll a voice file for a created profile using the python API.I was able to create a profile and list all profi…

Remove list of phrases from string

I have an array of phrases: bannedWords = [hi, hi you, hello, and you]I want to take a sentence like "hi, how are tim and you doing" and get this:", how are tim doing"Exact case mat…