Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Bug with casting int to float on Python 3 with get_random_food_position() #236

Open
@m0nt4ld0

Description

Problem Description:

I noticed that in the get_random_food_position() function, the code uses the random.randint() function with arguments that might be float values due to division. This is causing a TypeError because random.randint() expects integer values, not floats.

Currently, the code looks like this:
x = random.randint(-w / 2 + food_size, w / 2 - food_size)

And I'm getting this error trying to run this on Python 3
image

Why is it important?

This issue can lead to crashes or unexpected behavior during runtime.

Possible Solution:

🎯 My proposal is to ensure that the arguments passed to random.randint() are cast to integers. We can do this by either using int() to cast the values or by using integer division //.

Alternative 1:

def get_random_food_position():
 x = random.randint(int(-w / 2 + food_size), int(w / 2 - food_size))
 y = random.randint(int(-h / 2 + food_size), int(h / 2 - food_size))
 return (x, y)

Alternative 2:

def get_random_food_position():
 x = random.randint(-w // 2 + food_size, w // 2 - food_size)
 y = random.randint(-h // 2 + food_size, h // 2 - food_size)
 return (x, y)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /