## Python Tkinter Collision in an animation loop

I’m making a small game where the player (a blue ball) needs to avoid the falling enemies (colored balls). The user can click on a button to add more enemies to make it more difficult.

The problem I’m having here is collision between the player circle and the enemy circles within the animation loop. It works if the player collides with the default enemy that was made in the constructor of the Enemy class, but not with the randomly generated ones. I really could use some pointers for what I’m missing here. Note: The default enemy is just for testing and doesn’t actually get rendered once the final product is done.

View post on imgur.com

from project.helpers import * from tkinter import *  """Avoid the falling enemies (circles) for as long as you can"""   class GUI:      def __init__(self, window, width=1200, height=600):          self.player = Player()         self.enemy = Enemy()         self.enemy_list = []          # Set up canvas         self.window = window         self.width = width         self.height = height         self.canvas = Canvas(window, width=self.width, height=self.height, bg="gray")         self.canvas.pack()          # Set up animation variables         self.rate = 50         self.terminated = True         self.window.after(0, self.animation)          # Create the control frame for buttons and bind the arrow keys to the process_keys method         self.control_frame = Frame(window)         self.control_frame.pack(side=BOTTOM, pady=2)         self.canvas.bind("<Key>", self.process_keys)         self.canvas.focus_set()          # Welcome text that displays when module is first run, this disappears once the game has started         self.welcome_text = self.canvas.create_text(600, 300, fill="red", font="Tahoma 24", text="Welcome! Press Start to Play Game")          # Call the create_widgets method         self.create_widgets()      def create_widgets(self):         """Set up all buttons on the bottom of the GUI"""          quit_button = Button(self.control_frame, text="Quit", command=self.quit)         quit_button.pack(side=RIGHT)          play_button = Button(self.control_frame, text="Start", command=self.start)         play_button.pack(side=LEFT, padx=2)          add_enemy_button = Button(self.control_frame, text="Increase Difficulty", command=self.create_random_enemy)         add_enemy_button.pack(side=LEFT, padx=2)      def start(self):         """Once the user has clicked the Start button, call this method to begin the game - this will start the         animation loop"""         self.terminated = False      def game_over(self):          self.terminated = True         self.canvas.create_text(600, 300, fill="red", font="Tahoma 48", text="Game Over!")      def create_random_enemy(self):          rand_enemy = Enemy(randint(25, self.width - 25), randint(25, 30), randint(25, 30), randint(1, 2), get_random_color())         self.enemy_list.append(rand_enemy)      def animation(self):         """Create animation loop"""         if not self.terminated:             self.canvas.delete(ALL)             self.player.render(self.canvas)             #self.enemy.render(self.canvas)  # Only for testing, this just renders the default enemy not the random ones              for e in self.enemy_list:  # Render the random enemies on to the canvas                 e.render(self.canvas)                 e.move(self.canvas)                 if self.player.check_collision(self.enemy):                     self.game_over()         self.window.after(self.rate, self.animation)      def process_keys(self, event):         """Set up arrow keys to correspond to the player movements (left, right, up, down)"""         if event.keysym == "Right":             self.player.move_right(self.canvas)         if event.keysym == "Left":             self.player.move_left()         if event.keysym == "Up":             self.player.move_up(self.canvas)         if event.keysym == "Down":             self.player.move_down(self.canvas)      def quit(self):         self.window.destroy()  # Once user has clicked the quit button, exit the GUI program   class Player:      def __init__(self, x=600, y=550, radius=15, color="blue"):         """Set player instance variables"""         self.x = x         self.y = y         self.radius = radius         self.color = color      def render(self, canvas):         """Define a render method to render the player onto the canvas"""          canvas.create_oval(self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius, fill=self.color)      def move_right(self, canvas):         """These methods allow the player to move around the canvas based on arrow key input"""          self.x += 10         if self.x + self.radius > canvas.winfo_reqwidth():             self.x -= 10      def move_left(self):          self.x -= 10         if self.x - self.radius < 0:             self.x += 10      def move_up(self, canvas):          self.y -= 10         if self.y - self.radius < 0:             self.y += 10      def move_down(self, canvas):          self.y += 10         if self.y - self.radius > canvas.winfo_reqheight() - 30:             self.y -= 10      def get_radius(self):          return self.radius      def get_x(self):          return self.x      def get_y(self):          return self.y      def check_collision(self, enemy):         """If the distance between the center of the player and the center of the enemy ball are less than         the sum of both radii, there is a collision"""          return distance(self.x, self.y, enemy.get_x(), enemy.get_y()) <= (self.radius + enemy.get_radius())   class Enemy:      def __init__(self, x=50, y=50, radius=25, vel_y=3, color="white"):         """Set up enemy instance variables"""         self.x = x         self.y = y         self.radius = radius         self.vel_y = vel_y         self.color = color         self.width = 1200      def render(self, canvas):         """Render the enemy onto the canvas"""          canvas.create_oval(self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius, fill=self.color)      def move(self, canvas):          self.y += self.vel_y      def get_radius(self):          return self.radius      def get_x(self):         return self.x      def get_y(self):         return self.y   # Driver code if __name__ == '__main__':     root = Tk()     root.title('Dodger')     app = GUI(root)     root.mainloop() 

## Prove the probability of avoidance of collision in a hash function with particular range of inputs is larger than a constant

Suppose $$H = \{h_1, …, h_T\}$$ be a family of pairwise independent hash functions mapping $$\{0, 1\}^n$$ to $$\{0, 1\}^{n/2}$$. Let $$M = \frac{2^{n/4}}{10}$$ and let $$x_1, …, x_M$$ be any M distinct points in $$\{0, 1\}^n$$. If we choose $$h$$ randomly form $$H$$ and let $$E$$ be the event that $$h(x_1), …, h(x_M)$$ are all distinct. We need to show that $$Pr[E] \ge \frac{3}{4}$$.

$$\textbf{Markove’s inequality:}$$ If $$X$$ is a random variable which only takes non-negative values then, for any $$t \ge 0$$, $$Pr[X \ge t] \leq E[X]/t$$.

My idea is that we can compute $$Pr[h(x_i) = h(x_j)]$$, compute the expectation of the random variable $$Z = |\{(i,j) : h(x_i) = h(x_j)\}|$$ and use the Markove’s inequality to prove the question.

For two independent points $$x_i$$ and $$x_j$$, the probability that $$h(x_i)$$ and $$h(x_j)$$ are equal is $$1 – \{\text{the probability two independent points has the different hash values}\}$$, which is $$1 – \frac{1}{2^{n/2}}\cdot \frac{2^{n/2} – 1}{2^{n/2}}$$. That shows $$Pr[h(x_i) = h(x_j)] = \frac{2^{n/2} + 1}{2^{n}}$$.

As for the random variable $$Z$$, Let’s say $$Z_{i,j} = 1 \text{ if }h(x_i) = h(x_j)$$. Otherwise, $$Z_{i,j} = 0$$. Then we can get $$Pr(Z_{(i,j)}) = \frac{2^{n/2} + 1}{2^{n}}$$. Then $$E(Z) = \sum_{i,j} Pr(Z_{(i,j)}) = M \cdot \frac{2^{n/2} + 1}{2^{n}} = \frac{2^{n/4}}{10} \cdot \frac{2^{n/2} + 1}{2^{n}} = \frac{1}{10}$$.

Applying Markove’s inequality, $$Pr[Z > 0] < E[Z] = \frac{1}{10}$$. Since the event is exactly opposite of $$Z$$, we can know that $$Pr(E) = \frac{9}{10} \ge \frac{3}{4}$$.

This is my process, but I feel like the calculation of $$E(Z)$$ and the application of Markove’s inequality is not exactly right. I am new to the hash function and the random variable. Could someone give me some feedbacks or hints? Any help would be appreciated. Thanks in advance.

## Is there a collision free Hash Function for dynamic data that preserves already created hashes?

I am familiar with the concept of hash functions and fingerprints but I am new to the implementation of functions and the specific characteristics of all those hash functions out there.

## What I need

Say I have a table of employee data {FirstName, LastName, Birthday, …} which is dynamic. New employees join the the company, old employees leave. I want to hash the employee data. I need to make shure that the data of new employees is not hashed to the same value as any other employee that has ever been in the database.

In this sense the data set is append only. While deleting the employee data of an retiring employee is mandatory, I can store the hash, that was once linked to that employee. (Which most likely is of no use because the hash of past employees data will not evaluate to itself once hashed again 🙁 )

Hashing does not need to be cryptographic. Yet hashes must not easily be tracked back to employee data. By this I mean you are not supposed to use an efficient method to calculate employee data from hash values. Since information is lost in the process of hashing I would assume that this requirement is easy to match.

## The Goal

I want to reduce the size of the hash (meaning bit size) as much as possible.

I would assume that, without collision resistance, I need to pick a fairly large hash (2^32 or bigger) to assure a tolerable risk of collision. Avoiding this is the main interest behind the question.

I must guarantee that never ever a new employees data is hashed to the same value as one of the prior employees data was hashed to. I can make assumption like “Given infinite time there will in total never be more then 1.000.000 people in the company or retired from the company.” So the total number space of hashes is fixed.

Is this solvable? If not, what would be the best hashing procedure that assures maximum collision resistance (Rabin’s Fingerprinting?)

## How to check if moving OOB will resolve the collision?

I now (thanks to several questions that were already asked here) that I can use SAT to check if two OOB are intersecting or not. But what if they are already intersecting?

My situation is: I have two OOB that are moved independently by user with different speeds; my code can’t always prevent them from intersecting. They can also be intersecting from the start.

My code doesn’t move OOB so my problem is not exactly collision resolution (AFAIK), I need only to check if the movement chosen by the user is “ok”.

My question is – how can I check if moving one (or both) OOB will resolve the intersection?

What I tried already with some limited success:

• “Predict” OOB positions after moving for some time delta. Doesn’t work for slow movement, predicted OOB can still be intersecting. Making delta bigger can result in falling through. Checking several predictions each time requires too much time.
• Check if distance between centroids of the OOB is getting bigger. Kinda works but not for any movement; particularly, rotations around centroid won’t change said distance.

The only other solution that I can think of is too compute the volume of intersection and check if it’s getting smaller for a predicted OOBs but I’m afraid that will be too slow.

## different collision geometries in a component based game engine

I’m writing a simple game engine and after a lot of rethinking/refactoring I settled with sort of a component based architecture (not strictly ECS, but it isn’t inheritance based anymore either). So everything in my world is an entity, and each entity has got a bunch of components. Every system/subsystem in my game scans an entity for a series of components it’s interested in, and performs some relevant computations.

So far so good. The engine basic architecture can be seen here:

Now, every entity that is collidable with has a collision component (along with position/movement/rigidbody components), so the physics system needs to get that component and use it to feed its collision detection algorithms, in order to generate contact data to be used to resolve the collision.

I’m stuck on the following issue: the collison detection algorithms deal with different geometries: boxes,spheres,planes and rays (as of now), but I don’t want to have a spherecollisioncomponent and a boxcollisioncomponent, at least I don’t want them to be unrelated but I’d like them to share some common base class.

class Sphere  { public:     Sphere(float radius);     ~Sphere();     float GetRadius() { return mRadius; }  private:     float mRadius; };  class Box  : public BoundingVolume { public:     Box(const XMFLOAT3 &halfSize);     ~Box();     XMFLOAT3 const &GetHalfSize() const { return mHalfSize; } private:     XMFLOAT3 mHalfSize; }; 

Obviously each component has a different interface (boxes have halfsizes, spheres have a radius and so on), and the different collision detection functions deal very differently with each of them (box-box, box-sphere, sphere-sphere..).

void CollisionSystem::BoxAndBoxCollision(const Box &box1, const Box &box2) {     // contact data     XMFLOAT3 contactPoint;     XMFLOAT3 contactNormal;     float minOverlap = 100.0f;      // get axes for SAT test     std::vector<XMFLOAT3> axes = GetSATAxes(box1, box2);      int axisIndex = 0;     int index = 0;      for (XMFLOAT3 axis : axes)     {         if (XMVectorGetX(XMVector3Length(XMLoadFloat3(&axis))) < 0.01f)         {             index++;             continue;         }          float overlap = PerformSAT(axis, box1, box2);          if (overlap < 0)  // found separating axis - early out             return;          if (overlap < minOverlap)         {             minOverlap = overlap;             axisIndex = index;         }          index++;     }      // other collision detection/generation code.....       // store contact     mContacts.push_back(new Contact(box1->GetRigidBody(), box2->GetRigidBody(), contactPoint, contactNormal, minOverlap, coefficientOfRestitution)); } 

So how can I solve this in an elegant and robust way?

## How to find the speed of an object after collision without knowing the mass?

I have this question that’s dazzling me. We have two objects of the same mass, the first one is going 40 m/s towards the other which is sitting still (no friction here btw). The collision happens and the first one starts moving at an unknown speed at 30 degrees and the other also moves with unknown speed with 45 degrees.

The question is: What is the speed of both objects after the collision?

What’s confusing me is that without the masses i cannot calculate the kinetic energy, and conservation of momentum. I tried to use velocity components but since i am missing the velocity, it is impossible to find the length of the triangle with only one angle, or am i wrong?

thanks

## Triangle and Sphere collision?

I’m working through a collision detection problem and so far I got the colliding objects:

1. a sphere with center (1,1,1) and a radius of 3.
2. a triangle with vertices : v0 (0,5,-1) v1 (5,0,-1) v2 (-5,-5,0)

it is now asking me to find the
1. interpenetration depth
2. contact normal

From what I understand, the interpenatration depth is the magnitude of the vector from the closest point of collision to the center of the sphere. I just dont know how to get the closest point of collision and the contact normal.

Any help is appreciated!

## Planetary Collision vs a Large opponent’s AoO

So I have this situation: Largo the Large, who is Large, charges Count Countercharge, who has readied his Cometary Collision feat, and is Medium-sized.

The question is: does Largo, RAW, get an AoO on the Count?

The reasons I would think not are:

1. I seem to recall that you cannot take an AoO on your own turn, but I can’t find where I got that from.

2. Is an AoO during a charge possible? I think not – again, I can’t source why.

## Problem with the collision system

So,I did the very basic tutorial for phaser 3, which is a platformer. Following along those lines, I made my own custom platform(Striped Wavy Platform) and a custom player sprite(Red Amoeba) but somehow the collision is not working between the platform and the player .. Below are my screenshots followed by the code.

<!doctype html> <html lang="en"> <head>     <meta charset="UTF-8" />     <title>Making your first Phaser 3 Game - Part 2</title>     <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"</script>     <style type="text/css">         body {             margin: 0;         }     </style> </head> <body>  <script type="text/javascript">      var config = {         type: Phaser.AUTO,         width: 800,         height: 600,         physics: {                              //for physics system           default: 'arcade',           arcade: {             gravity: { x: 200,                       y: 300},             debug: false           }         },         scene: {             preload: preload,             create: create,             update: update         }     };      var level;     var player;      var game = new Phaser.Game(config);      function preload ()     {         this.load.image('amoeba', 'PlatformerJam/amoeba.png');         this.load.image('ground', 'PlatformerJam/level_ground.png');         this.load.image('air', 'PlatformerJam/air_particle.png');     }      function create ()     {       level = this.physics.add.staticGroup();       level.create(400,300,'ground');        player = this.physics.add.sprite(400,300,'amoeba');       player.setBounce(0.2);        player.setCollideWorldBounds(true);            this.physics.add.collider(level,player);       }      function update ()     {     }  </script>  </body> </html> 

## How client movement prediction syncs with server position to avoid a clip around collision?

I have searched a lot on stackexchange and on google, yet I have not found a satisfactory answer to this seemingly simple question.

I am making an online multiplayer game where the players navigate a 2d map with basic square obstacles. In this case I am making collision checks both on the client and the server, where the server broadcast everyone’s position once per second as authority. However, when making a sharp turn around a square, often times either the client makes the turn while the server clips, or the client clips at the corner while the server makes the turn. That is understandable considering the possible discrepancy between the position on the server and the predictive position of the client. How do online multiplayer games usually work around this simple yet crucial problem?

I understand that it comes down to a pixel perfect sync which isn’t possible, but how do other games navigate around this issue, to give a flawless collision experience?

What I am considering of doing:

1. Increase the position broadcasting rate from 1 time per second to however high needed to accurately sync the positions (20/sec). I believe this is the solution most games are doing. This however, will drastically increases the load on the server.
2. In my case, the game’s main mechanism isn’t the navigation (think MMO), so I am leaning towards only checking collision on the client side, and have a simpler collision check on the server to ban walk-through-wall hackers. This would relax the server from heavy collision operations which is nice too.