jeudi 31 décembre 2020

Odd Python random.randint behavior

I wrote a program to create the appearance of a snake sliding down the screen. You can pass in a width and length for the path the snake travels down. The snake moves at random staying within the width confines given.

All works fairly well, except when testing my guard rails to keep the snake within the defined width. I noticed at times the snake position (left_side) appears to be able to go to a negative value. Given that I have a guard rail that when left_side == 0 it should only be able to move back right given that when that condition is true my only values I can add to is should be 0 or 1.

How do I fix this?

My code:

import random
import time

def path(path_width, snake_pos):
    path = ""
    for space in range(path_width + 1):
        if space == 0:
            path = path + "|"
        if space == snake_pos:
            path = path + "()"
        if space == width: 
            path = path + "|"
        else:
            path = path + " "
    return path

width = int(input("How wide is your course? "))
length = int(input("How long is your course? "))

left_side = random.randint(1, width -1)

i=1
while i < length:
    if left_side == 0:
        left_side = left_side + random.randint(0, 1)
    if left_side == width:
        left_side = left_side + random.randint(-1, 0)
    else:
        left_side = left_side + random.randint(-1, 1)
    print(path(width, left_side) + " : leftside = " + str(left_side))
    i += 1
    time.sleep(.05)



Aucun commentaire:

Enregistrer un commentaire