0

I'm making a version of Candy Box. Here is my code so far

import time 
print("Candy box")
candy = 0
while True:
    time.sleep(1)
    candy += 1
    print("You have ", candy, " candies.")

The problem is that this will output many lines one after the other when I want the last to be updated. Example:

Instead of:

You have 3 candies.
You have 4 candies.
You have 5 candies.

It would be:

You have 3 candies.

And then it would turn into:

You have 4 candies.
Paolo Casciello
  • 7,982
  • 1
  • 43
  • 42
user2916424
  • 37
  • 1
  • 1
  • 3
  • 4
    You might be interested in this post: http://stackoverflow.com/questions/6169217/replace-console-output-in-python – karthikr Nov 20 '13 at 17:43

2 Answers2

0

If your console understands ANSI control codes, you can use this:

#! /usr/bin/python3

import time

print ('Candy box\n')
candies = 0
while True:
    time.sleep (1)
    print ('\x1b[FYou have {} cand{}.\x1b[J'.format (candies, 'y' if candies == 1 else 'ies') )
    candies += 1

If your console doesn't understand ANSI, replace CSI F and CSI J with the corresponding control codes your console expects.

Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • Does it work? `\x1b[F` moves the cursor to the beginning of the previous line and `\x1b[J` clears the screen from the cursor. – Hyperboreus Nov 20 '13 at 17:55
0

A simpler version (IMO)

Used the '\b' to go back & re-write the whole line, thus giving a sense of update

import time
print("Candy box\n")
candies = 0
backspace = 0 # character count for going to .
while True:
    time.sleep(1)
    candies += 1
    if candies == 1:
        to_print = 'You have 1 candy.'
    else:
        to_print = 'You have %s candies.'%candies

    backspace = len(to_print)  # update number of characters to delete
    print(to_print+'\b'*backspace, end="")

You could also try the following

import time
print("Candy box\n")
candies = 0

to_print = 'You have 1 candy.'
backspace = len(to_print)      # character count for going to .
print(to_print+'\b'*backspace, end="")

while True:
    time.sleep(1)
    candies += 1
    to_print = 'You have %s candies.'%candies
    backspace = len(to_print)  # update number of characters to delete
    print(to_print+'\b'*backspace, end="")
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90