Changing Selected Variables Chosen From Input()

I want to change different variables in my code while it's running, for example changing the variable speed = 1 to speed = 2 using the CMD. The variable I want to change is decided on the person running the code through an input(). They type in speed, and the variable speed changes to another number, also chosen by the person running the code through another input().

To change the values, you should need to-

.

Press Enter, to pause the game

Select the CMD window

Type 'setvar', then Enter

Type 'speed', then Enter

Type '5', then Enter

.

I want this to change speed = 1 to speed = 5, but I also want to be able to do this with every variable, being able to change the score variable, or anything else. So far, I have made it so you input the variable you want to change, and what you want to change it to. The code is slightly messy, but readable.

So far I have tried

exec("%s = %s" % (var,setTo))

and

exec(f"{var} = '{setTo}'")

But it hasn't worked, although speed = 5 does.

The code I want help with is near the bottom. The whole code is...

def RUN():
    
    import pygame
    import time
    import random
    import msvcrt as m
    pygame.init()
    
    dis_width = 800
    dis_height = 600
    
    score = 0
    x = 375
    y = 275
    foodx = -100
    foody = -100
    speed = 1
    stanima = 0
    gotox = 200
    gotoy = 200
    gotoSet = []
    goto = []
    gotoSet.append(gotox)
    gotoSet.append(gotoy)
    goto.append(gotoSet)
    people = []
    numOfPeople = 1  # Number of people
    foodEaten = True
    foodRun = True
    speedRunPlus = True
    speedRunMinus = True
    runningRun = True
    
    clock = pygame.time.Clock()
    font = pygame.font.SysFont("Arial", 18)
    
    dis = pygame.display.set_mode((dis_width, dis_height)) #screen stuff
    pygame.display.set_caption('Game')
    
    game_over = False
    running = True
    
    lightBlue = (50, 153, 213) #colors
    red = (255, 100, 0)
    yellow = (255, 255, 102)
    blue = (70, 70, 255)
    green1 = (0, 255, 0)
    green2 = (0, 255, 25)
    green3 = (0, 255, 50)
    green4 = (0, 255, 75)
    green5 = (0, 255, 100)
    green6 = (0, 255, 125)
    green7 = (0, 255, 150)
    green8 = (0, 255, 175)
    green9 = (0, 255, 200)
    green10 = (0, 255, 225)
    
    dis.fill(blue) #Backround
    
    pygame.draw.rect(dis, lightBlue, [50, 50, 700, 500]) #Inner rectangle
    
    
    def update_fps():
        fps = str(int(clock.get_fps()))
        fps = str("FPS: "+fps)
        fps_text = font.render(fps, 1, pygame.Color("coral"))
        return fps_text
        
    def speedRender():
        speed_str = str(speed)
        speed_sentance = str("Average Speed: "+speed_str)
        speed_text = font.render(speed_sentance, 1, pygame.Color("coral"))
        return speed_text
    
    def player(x, y, color, stamina): #Rectangle player
        player = pygame.draw.rect(dis, color, [x, y, 25, 25])
        
        if stanima == 1:
            pygame.draw.rect(dis, red, [x+11, y+11, 3, 3])
        elif stanima == 2:
            pygame.draw.rect(dis, red, [x+10, y+10, 5, 5])
        elif stanima == 3:
            pygame.draw.rect(dis, red, [x+9, y+9, 7, 7])
        elif stanima == 4:
            pygame.draw.rect(dis, red, [x+8, y+8, 9, 9])
        elif stanima == 5:
            pygame.draw.rect(dis, red, [x+7, y+7, 11, 11])
        elif stanima == 6:
            pygame.draw.rect(dis, red, [x+6, y+6, 13, 13])
        elif stanima == 7:
            pygame.draw.rect(dis, red, [x+5, y+5, 15, 15])
        elif stanima == 8:
            pygame.draw.rect(dis, red, [x+4, y+4, 17, 17])
        elif stanima == 9:
            pygame.draw.rect(dis, red, [x+3, y+3, 19, 19])
        
        
    def food(foodx, foody): #Rectangle food
        food = pygame.draw.rect(dis, yellow, [foodx, foody, 10, 10])
    
    for num1 in range(numOfPeople):
            x = random.randint(300,400)
            y = random.randint(300,400)
            person = []
            person.append(x)
            person.append(y)
            person.append(1)
            person.append(goto)
            person.append(score)
            people.append(person)
    
    while not game_over:
        
        while running:
            
            dis.fill(blue)
            pygame.draw.rect(dis, lightBlue, [50, 50, 700, 500])
            
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    game_over = True
        
            for num2 in range(numOfPeople):
                
                x = people[0][0]
                y = people[0][1]
                #speed = people[0][2]
                goto = people[0][3]
                score = people[0][4]
                
                del people[0]
                
                if x+12 > foodx+5: # "AI"
                    x -= speed
                elif x+12 < foodx+5:
                    x += speed
            
                if y+12 > foody+5: # "AI"
                    y -= speed
                elif y+12 < foody+5:
                    y += speed
                
                if x > 725: #Creates Borders
                    x = 725
                    game_over = True
                elif x < 50:
                    x = 50
                    game_over = True
                    
                if y > 525:
                    y = 525
                    game_over = True
                elif y < 50:
                    y = 50
                    game_over = True
                
                if x >= foodx-24 and x <= foodx+10:
                    if y >= foody-24 and y <= foody+10:
                        score += 1
                        foodEaten = True
                        #print("Score:", score)
                
                person = []
                person.append(x)
                person.append(y)
                person.append(1)
                person.append(goto)
                person.append(score)
                people.append(person)
                
                playerColor = green1
                
                player(x, y, playerColor, stanima) #Creating Player
            
            if foodEaten == True:
                foodx = random.randint(90, 700)
                foody = random.randint(90, 500)
                stanima += 1
                foodEaten = False
            
            food(foodx, foody) #Creating Food
            
            pressed = pygame.key.get_pressed() #Key Movement
            if pressed[pygame.K_RCTRL]:
                dis.blit(update_fps(), (10,0))
                dis.blit(speedRender(), (100,0))
            if pressed[pygame.K_SPACE]:
                RUN()
            if pressed[pygame.K_ESCAPE]:
                running = False
                game_over = True
            if pressed[pygame.K_RSHIFT]:
                if foodRun == True:
                    foodx = random.randint(90, 700)
                    foody = random.randint(90, 500)
                    stanima += 1
                    foodEaten = False
                    foodRun = False
            else:
                foodRun = True
            if pressed[pygame.K_RETURN]:
                if runningRun == True:
                    running = False
                    runningRun = False
                    print(" ")
            else:
                runningRun = True
            if pressed[pygame.K_MINUS]:
                if speedRunMinus == True:
                    speed -= 0.1
                    speedRunMinus = False
            else:
                speedRunMinus = True
            if pressed[pygame.K_EQUALS]:
                if speedRunPlus == True:
                    speed += 0.1
                    speedRunPlus = False
            else:
                speedRunPlus = True
                        
            pygame.display.flip() #updating screen
            clock.tick()
        
        if not game_over:
            command = input(" :")
            commandSplit = command.split(".")
            
            #try:
            if commandSplit[0] == "return":
                var = input("  :")
                if var in dir():
                    print("   :", eval(var), sep='')
                else:
                    print("   :Variable Not Found")
            elif commandSplit[0] == "run":
                if commandSplit[1] == "exit":
                    running = False
                    game_over = True
            elif commandSplit[0] == "setvar":
                var = input("  :")
                print("Var value now:", eval(var), sep='')
                if var in locals():
                    setTo = input("Change variable to:") #Code I need help with -----------------------
                    
                    
                    
                    print("Var value after:", eval(var), sep='')
            else:
                print("  :Invalid Syntax Error")
            '''
            except Exception:
                print("  :Invalid Syntax Error")
                pass
            '''#to implement later

RUN()


Read more here: https://stackoverflow.com/questions/67480444/changing-selected-variables-chosen-from-input

Content Attribution

This content was originally published by Tequin Lake at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: