2013-11-20 70 views
0

我正在製作一個Candy Box版本。這是到目前爲止我的代碼用另一個文本替換一行文本(Python)

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

的問題是,其他在此之後會輸出很多行之一,當我想更新的最後一次。例如:

相反的:

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

這將是:

You have 3 candies. 

然後它會變成:如果您的控制檯理解ANSI控制碼

You have 4 candies. 
+4

您可能對這篇文章感興趣:http://stackoverflow.com/questions/6169217/replace-console-outp ut-in-python – karthikr

回答

0

,你可以用這個:

#! /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 

如果您的控制檯不理解ANSI,請將您的控制檯所需的相應控制代碼替換爲CSI FCSI J

+0

我真的沒那麼有經驗.. – user2916424

+0

它工作嗎? '\ x1b [F'將光標移動到上一行的開始,'\ x1b [J'清除光標處的屏幕。 – Hyperboreus

0

一個簡單的版本(IMO)

使用的'\b'回去&重新編寫整條生產線,從而使更新感

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="") 

您也可以嘗試以下

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="") 
相關問題