Home > Software design >  How to get a continuously changing user input dependent output in the same place at command line
How to get a continuously changing user input dependent output in the same place at command line

Time:12-03

I am designing a string based game where the real time positions of characters are represented as a string as follows: -----A-----o----- I am changing the position of the character "A" based upon user keyboard inputs eg: updated position: --------A--o-----

I don't want to print the string line by line as It gets updated instead I want to modify it every time in the same place when being output in command line, as the constraint I am working with is :

The entire game map should run on a single line on the command line - changing the state of the game should not spawn a new line every time.

CodePudding user response:

You could use '\r' in some way. Carriage return is a control character or mechanism used to reset a device's position to the beginning of a line of text. e.g.

import time

for i in range(100):
    time.sleep(1)
    print(i, end="\r");

Example including controls

import time
import keyboard

# params
size = 20
position = 0

# game loop
while True:
    # draw
    print("", end="\r")
    for i in range(size):
        print("-" if (position != i) else "o", end="")
    # move
    if keyboard.is_pressed("left"):  
        position = position - 1
        if position < 0:
            position = 0
    elif keyboard.is_pressed("right"):  
        position = position   1
        if position >= size:
            position = size
    # delay    
    time.sleep(0.1)
   

CodePudding user response:

when printing the output use the end attribute for print statements and set it as "\r" to get back the output position to starting of the line.

  • Related