[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Pygame Problem Solving 1



Lamonte Harris wrote:
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    print pygame.mouse.get_pos() + (25,25)
As DR0ID said, you should be able to get the mouse position from the event.
                    print MAP.blocks[2].point
                    mouse = pygame.mouse.get_pos()
                    rng = mouse[0] - MAP.blocks[2].point[0]
                    rng2 = mouse[1] - MAP.blocks[2].point[1]
This is a pretty ugly way to have to deal with your map. If map is an object, I would abstract this into another class called Editor maybe, that has a function get_square that you pass it the mouse coordinates (it should already have the current map stored as an attribute of itself) and it returns a tuple of the position on the map the mouse is currently on. Or None for any coord of the mouse that's off the map so is obviously not colliding with any part of the map.
                    if rng in range(0,25) and rng2 in range(0,25):
                        print "True"
You can assume the coordinates are nonnegative here (since you're getting the mouse position in absolute rather than relative mode), so it would've been much more efficient to say
if rng < 25 and rng2 < 25:
Also notice that it's more likely the mouse will be too far in the x direction than the y because the resolution of the screen is elongated in the x direction, and because the 'and' short-circuits you want to check that x is in the desired position first. But this is a minor optimization that probably wouldn't make a noticable difference, and the way you ordered it originally was fine, anyway. Just wanted to mention that there actually is a reason to check x before y.


It's important for computer scientists to notice things like this so that their code will not end up needlessly complicated / slow. Yes, premature optimization can be bad, but optimizations like this aren't considered premature, just good practice.
-Luke