Wall Collision Problem – Python game with Pythonista iOS

I try to programm a little game with Python on Pythonista for my iPad. I’m using the accelerometer (gravity() function) from the iPad to control the player.

I’ve build some walls and want to do some basic collision. The collision detection is working fine but I just don’t get it how do I make the player not run throught the wall. I tried some things but it doesn’t work. I already looked for similiar questions but the solution mentioned there don’t seem to work in my case. I tried to set the velocity to 0 but then the player is stuck on the wall.

See “alien_move()” for the details. “self.walls” is just a list with all wall objects. I think the reason might be that both gravity parameters always change and not only one. But I don’t get anything to work. Any ideas? Thanks in advance!

from scene import * import sound import random import math import ui import map import time A = Action 
class Game (Scene):      def map(self):         ''' Some code for walls not that important'''         self.walls.append(self.wall_1)         self.walls.append(self.wall_2)         self.walls.append(self.wall_3)         self.walls.append(self.wall_4)         self.walls.append(self.wall_5)         self.walls.append(self.wall_6)         self.walls.append(self.wall_7)      def setup(self):         self.game_running = False         # Screen Size         screen_w = 834         screen_h = 1184         # Background         self.background_color = '#1a0093'         # Lists         self.objects = []         self.walls = []         self.persons = []         # Map         self.map()         # Player         self.alien = SpriteNode('emj:Alien')         self.alien.position = (screen_w / 2, 70)         self.alien.scale = 0.75         # Constant which describes the velocity of the alien         self.alien_velocity_x = 10         self.alien_velocity_y = 10         # Add Child         self.add_child(self.alien)         for w in self.walls:             self.add_child(w)         # Print      def did_change_size(self):         pass      def alien_move(self):         if self.game_running == True:             self.alien_velocity_x = 10             self.alien_velocity_y = 10             #print(gravity().x, gravity().y)             # left minus, right plus, tilted front plus, tilted back minus             new_x = self.alien.position.x + gravity().x * self.alien_velocity_x             new_y = self.alien.position.y + gravity().y * self.alien_velocity_y             if new_x >= 0 and new_x <= 834 and new_y >= 0 and new_y <= 1154:                 self.alien.position = (new_x, new_y)             for w in self.walls:                 newPos = self.alien.position                 if self.alien.bbox.intersects(w.bbox):                     if gravity().x > 0:                         self.alien_velocity_x = 0                         newPos.x = (w.bbox.x - w.bbox.w) - self.alien.bbox.w                     elif gravity().x < 0:                         self.alien_velocity_x = 0                         newPos.x = (w.bbox.x + w.bbox.w)                     elif gravity().y > 0:                         newPos.y = (w.bbox.y - w.bbox.h) - self.alien.bbox.h                         self.alien_velocity_y = 0                     elif gravity().y < 0:                         newPos.y = (w.bbox.y + w.bbox.h)                         self.alien_velocity_y = 0      def update(self):         self.alien_move()      def touch_began(self, touch):         x, y = touch.location         if (x, y) > (0, 0):             self.game_running = True      def touch_moved(self, touch):         pass      def touch_ended(self, touch):         pass  if __name__ == '__main__':     run(Game(), PORTRAIT, show_fps=True) 

Collision Security

Question concerning collision issue in CBC-mode: If we are using CBC mode with AES for 1 message, the birthday paradox indicates that we risk a collision after 2^(n/2) so 2^64 plaintext of 128 bits of the message.

My question is: is there a similar result concerning the number of messages we can send with different IV but the same Key? Is it still 2^(n/2) different messages before security issues or is it something else?

Thank you

What does “claim name collision” mean in the context of JWTs?

Recently, I have been reading the JWT’ RFC and I’m struggling to understand the meaning of claim names collision.

The registered claim names are more or less clear. If I got it right, these are addressed to provide JWT specification with a set of claims out of the box. 1

However, when it comes to public and private claims, I don’t see it so clearly. My question is regarding public and private claim names collision.

Public

Claim Names can be defined at will by those using JWTs. However, in
order to prevent collisions, any new Claim Name should either be
registered in the IANA “JSON Web Token Claims” registry established
by Section 10.1 or be a Public Name: a value that contains a
Collision-Resistant Name
. In each case, the definer of the name or
value needs to take reasonable precautions to make sure they are in
control of the part of the namespace they use to define the Claim
Name.

Private

Private Claim Names are subject to collision and should be used with caution.

What does collision mean in this context? How can claim names collide when there is only one authentication and authorization provider? Are not these providers aware of the claims they populate and verify?

Could it be possible that a secondary auth provider could change the JWT payload so that it could override some of these claims?

Probably, I’m missing something important regarding the authentication and the authorization workflow, but I don’t know what. Or maybe I’m not getting the definition of collision because of my limited English skills.


1: I have checked out a couple of JWT APIs in Java and I have confirmed that these claims can be informed through dedicated methods/functions (unlike public o private claims whom are informed like a tuple key-value).

How to get collision area within a circle in libgdx

I have a ball inside of a multi-colored circle, the ball will hit the inner area of the circle like this bellow circle image

multiColoredCirlce

And the Circle will be rotated clockwise or anti-clockwise based on user input. How would I know, where the ball hit the Big Colored circle.

I just need to identify in which color of my circle sprite has made a collision with the ball.

I have tried a lot, googled a lot but still, the solution has not been found yet.

Experts, please help me.

Increasing probability of finding a hash collision

My objective is to find a hash collision of my modified hash function. Assuming my modified hash only outputs the first 36 bits of SHA-1. As we know, SHA-1 is a 160-bit hash value, hence, we only need to output 9 characters out of 40 characters for comparison.

How i begin my program is by hashing a string (I have a SHA-1 algorithm running and i will name it as sha1. I have also ensured that the output of the SHA-1 algorithm is correct.)

Firstly, i would hardcode 2 string and extract out 9 characters out of 40 characters since i require only the first 36 bits of SHA-1. The function below basically return a true if a collision is found and false if a collision is not found

public static boolean findCollision(int x1, int x2) {      String message1 = "I tried " + x1 + " iteration to find a collision";     String message2 = "I tried " + x2 + " iteration to find a collision";              //hashing my string and extracting 9 characters     String message_hash1 = sha1(message1);     String message_hash2 = sha1(message2);      String modified_hash1 = message_hash1.substring(0, 9);     String modified_hash2 = message_hash2.substring(0, 9);      if (modified_hash1.equals(modified_hash2))           return true;      else          return false; } 

Lastly, i will have a main function that will random Integers up to MAX_VALUE in a infinite loop and will break out if and only if a hash is found.

public static void main(String[] args) {      Random random = new Random();     int x1 = 0;     int x2 = 0;     int counter = 0;      while (true) {          while(true){              x1 = random.nextInt(Integer.MAX_VALUE);             x2 = random.nextInt(Integer.MAX_VALUE);              if (x1 != x2)                  break;           }           if (findCollision(x1, x2) == true) {             break;         }         counter++;     }      System.out.println("\nNumber of trials: " + counter); } 

If i tried taking only the first 24 bits of SHA-1, i could easily find a collision. However, i’m unable to find a collision for 36 bits instead despite running it for hours. Hence, I’m wondering what is other alternative way for me to find a collision with just 36 bits of SHA-1.

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?