[Pygame] A fusion of two images

[Pygame] A fusion of two images

Postby IvyMike » Tue Apr 02, 2013 7:01 pm

Hello !

Firstly, sorry for my english writting ...
I create a program like the famous game "Alchemy". In this game you can drag a lot of elements, like water or fire, on himselves and create new elements with their combinations ...

So I try to make a "drag and drop" program with three pictures for a test. It's a Pygame program and it work.
And now, I want to allow that when i drag "fire" on "water" (for example), these two elements make a new element.

If you can help me to find a step or solutions for my program, thank you very much !

This is the program :

Code: Select all
from pygame import *
 
class Dragable(Rect,object):
 
    def __init__(self,img,**args):
        self.img = img
        Rect.__init__(self,img.get_rect(**args))
        self.selected = False
 
    def update(self,ev):
        if ev.type == MOUSEBUTTONDOWN and ev.button == 1 and self.collidepoint(ev.pos):
            self.selected = True
        elif ev.type == MOUSEBUTTONUP and ev.button == 1:
            self.selected = False
        elif ev.type == MOUSEMOTION and self.selected:
            relx,rely = ev.rel
            self.x += relx
            self.y += rely
            return True
 
    @property
    def pos(self):
        return self.topleft
 
 
fenetre = display.set_mode((850,850))

fond = image.load("interface.jpg").convert()
fenetre.blit(fond, (0,0))

feu = Dragable(image.load("fire-icon.png"),center=(800,400))
fenetre.blit(feu.img,feu.pos)

eau = Dragable(image.load("water-icon.png"),center=(800,500))
fenetre.blit(eau.img,eau.pos)

soufre = Dragable(image.load("sulphur-icon.png"),center=(800,600))
fenetre.blit(soufre.img,soufre.pos)

display.flip()
 
while True:
    ev = event.wait()
    if feu.update(ev):
        fenetre.blit(fond,(0,0))
        fenetre.blit(feu.img,feu.pos)
        fenetre.blit(eau.img,eau.pos)
        fenetre.blit(soufre.img,soufre.pos)
        display.flip()

    if eau.update(ev):
        fenetre.blit(fond,(0,0))
        fenetre.blit(eau.img,eau.pos)
        fenetre.blit(feu.img,feu.pos)
        fenetre.blit(soufre.img,soufre.pos)
        display.flip()
   
    if soufre.update(ev):
        fenetre.blit(fond,(0,0))
        fenetre.blit(soufre.img,soufre.pos)
        fenetre.blit(eau.img,eau.pos)
        fenetre.blit(feu.img,feu.pos)
        display.flip()
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby Mekire » Wed Apr 03, 2013 12:04 am

You haven't explained "how" you want your elements to mix. If you literally want the images to blend together, experiment with changing the alpha value on the surface as you are dragging it around. If you want it to use a completely new picture when you drop one item on top of another, that should be even easier. Also, as we don't have your images we can't experiment with the code despite whether it works or not.

One more note:
You should really try not to update the screen multiple times per frame if you don't have a good reason. Draw everything you need to the screen and then call pygame.display.update() or pygame.display.flip() once at the end of the loop. Also, anytime you are repeating code in python you are generally doing something wrong.

-Mek
User avatar
Mekire
 
Posts: 829
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [Pygame] A fusion of two images

Postby IvyMike » Wed Apr 03, 2013 6:58 am

Ah sorry, i just want a completely new picture when i drop an item on top of another.
You can try to make this with fire, water and sulphur ... For example water+fire = sulphur (just for example ;))
There i put the pictures that you need :

interface.jpg :
Image

sulphur-icon.png :
Image

water-icon.png
Image

fire-icon.png
Image

For the note ... I don't really understand ... If i disable display.flip(), the game don't work ... On an other forum they tell me thart we should to refreshing constantly.
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby Mekire » Wed Apr 03, 2013 2:39 pm

This is just a restructuring of your program; it doesn't do what you are aiming for just yet. I just want you to get an idea of the type of structure that you will eventually want to aim for.

Code: Select all
import pygame as pg
import os,sys

class BaseEle(object):
    def __init__(self,img,loc):
        self.img = img
        self.rect = self.img.get_rect(center=loc)
    def update(self,Surf):
        Surf.blit(self.img,self.rect)
    def events(self,ev):
        if ev.type == pg.MOUSEBUTTONDOWN and self.rect.collidepoint(ev.pos):
            if ev.button==1:
                return "Create new draggable copy"

class Dragable(object):
    def __init__(self,img,location):
        self.img = img
        self.rect = self.img.get_rect(center=location)
        self.start = self.rect.copy()
        self.selected = True
    def events(self,ev):
        if ev.type == pg.MOUSEBUTTONDOWN and ev.button == 1 and self.rect.collidepoint(ev.pos):
            self.selected = True
        elif ev.type == pg.MOUSEBUTTONUP and ev.button == 1:
            self.selected = False
        elif ev.type == pg.MOUSEMOTION and self.selected:
            self.rect.move_ip(ev.rel)
    def update(self,Surf):
        Surf.blit(self.img,self.rect)

class Control(object):
    def __init__(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        self.screen = pg.display.set_mode((850,640))
        self.load_gfx()
        self.elements = [BaseEle(self.ele_gfx[ele],(800,400+100*i)) for i,ele in enumerate(self.ele_gfx)]
        self.drag_list = []
    def load_gfx(self):
        self.bg = pg.image.load("interface.jpg").convert()
        self.ele_gfx = {"fire": pg.image.load("fire-icon.png").convert_alpha(),
                        "water": pg.image.load("water-icon.png").convert_alpha(),
                        "sulfur": pg.image.load("sulphur-icon.png").convert_alpha()}
    def event_loop(self):
        for ev in pg.event.get():
            if ev.type == pg.QUIT or (ev.type == pg.KEYDOWN and ev.key == pg.K_ESCAPE):
                pg.quit();sys.exit()
            for ele in self.drag_list[:]+self.elements:
                if ele.events(ev):
                    self.drag_list.append(Dragable(ele.img,ev.pos))
    def update(self):
        self.screen.fill(0)
        self.screen.blit(self.bg,(0,0))
        for ele in self.elements+self.drag_list:
            ele.update(self.screen)
    def main(self):
        while 1:
            self.event_loop()
            self.update()
            pg.display.update()

###
if __name__ == "__main__":
    RunIt = Control()
    RunIt.main()

Note that the screen is only updated once every time we loop. Also please take note of the imports.
Do not:
Code: Select all
from pygame import *
Don't even:
Code: Select all
from pygame.locals import *
Both of these are absolutely brutal on the namespace; never mind what you see in other peoples code.

To accomplish your goal you are going to need a defined target zone (a rectangle). If an element is dragged there, add it to another list of pending mix items. If the mouse button is released when the element is not in a target zone, delete the item from the drag list. Under whatever circumstances you require, check the pending mix item list and update and change things as you desire.

This project should be quite a lot of fun.
Good luck and keep me updated as you progress,
-Mek
User avatar
Mekire
 
Posts: 829
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [Pygame] A fusion of two images

Postby IvyMike » Thu Apr 04, 2013 6:02 pm

Thank You very much i've read this program attentively and i'll find a solution for my goal.

But there is a little problem ... When i want to take a picture, it's duplicatded. The starting image stay on the screen. Whereas i wand to make move independently any image which i add in fact ... I'm very sorry but how can i modify the program ?
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby Mekire » Thu Apr 04, 2013 11:43 pm

Sorry. I imagined the original icons working as a sort of pallet menu you could select from. Making it so they just move wherever you want is significantly easier.

Code: Select all
import pygame as pg
import os,sys

class Dragable(object):
    def __init__(self,img,location):
        self.img = img
        self.rect = self.img.get_rect(center=location)
        self.selected = False
    def events(self,ev):
        if ev.type == pg.MOUSEBUTTONDOWN and self.rect.collidepoint(ev.pos):
            if ev.button == 1:
                self.selected = True
        elif ev.type == pg.MOUSEBUTTONUP:
            if ev.button == 1:
                self.selected = False
    def update(self,Surf):
        if self.selected:
            self.rect.center = pg.mouse.get_pos()
        Surf.blit(self.img,self.rect)

class Control(object):
    def __init__(self):
        pg.init()
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        self.screen = pg.display.set_mode((850,640))
        self.load_gfx()
        self.done = False
        self.elements = [Dragable(self.ele_gfx[ele],(800,400+100*i)) for i,ele in enumerate(self.ele_gfx)]
    def load_gfx(self):
        self.bg = pg.image.load("interface.jpg").convert()
        self.ele_gfx = {"fire": pg.image.load("fire-icon.png").convert_alpha(),
                        "water": pg.image.load("water-icon.png").convert_alpha(),
                        "sulfur": pg.image.load("sulphur-icon.png").convert_alpha()}
    def event_loop(self):
        for ev in pg.event.get():
            if ev.type==pg.QUIT or (ev.type==pg.KEYDOWN and ev.key==pg.K_ESCAPE):
                self.done = True
            for ele in self.elements:
                ele.events(ev)
    def update(self):
        self.screen.fill(0)
        self.screen.blit(self.bg,(0,0))
        for ele in self.elements:
            ele.update(self.screen)
    def main(self):
        while not self.done:
            self.event_loop()
            self.update()
            pg.display.update()
###
if __name__ == "__main__":
    RunIt = Control()
    RunIt.main()
    pg.quit();sys.exit()


-Mek
User avatar
Mekire
 
Posts: 829
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [Pygame] A fusion of two images

Postby IvyMike » Tue Apr 09, 2013 4:07 pm

Thank You !
Can you comment yout program please ? Because i try all this week to use pygame's functions and parts of others programs to make my "fusion" and i dont find ... So if i understand your code, it will easier for me ...
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby Mekire » Wed Apr 10, 2013 2:46 pm

Here's a bit of commenting. Feel free to ask if there is something specific you don't understand about it.

Code: Select all
import pygame as pg
import os  #os is used for centering the screen with os.environ
import sys #sys is used for sys.exit

class Dragable(object):
    """Our dragable object class."""
    def __init__(self,img,location):
        """Set up the image, rectangle, and initialize self.selected flag to False"""
        self.img = img
        self.rect = self.img.get_rect(center=location)
        self.selected = False
    def events(self,ev):
        """If object is clicked on, set self.selected to True until button is released."""
        if ev.type == pg.MOUSEBUTTONDOWN and self.rect.collidepoint(ev.pos):
            if ev.button == 1:
                self.selected = True
        elif ev.type == pg.MOUSEBUTTONUP:
            if ev.button == 1:
                self.selected = False
    def update(self,Surf):
        """If self.selected is True move the object to the location of the mouse cursor;
        then blit the object to the given surface (usually the display surface)."""
        if self.selected:
            self.rect.center = pg.mouse.get_pos()
        Surf.blit(self.img,self.rect)

class Control(object):
    """Our main event and game loop are controlled with this class."""
    def __init__(self):
        """Initialize the necessary things for our pygame display;
        create a clock to control the frame rate; load graphics; and create an
        initial list of our desired Dragable objects."""
        pg.init()
        os.environ['SDL_VIDEO_CENTERED'] = '1'  #Center screen.
        self.Screen = pg.display.set_mode((850,640))
        self.Clock = pg.time.Clock()
        self.load_gfx()
        #The following line creates our list with a list comprehension.
        self.elements = [Dragable(self.ele_gfx[ele],(800,400+100*i)) for i,ele in enumerate(self.ele_gfx)]
        self.done = False #Flag for breaking out of main loop and exiting.
    def load_gfx(self):
        """Load our background image; then load each of our icon images,
        placing them in a dictionary. Always use convert or convert_alpha for
        improved performance."""
        self.bg = pg.image.load("interface.jpg").convert()
        self.ele_gfx = {"fire": pg.image.load("fire-icon.png").convert_alpha(),
                        "water": pg.image.load("water-icon.png").convert_alpha(),
                        "sulfur": pg.image.load("sulphur-icon.png").convert_alpha()}
    def event_loop(self):
        """Process the events on the event queue. Currently this checks if there
        is a reason the game should exit; then passes this event to each of our
        dragable objects' events function."""
        for ev in pg.event.get():
            if ev.type==pg.QUIT or (ev.type==pg.KEYDOWN and ev.key==pg.K_ESCAPE):
                self.done = True
            for Ele in self.elements:
                Ele.events(ev)
    def update(self):
        """Our main update function. It fills the screen with black; then draws
        our background image; and finally updates each of the dragable objects."""
        self.Screen.fill(0)
        self.Screen.blit(self.bg,(0,0))
        #Updating using list comprehensions.
        [Ele.update(self.Screen) for Ele in self.elements if not Ele.selected]
        #Makes sure that the current one we are dragging around appears on top.
        [Ele.update(self.Screen) for Ele in self.elements if Ele.selected]

    def main(self):
        """The main loop. Every frame it processes the event queue; updates everything;
        and then restricts the game to the desired framerate."""
        while not self.done:
            self.event_loop()
            self.update()
            pg.display.update()
            self.Clock.tick(60) #60 FPS is usually a good number.
###
if __name__ == "__main__":
    #This is the proper may to run code. Things down here only run if this module
    #is run directly; not if imported by another module.
    RunIt = Control() #Create an instance of Control. This also initializes pygame.
    RunIt.main()
    pg.quit();sys.exit()

-Mek
User avatar
Mekire
 
Posts: 829
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [Pygame] A fusion of two images

Postby IvyMike » Wed Apr 10, 2013 7:13 pm

Okay, I understand now ! :D
I find a way now ! In our def event_loop, i add an itertools function
Code: Select all
def event_loop(self):
        for ev in pg.event.get():
            if ev.type==pg.QUIT or (ev.type==pg.KEYDOWN and ev.key==pg.K_ESCAPE):
                self.done = True
            for ele in itertools.permutations(self.elements, 2):
                if ele[0].rect.colliderect(ele[1]):
                    print "collision between:", ele


Now I can detect a collision between two elements. It work but i thought that "permutation" can make my fusion ... Like that :

Code: Select all
            for ele in itertools.permutations(self.elements, 2):
                if ele[0].rect.colliderect(ele[1]):
                    print "collision between:", ele
                       remove (elements) and blit "water vapor"


What do you think about this way ? How i can make that replacement ?
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby Mekire » Thu Apr 11, 2013 4:58 am

That is an interesting way to do, and may suit your purposes. You might also want to look into pygame.Rect.collidelist as a possible alternative. Also, keep in mind why, and how, the code is organized. If a function has nothing to do with getting an event from the event queue, don't place it in the event_loop function. Place things in obvious places with obvious names.

I changed a few things regarding image loading and gave the Dragable class an attribute called self.kind so that we can keep track of what type of object is what. I also added two global constants; one is called ELE_LIST and is a list of the names of all our elements (note these must be identical to the prefix element name of the corresponding image file i.e. the name corresponding to "sulphur-icon.png" must be "sulphur"); the other global constant is called TRANS_DICT in which we tell it what pair of elements turn into what new element.

The transformations themselves are implemented in the Control method, Alchemize. This is essentially using the method you were trying but is, maybe, a bit hackish. I also made it so the transformations wouldn't occur until after an item was released (it won't changed while actively dragging it around the screen).

This all works well enough, but you also might want to consider having a specific "mixing area" in the screen, and maybe even a confirm mixing button. I don't really know what your target goal is though so who knows.

Anyway... take a look:
Code: Select all
import pygame as pg
import os  #os is used for centering the screen with os.environ
import sys #sys is used for sys.exit
import itertools

ELE_LIST = ["fire","water","sulphur"]

TRANS_DICT = {("fire" ,"water")   : "sulphur",
              ("fire" ,"sulphur") : "water",
              ("water","sulphur") : "fire"}

class Dragable(object):
    """Our dragable object class."""
    def __init__(self,kind,location):
        """Set up the image, rectangle, and initialize self.selected flag to False"""
        self.kind = kind
        self.img = self.get_img()
        self.rect = self.img.get_rect(center=location)
        self.selected = False
    def get_img(self):
        """Our draggable objects now have an attribute self.kind to keep track
        of what type of element they are. As a result element image file names
        must conform to the form self.kind+"-icon.png"."""
        return pg.image.load(self.kind+"-icon.png").convert_alpha()

    def events(self,ev):
        """If object is clicked on, set self.selected to True until button is released."""
        if ev.type == pg.MOUSEBUTTONDOWN and self.rect.collidepoint(ev.pos):
            if ev.button == 1:
                self.selected = True
        elif ev.type == pg.MOUSEBUTTONUP:
            if ev.button == 1:
                self.selected = False
    def update(self,Surf):
        """If self.selected is True move the object to the location of the mouse cursor;
        then blit the object to the given surface (usually the display surface)."""
        if self.selected:
            self.rect.center = pg.mouse.get_pos()
        Surf.blit(self.img,self.rect)

class Control(object):
    """Our main event and game loop are controlled with this class."""
    def __init__(self):
        """Initialize the necessary things for our pygame display;
        create a clock to control the frame rate; load graphics; and create an
        initial list of our desired Dragable objects."""
        pg.init()
        os.environ['SDL_VIDEO_CENTERED'] = '1'  #Center screen.
        self.Screen = pg.display.set_mode((850,640))
        self.Clock = pg.time.Clock()
        self.bg = pg.image.load("interface.jpg").convert() #load background image
        #The following line creates our list with a list comprehension.
        self.elements = [Dragable(name,(800,50+100*i)) for i,name in enumerate(ELE_LIST*2)]
        self.done = False #Flag for breaking out of main loop and exiting.

    def event_loop(self):
        """Process the events on the event queue. Currently this checks if there
        is a reason the game should exit; then passes this event to each of our
        dragable objects' events function."""
        for ev in pg.event.get():
            if ev.type==pg.QUIT or (ev.type==pg.KEYDOWN and ev.key==pg.K_ESCAPE):
                self.done = True
            for Ele in self.elements:
                Ele.events(ev)

    def update(self):
        """Our main update function. It fills the screen with black; then draws
        our background image; and finally updates each of the dragable objects."""
        self.Screen.fill(0)
        self.Screen.blit(self.bg,(0,0))
        #Updating using list comprehensions.
        [Ele.update(self.Screen) for Ele in self.elements if not Ele.selected]
        #Makes sure that the current one we are dragging around appears on top.
        [Ele.update(self.Screen) for Ele in self.elements if Ele.selected]

    def alchemize(self):
        """If items that aren't currently selected overlap, transform them
        according to our global constant TRANS_DICT."""
        for Eles in itertools.permutations(self.elements,2):
            if not Eles[0].selected and not Eles[1].selected:
                if Eles[0].rect.colliderect(Eles[1]):
                    self.elements.remove(Eles[0])
                    key = Eles[0].kind,Eles[1].kind
                    if key[0] != key[1]:
                        if key not in TRANS_DICT:
                            key = key[::-1]
                        Eles[1].kind = TRANS_DICT[key]
                        Eles[1].img = Eles[1].get_img()
                    break

    def main(self):
        """The main loop. Every frame it processes the event queue; updates everything;
        and then restricts the game to the desired framerate."""
        while not self.done:
            self.event_loop()
            self.alchemize()
            self.update()
            pg.display.update()
            self.Clock.tick(60) #60 FPS is usually a good number.

###
if __name__ == "__main__":
    #This is the proper may to run code. Things down here only run if this module
    #is run directly; not if imported by another module.
    RunIt = Control() #Create an instance of Control. This also initializes pygame.
    RunIt.main()
    pg.quit();sys.exit()


-Mek
User avatar
Mekire
 
Posts: 829
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [Pygame] A fusion of two images

Postby IvyMike » Thu Apr 11, 2013 7:04 pm

That is perfect ! :D I will never have thought about this !
I learn I learn.

I change combinations to a funny chain >>
Water + Fire = Vapor
Vapor + Water = Alcool
Alcool + Fire = Cocktail Molotov

I search a way to make specifics areas like you say : The center area for combinations and right area for conserve my elements progressively.
I annoy certainly you... But how can i place your "palett" function that you proposed to me ? I would like to have two cocktails molotov for example. So i need to have primary elements to infinite. Also for new elements creates.

Thank you very much for this program too ! I'm very grateful for all
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby Mekire » Fri Apr 12, 2013 2:16 am

Take a look back at how I originally did it in my first program. You will probably need another simple class for the pallette objects. These objects won't be dragable; all they will do is create a new dragable of their type when clicked. These basic pallette objects will need their own list. And after clicking them and creating a draggable of their type, it must then be added to the list of current dragables. As dragables will only be created in this manner you must also make it so they initialize with self.selected = True.

I could do it for you but I think I will give you some time to approach and think about the problem.

Another thing I noticed that you might want to consider changing; it would probably make things much easier if all of your element-icons were the same size. This will make centering them on each other much simpler. This doesn't mean you change the size of the drawn image. Just center each of them in a 60x60 pixel transparent image. Alternately you could even put them all on one sprite sheet (this is probably the best method especially as you get more and more images, but it will take a bit more work).

Eventually you might want to change your method of collision detection (of both mouse clicks and item overlaps) to bitmask collision rather than rectangle collision. This can be a bit tricky at first but it will make it so the drawn parts of your images actually have to be clicked/collide; rather than just their rectangles. Currently you can click on an empty area near an object and it will still register as clicking the object, for example.

-Mek
User avatar
Mekire
 
Posts: 829
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: [Pygame] A fusion of two images

Postby IvyMike » Mon Apr 22, 2013 1:31 pm

I see
Last edited by IvyMike on Tue Apr 23, 2013 12:07 pm, edited 3 times in total.
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm

Re: [Pygame] A fusion of two images

Postby metulburr » Mon Apr 22, 2013 2:46 pm

i think i am quite well versed in python, but just starting out in game programming. I find it quite mind boggling too.

But someone from c++ as siad: "You just have to jump into it".

And actually thanks for the idea. I think i might try out for a first test program a mimic of alchemy in pygames i think its easier than what i was trying to start off as a jumping point.

I am now actually trying to aquire all the images from alchemy, but not sure where to find them.
New Users, Read This
version Python 3.3.2 and 2.7.5, tkinter 8.5, pyqt 4.8.4, pygame 1.9.2 pre
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
User avatar
metulburr
 
Posts: 1123
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: [Pygame] A fusion of two images

Postby IvyMike » Tue Apr 23, 2013 12:07 pm

Should I re-use class BaseEle like this :

Code: Select all
import pygame as pg
import sys
import itertools

ELE_LIST = ["feu","eau",]

TRANS_DICT = {("feu" ,"eau")   : "vapeur",
              ("vapeur" ,"eau") : "alcool",
              ("alcool","feu") : "molotov"}

class BaseEle(object):
    def __init__(self,img,loc):
        self.img = self.get_img()
        self.rect = self.img.get_rect(center=loc)
    for Eles in ELE_LIST :
        self.element = False
    def update(self,Surf):
        Surf.blit(self.img,self.rect)
   
    def events(self,ev):
        if ev.type == pg.MOUSEBUTTONDOWN and self.rect.collidepoint(ev.pos):
            if ev.button==1:
                self.selected = True
                return "Create new draggable copy"
           
class Dragable(object):

    def __init__(self,kind,location):
       
        self.kind = kind
        self.img = self.get_img()
        self.rect = self.img.get_rect(center=location)
        self.selected = False
        self.element = True
    def get_img(self):
       
        return pg.image.load(self.kind+"-icon.png").convert_alpha()

    def events(self,ev):
        if ev.type == pg.MOUSEBUTTONDOWN and self.rect.collidepoint(ev.pos):
            if ev.button == 1:
                self.selected = True
        elif ev.type == pg.MOUSEBUTTONUP:
            if ev.button == 1:
                self.selected = False

    def update(self,Surf):
        if self.selected:
            self.rect.center = pg.mouse.get_pos()
        Surf.blit(self.img,self.rect)

class Control(object):

    def __init__(self):
        pg.init()
        self.Screen = pg.display.set_mode((850,850))
        self.bg = pg.image.load("interface.jpg").convert()
        self.elements = [Dragable(name,(800,50+100*i)) for i,name in enumerate(ELE_LIST*2)]
        self.done = False

    def event_loop(self):
        for ev in pg.event.get():
            if ev.type==pg.QUIT or (ev.type==pg.KEYDOWN and ev.key==pg.K_ESCAPE):
                self.done = True

       for ele in self.drag_list[:]+self.elements:
                if ele.events(ev):
                    self.drag_list.append(Dragable(ele.img,ev.pos))
           
        for Ele in self.elements:
                Ele.events(ev)

    def update(self):
        self.Screen.fill(0)
        self.Screen.blit(self.bg,(0,0))
        [Ele.update(self.Screen) for Ele in self.elements if not Ele.selected]
        [Ele.update(self.Screen) for Ele in self.elements if Ele.selected]

    def alchemize(self):
        for Eles in itertools.permutations(self.elements,2):
            if not Eles[0].selected and not Eles[1].selected:
                if Eles[0].rect.colliderect(Eles[1]):
                    self.elements.remove(Eles[0])
                    key = Eles[0].kind,Eles[1].kind
                    if key[0] != key[1]:
                        if key not in TRANS_DICT:
                            key = key[::-1]
                        Eles[1].kind = TRANS_DICT[key]
                        Eles[1].img = Eles[1].get_img()
                    break

    def main(self):
        while not self.done:
            self.element()
            self.event_loop()
            self.alchemize()
            self.update()
            pg.display.update()

if __name__ == "__main__":
   
    RunIt = Control()
    RunIt.main()
    pg.quit();sys.exit()


Note : I find my program ! the same ! exactely the same ! It's probably in java : http://littlealchemy.com
IvyMike
 
Posts: 11
Joined: Tue Apr 02, 2013 6:39 pm


Return to Game Development

Who is online

Users browsing this forum: Mekire, ssmith21991 and 1 guest