Hot answers tagged

42

tl;dr don't mix your event loop with your game loop. When you move your mouse, the game receives a load of pygame.MOUSEMOTION events. You don't actually use these events to update your mouse position though, you are getting the current state of the mouse using pygame.mouse.get_pos(). That's inefficient, but it's not the problem. The problem is you are ...


12

A Unit Vector is of length 1. A given vector can be converted to a unit vector by dividing it by it's magnitude. (With the exception of course that a zero length vector can not be converted). Note that magnitude can be calculated using the Pythagorean theorem For example if a vector has components: (x, y, z) magnitude = sqrt( x2+ y2+ z2) unit vector =...


11

Finding an algorithm is usually best done with a data structure that makes the algorithm easy. In this case, your territory. The territory should be an unordered (O(1) hash) set of borders and elements. Whenever you add an element to the territory, you iterate over adjacent tiles and see if they should be a border tile; in this case, they are a border ...


10

A* gives you the shortest path in the graph. When using a grid as your graph there are often multiple shortest paths. In your first diagram, that is one of the shortest paths. It puts all the axial movements first and all the diagonal movements afterwards. But that's the same length path as if you put all the diagonals first, or if you mixed axial and ...


10

If you read the pygame.time.Clock.tick() and pygame.time.Clock.get_fps() documents, you'll find that: tick() works with milliseconds - it returns the number of milliseconds since the last call get_fps() returns an average of the last 10 calls to tick(). If you do the math, that's pretty damn good that you're getting 59.8 most of the time, since with 60 FPS ...


10

If I understand you correctly, you want to create a densely packed maze like this, where each wall is the same thickness as each corridor: But you say the maze algorithms you've found only deal with infinitely thin partitions between cells corridor cells, rather than thick walls like these. Let's look closer. Here I've overlaid a grid on the maze above, ...


9

If I understand right, your map stores whether something is dirt or air, and the simplest thing would be to have dirt and air tiles. However, to make things look better, you have separate images for air above dirt, dirt above air, dirt left of air, and so on. So you're trying to figure out which image to use, given a tile and its neighbors. Is that right? ...


9

If you need to find edges of holes in the middle of your territory too, then your linear in the area of the territory bound is the best we can do. Any tile on the interior could potentially be a hole that we need to count, so we need to look at every tile in the area bounded by the territory's outline at least once to be sure we've found all the holes. But ...


7

convert() is used to convert the pygame.Surface to the same pixel format as the one you use for final display, the same one created from pygame.display.set_mode(). If you don't call it, then every time you blit a surface to your display surface, a pixel conversion will be needed - this is a per pixel operation, very slow - instead of a series of memory ...


7

You could look at Skulpt.org which provides a completely brower-based implementation of PyGame. However I do not know what external APIs PyGame uses and which are supported by Skulpt. Edit: it seems Skulpt also has WebGL bindings so this should be very possible!


7

Sounds like you're after something like a flood fill algorithm. Basically, something like the following algorithm (you can see other examples on the wikipedia page): 1. Add your castle to the Checklist 2. Get the first item from the Checklist 3. For each surrounding position 4. If not on Complete list 5. If `0` add to Checklist 6. If `1` ...


7

First you need to calculate the vector pointing from your player to the current mouse position. This can be done by subtracting the player's position with the mouse's position: mouse_x, mouse_y = pygame.mouse.get_pos() rel_x, rel_y = mouse_x - self.x, mouse_y - self.y Then calculate the angle: angle = math.atan2(rel_y, rel_x) This will calculate the ...


7

REST is not the right paradigm for bidirectional communication, because with REST you can not send data which wasn't specifically requested. Hammering the server with repeated requests is not a good solution because it generates lots of unnecessary network traffic and still gives you additional delays up to the length of your hammering interval. But there ...


7

Notice: Whether or not a tile is on the boundary only depends on it and its neighbors. Because of that: It is easy to run this query lazily. For instance: You do not need to search for the boundary on the whole map, only on what is visible. It is easy to run this query in parallel. In fact, I could image some shader code that does this. And if you need it ...


6

It's only randomized the first time because you're only calling the random function one time (when you create the monster object). When you have ma=random.randmint(5, 20) in your class then you are creating that variable with a random amount at that time, but you are not altering it. In order to get a random value every time you need to reset the value every ...


6

In a game, music would be the a way to play background music and sound the way to play sound effects (ej. jumping, firing, etc). Music is a special streaming channel of the Mixer. This means the file is streamed from disk in small chuncks and not loaded at once. Pygame only supports one Music at a time but you can have several Sound objects playing at once,...


6

You can use the size method size() size(text) -> (width, height) Returns the dimensions needed to render the text. This can be used to help determine the positioning needed for text before it isrendered. It can also be used for wordwrapping and other layout effects. Here is an example myFont = pygame.font.Font(None, fontSize) width = myFont....


6

This site showed me how to do it: https://skellykiernan.wordpress.com/2015/01/04/python-pygame-install/ Note that the site uses Python 3.4.2 and pygame version 34cp, but I did it with Python 3.5 and pygame version 35cp and it worked perfectly.


6

I would create a directory containing language text files. The directory could look like this: en.txt 0 "Start game" 1 "Load game" 2 "Enable cannons" 3 "Join server" 4 "Kill the enemy" fr.txt 0 "Démarrer le jeu" 1 "Load game" 2 "Activer canons" 3 "Rejoignez serveur" 4 "Tuer l'ennemi" de.txt 0 "Spiel starten" 1 "Spiel laden" 2 "Enable Kanonen" ...


6

There's a great GDC Talk by Elan Ruskin of Valve on what they call "AI-Driven Dialogue through Fuzzy Pattern Matching" or "Rule Databases for Contextual Dialogue and Game Logic" - it's the system that powers contextual dialogue in the Left4Dead games, for example. The core idea is that you can tag your dialogue with arbitrarily deep criteria for when it ...


5

the biggest problem I see is the sort call each step which is O(n log n) I suggest using the heapq so it will be reduced to O(log n) per insert and pop saving you a factor of n you will need to add the steps as lists with the sort key (the path["cost"] + computeOffset(path["steps"][-1], end) as first and then the tuple so natural ordering will be used ...


5

You have an issue with the capitalization of your variable names. You use a lowercase first letter for pressedLeft, but you're not careful with the other names (PressedRight vs pressedRight, same for up and down). This results in the creation of never used values in your if blocs. The syntax colouring helped my spot it right away. This should do the ...


4

Data-Driven Design I submitted something like this question to code review recently. After some suggestions and improvements, the result was a simple code that would allow some relative flexibility on weapon creation based on a dictionary (or JSON). The data is interpreted at runtime and simple verifications are done by the Weapon class itself, without the ...


4

The read() function in this line: map01 = f.read() doesn't do any format checking to try determine what the text is. It just returns raw bytes as a string. You need to convert it to a number explicitly: map01 = int(f.read())


4

I think what you mean is, how to load an animated GIF in pygame. It's true that pygame doesn't support animated GIFs natively, and you'd need GIFImage for that. Not sure how well it works, but I wouldn't recommend it anyway. This is because in games you usually want to control the animation yourself. Use a spritesheet or separate images for your sprite ...


4

The idea is to have spell objects hold some reference to the in-code action you want that spell to do. Python's first-class functions make this quite nice (I'll assume Python 2.7.x): class Spell: def __init__(self, name, description, activationFunction): self.name = name self.description = description self.activationFunction = ...


4

The Pygame Rect already comes with a few collision detection functions that may just do what you need: pygame.Rect.contains: test if one rectangle is inside another pygame.Rect.collidepoint: test if a point is inside a rectangle pygame.Rect.colliderect: test if two rectangles overlap pygame.Rect.collidelist: test if one rectangle in a list intersects pygame....


4

Looking at the implementation of clock.tick() and where in that module the FPS value is set (search for _clock->fps =), the documentation seems to be correct that it determines the FPS after 10 calls (which means at the 11th call) to tick(). Let's try with a more isolated example: import pygame clock = pygame.time.Clock() fps = 60 for i in range(20): ...


4

Unity's primary development language is C#. I am not aware of any way to add a new scripting language to Unity which works just like a native one. But you can call Python from C# using IronPython. So you could implement a stub for each MonoBehaviour in C# which doesn't do more than call a Python script to implement the actual logic. The end result might ...


Only top voted, non community-wiki answers of a minimum length are eligible