2020 UPDATE: Due to tk being removed from the Ruby standard library and due to changes on macOS (which I primarily use), this library is no longer as easy to use for beginners as it once was. If you can come up with solutions to resolve this issue, I am all ears.
2021 UPDATE: I have not had to time to spend updating this project but some kind people in the issue tracker have suggestions on installing Tk in the modern age. See #5 (comment)
gem install trtl
Trtl is a simple 'turtle' system inspired by Python's turtle.py. It provides simple turtle drawing capabilities in Ruby, even if you're just at an IRB prompt. It leans on Tk (which used to be in Ruby's standard library but is now an external gem).
If Trtl detects you're in an IRb or Pry session, it'll automatically make turtle methods available directly at the prompt. For example:
$ irb
> require 'trtl'
> forward 100
# At this point, a window appears with the turtle
If you wish to use Trtl from a regular Ruby script, you have a few options. You can create a Trtl instance and use it directly:
require 'trtl'
t = Trtl.new
10.times { t.left(24); t.forward(30); t.ensure_drawn }
t.wait
You can use Trtl's run
method to use it in a more interactive fashion:
Trtl.new.run { 10.times { left(24); forward(30); ensure_drawn } }
Or you can include InteractiveTurtle and get a similar effect as if you were in IRb:
include InteractiveTurtle
10.times { left(24); forward(30) }
Note: Using InteractiveTurtle makes drawing slower as it ensures all graphics are drawn after every action (as necessary for IRb use).
Only a small number of commands are currently implemented, but they're enough for the major actions:
title(title_name)
forward(distance)
- aliased asfd
back(distance)
- aliased asbk
andbackward
left(angle)
- aliased aslt
right(angle)
- aliased asrt
pen_up
- aliased aspu
andup
andpenup
pen_down
- aliased aspd
anddown
andpendown
color(color_name)
- aliased aspencolor
move(x, y)
- aliased asgoto
position
- aliased aspos
circle(radius, extent = 360, steps = 360)
dot(size)
- draws a dot, defaults to a sensible size but you can supply if you wantis_drawing?
width(width_in_pixels)
The examples in the examples
folder should be reasonably illustrative. If you
try any of them, try example4.rb
- it renders an awesome looking tree.
- turtle.py for inspiration (in the 'Ruby needs this!' sense)
- Some of the examples taken from examples for an earlier Ruby turtle found at http://www.rubyquiz.com/quiz104.html
Copyright (c) 2012-2017 Peter Cooper (other than minor parts of some samples.)
MIT licensed. See LICENSE.md
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;