2009-05-13 8 views
1

J'ai emprunté du code à un site, mais je ne sais pas comment l'afficher.Comment faire fonctionner un programme chronomètre?

class Stopwatch 
    def start 
    @accumulated = 0 unless @accumulated 
    @elapsed = 0 
    @start = Time.now 
    @mybutton.configure('text' => 'Stop') 
    @mybutton.command { stop } 
    @timer.start 
    end 

    def stop 
    @mybutton.configure('text' => 'Start') 
    @mybutton.command { start } 
    @timer.stop 
    @accumulated += @elapsed 
    end 

    def reset 
    stop 
    @accumulated, @elapsed = 0, 0 
    @mylabel.configure('text' => '00:00:00.00.000') 
    end 

    def tick 
    @elapsed = Time.now - @start 
    time = @accumulated + @elapsed 
    h = sprintf('%02i', (time.to_i/3600)) 
    m = sprintf('%02i', ((time.to_i % 3600)/60)) 
    s = sprintf('%02i', (time.to_i % 60)) 
    mt = sprintf('%02i', ((time - time.to_i)*100).to_i) 
    ms = sprintf('%04i', ((time - time.to_i)*10000).to_i) 
    ms[0..0]='' 
    newtime = "#{h}:#{m}:#{s}.#{mt}.#{ms}" 
    @mylabel.configure('text' => newtime) 
    end 
end 

Comment ferais-je pour que cela fonctionne? Merci

+0

Quel cadre comptiez-vous utiliser avec ? – Pesto

+0

Chaussures. Sauf si vous pouvez en recommander un meilleur. Je suis un débutant. – danhere

Répondre

4

Basé sur le code supplémentaire rkneufeld posté, cette classe nécessite un temporisateur spécifique à Tk. Pour le faire sur la console, vous pouvez simplement créer une boucle qui appelle tick encore et encore. Bien sûr, vous devez supprimer tout le code qui a été lié à l'interface graphique:

class Stopwatch 
    def start 
    @accumulated = 0 unless @accumulated 
    @elapsed = 0 
    @start = Time.now 
# @mybutton.configure('text' => 'Stop') 
# @mybutton.command { stop } 
# @timer.start 
    end 

    def stop 
# @mybutton.configure('text' => 'Start') 
# @mybutton.command { start } 
# @timer.stop 
    @accumulated += @elapsed 
    end 

    def reset 
    stop 
    @accumulated, @elapsed = 0, 0 
# @mylabel.configure('text' => '00:00:00.00.000') 
    end 

    def tick 
    @elapsed = Time.now - @start 
    time = @accumulated + @elapsed 
    h = sprintf('%02i', (time.to_i/3600)) 
    m = sprintf('%02i', ((time.to_i % 3600)/60)) 
    s = sprintf('%02i', (time.to_i % 60)) 
    mt = sprintf('%02i', ((time - time.to_i)*100).to_i) 
    ms = sprintf('%04i', ((time - time.to_i)*10000).to_i) 
    ms[0..0]='' 
    newtime = "#{h}:#{m}:#{s}.#{mt}.#{ms}" 
# @mylabel.configure('text' => newtime) 
    end 
end 

watch = Stopwatch.new 
watch.start 
1000000.times do 
    puts watch.tick 
end 

Vous finirez avec sortie comme ceci:

00:00:00.00.000 
00:00:00.00.000 
00:00:00.00.000 
... 
00:00:00.00.000 
00:00:00.00.000 
00:00:00.01.160 
00:00:00.01.160 
... 

Pas particulièrement utile, mais il est. Maintenant, si vous cherchez à faire quelque chose de similaire dans Chaussures, essayez this tutorial qui est très similaire.

2

Je crois que vous avez trouvé l'exemple sur this site

Je répète ce qui est déjà sur le site, mais vous manque:

require 'tk' 

ainsi que le code d'initialisation:

def initialize 
     root = TkRoot.new { title 'Tk Stopwatch' } 

     menu_spec = [ 
        [ 
         ['Program'], 
         ['Start', lambda { start } ], 
         ['Stop', lambda { stop } ], 
         ['Exit', lambda { exit } ] 
        ], 
        [ 
         ['Reset'], ['Reset Stopwatch', lambda { reset } ] 
        ] 
        ] 

     @menubar = TkMenubar.new(root, menu_spec, 'tearoff' => false) 
     @menubar.pack('fill'=>'x', 'side'=>'top') 

     @myfont = TkFont.new('size' => 16, 'weight' => 'bold') 

     @mylabel = TkLabel.new(root) 
     @mylabel.configure('text' => '00:00:00.0', 'font' => @myfont) 
     @mylabel.pack('padx' => 10, 'pady' => 10) 
     @mybutton = TkButton.new(root) 
     @mybutton.configure('text' => 'Start') 
     @mybutton.command { start } 
     @mybutton.pack('side'=>'left', 'fill' => 'both') 


     @timer = TkAfter.new(1, -1, proc { tick }) 

     Tk.mainloop 
     end 
    end 

    Stopwatch.new 

Je vous suggère de lire le reste de the site pour comprendre ce qui se passe tout.

+0

Oui, je le sais. Je veux utiliser des chaussures à la place et essayais de le convertir en tant que tel. Je préfèrerais de préférence retourner quelque chose, même dans le terminal. – danhere

1

Je cherchais une classe de montre d'arrêt rapide et sale pour éviter le codage tel et suis tombé sur le site où le code original a été publié et ce site ainsi. En fin de compte, j'ai modifié le code jusqu'à ce qu'il rencontre ce que je pense que je recherchais à l'origine. Au cas où quelqu'un serait intéressé, la version à laquelle j'ai abouti est la suivante (bien que je doive encore l'appliquer dans l'application que je suis en train de mettre à jour et pour laquelle je veux utiliser cette fonctionnalité).

# REFERENCES 
#  1. http://stackoverflow.com/questions/858970/how-to-get-a-stopwatch-program-running 
#  2. http://codeidol.com/other/rubyckbk/User-Interface/Creating-a-GUI-Application-with-Tk/ 
#  3. http://books.google.com.au/books?id=bJkznhZBG6gC&pg=PA806&lpg=PA806&dq=ruby+stopwatch+class&source=bl&ots=AlH2e7oWWJ&sig=KLFR-qvNfBfD8WMrUEbVqMbN_4o&hl=en&ei=WRjOTbbNNo2-uwOkiZGwCg&sa=X&oi=book_result&ct=result&resnum=8&ved=0CEsQ6AEwBw#v=onepage&q=ruby%20stopwatch%20class&f=false 
#  4. http://4loc.wordpress.com/2008/09/24/formatting-dates-and-floats-in-ruby/ 


module Utilities 
    class StopWatch 
    def new() 
     @watch_start_time = nil   #Time (in seconds) when the stop watch was started (i.e. the start() method was called). 
     @lap_start_time = nil   #Time (in seconds) when the current lap started. 
    end #def new 


    def start() 
     myCurrentTime = Time.now()  #Current time in (fractional) seconds since the Epoch (January 1, 1970 00:00 UTC) 

     if (!running?) then  
     @watch_start_time = myCurrentTime   
     @lap_start_time = @watch_start_time 
     end #if 

     myCurrentTime - @watch_start_time; 
    end #def start 


    def lap_time_seconds() 
     myCurrentTime = Time.now() 
     myLapTimeSeconds = myCurrentTime - @lap_start_time 
     @lap_start_time = myCurrentTime 
     myLapTimeSeconds 
    end #def lap_time_seconds 


    def stop() 
     myTotalSecondsElapsed = Time.now() - @watch_start_time 
     @watch_start_time = nil 

     myTotalSecondsElapsed 
    end #def stop 


    def running?() 
     [email protected]_start_time.nil? 
    end #def 
    end #class StopWatch 
end #module Utilities 






def kill_time(aRepeatCount) 
    aRepeatCount.times do 
    #just killing time 
    end #do 
end #def kill_time 



elapsed_time_format_string = '%.3f' 

myStopWatch = Utilities::StopWatch.new() 
puts 'total time elapsed: ' + elapsed_time_format_string % myStopWatch.start() + ' seconds' 

kill_time(10000000) 
puts 'lap time:   ' + elapsed_time_format_string % myStopWatch.lap_time_seconds() + ' seconds' 

kill_time(20000000) 
puts 'lap time:   ' + elapsed_time_format_string % myStopWatch.lap_time_seconds() + ' seconds' 

kill_time(30000000) 
puts 'lap time:   ' + elapsed_time_format_string % myStopWatch.lap_time_seconds() + ' seconds' 
puts 'total time elapsed: ' + elapsed_time_format_string % myStopWatch.stop() + ' seconds' 
0

simple script chronomètre:

# pass the number of seconds as the parameter 

seconds = eval(ARGV[0]).to_i 
start_time = Time.now 

loop do 
    elapsed = Time.now - start_time 
    print "\e[D" * 17 
    print "\033[K" 

    if elapsed > seconds 
    puts "Time's up!" 
    exit 
    end 

    print Time.at(seconds - elapsed).utc.strftime('%H:%M:%S.%3N') 
    sleep(0.05) 
end 

courir comme dans votre terminal (pour marquer un tour, appuyez simplement sur Entrée):

# 10 is the number of seconds 
ruby script.rb 10 
# you can even do this: 
ruby script.rb "20*60" # 20 minutes