Shahrayar123 / Shahrayar123/Python-Projects

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

Open
#236 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
582
Forks
441
PR merge metrics
No merged PRs in 30d

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)

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Locate the get_random_food_position() function and inspect its callers and surrounding game logic. Reproduce the Python 3 failure, then verify that the function completes without a TypeError and continues returning valid food positions for representative dimensions.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
game-dev
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.