Add all the A tasks

This commit is contained in:
Ingy döt Net 2013-04-10 14:58:50 -07:00
parent 2dd7375f96
commit 051504d65b
1608 changed files with 18584 additions and 0 deletions

View file

@ -0,0 +1,3 @@
Animation is the foundation of a great many parts of graphical user interfaces, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Create a window containing the string "<code>Hello World! </code>" (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the text, it should reverse its direction.

View file

@ -0,0 +1,6 @@
---
category:
- GUI
note: Temporal media
requires:
- Graphics

View file

@ -0,0 +1,21 @@
//create the text box
var textBox:TextField = new TextField();
addChild(textBox);
var text = "Hello, World! ";
var goingRight = true;
//modify the string and update it in the text box
function animate(e:Event)
{
if(goingRight)
text = text.slice(text.length-1,text.length) + text.slice(0, text.length - 1);
else
text = text.slice(1) + text.slice(0,1);
textBox.text = text;
}
//event handler to perform the animation
textBox.addEventListener(Event.ENTER_FRAME, animate);
//event handler to register clicks
textBox.addEventListener(MouseEvent.MOUSE_DOWN, function(){goingRight = !goingRight;});

View file

@ -0,0 +1,92 @@
with Gtk.Main;
with Gtk.Handlers;
with Gtk.Label;
with Gtk.Button;
with Gtk.Window;
with Glib.Main;
procedure Animation is
Scroll_Forwards : Boolean := True;
package Button_Callbacks is new Gtk.Handlers.Callback
(Gtk.Button.Gtk_Button_Record);
package Label_Timeout is new Glib.Main.Generic_Sources
(Gtk.Label.Gtk_Label);
package Window_Callbacks is new Gtk.Handlers.Return_Callback
(Gtk.Window.Gtk_Window_Record, Boolean);
-- Callback for click event
procedure On_Button_Click
(Object : access Gtk.Button.Gtk_Button_Record'Class);
-- Callback for delete event
function On_Main_Window_Delete
(Object : access Gtk.Window.Gtk_Window_Record'Class)
return Boolean;
function Scroll_Text (Data : Gtk.Label.Gtk_Label) return Boolean;
procedure On_Button_Click
(Object : access Gtk.Button.Gtk_Button_Record'Class)
is
pragma Unreferenced (Object);
begin
Scroll_Forwards := not Scroll_Forwards;
end On_Button_Click;
function On_Main_Window_Delete
(Object : access Gtk.Window.Gtk_Window_Record'Class)
return Boolean
is
pragma Unreferenced (Object);
begin
Gtk.Main.Main_Quit;
return True;
end On_Main_Window_Delete;
function Scroll_Text (Data : Gtk.Label.Gtk_Label) return Boolean is
Text : constant String := Gtk.Label.Get_Text (Data);
begin
if Scroll_Forwards then
Gtk.Label.Set_Text
(Label => Data,
Str => Text (Text'First + 1 .. Text'Last) & Text (Text'First));
else
Gtk.Label.Set_Text
(Label => Data,
Str => Text (Text'Last) & Text (Text'First .. Text'Last - 1));
end if;
return True;
end Scroll_Text;
Main_Window : Gtk.Window.Gtk_Window;
Text_Button : Gtk.Button.Gtk_Button;
Scrolling_Text : Gtk.Label.Gtk_Label;
Timeout_ID : Glib.Main.G_Source_Id;
pragma Unreferenced (Timeout_ID);
begin
Gtk.Main.Init;
Gtk.Window.Gtk_New (Window => Main_Window);
Gtk.Label.Gtk_New (Label => Scrolling_Text, Str => "Hello World! ");
Gtk.Button.Gtk_New (Button => Text_Button);
Gtk.Button.Add (Container => Text_Button, Widget => Scrolling_Text);
Button_Callbacks.Connect
(Widget => Text_Button,
Name => "clicked",
Marsh => Button_Callbacks.To_Marshaller (On_Button_Click'Access));
Timeout_ID :=
Label_Timeout.Timeout_Add
(Interval => 125,
Func => Scroll_Text'Access,
Data => Scrolling_Text);
Gtk.Window.Add (Container => Main_Window, Widget => Text_Button);
Window_Callbacks.Connect
(Widget => Main_Window,
Name => "delete_event",
Marsh => Window_Callbacks.To_Marshaller (On_Main_Window_Delete'Access));
Gtk.Window.Show_All (Widget => Main_Window);
Gtk.Main.Main;
end Animation;

View file

@ -0,0 +1,15 @@
SetTimer, Animate ; Timer runs every 250 ms.
String := "Hello World "
Gui, Add, Text, vS gRev, %String%
Gui, +AlwaysOnTop -SysMenu
Gui, Show
Return
Animate:
String := (!Reverse) ? (SubStr(String, 0) . Substr(String, 1, StrLen(String)-1)) : (SubStr(String, 2) . SubStr(String, 1, 1))
GuiControl,,S, %String%
return
Rev: ; Runs whenever user clicks on the text control
Reverse := !Reverse
return

View file

@ -0,0 +1,72 @@
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
// since we shift a whole character per time, it's better to use
// a monospace font, so that the shifting seems done at the same pace
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}

View file

@ -0,0 +1,33 @@
(import '[javax.swing JFrame JLabel])
(import '[java.awt.event MouseAdapter])
(def text "Hello World! ")
(def text-ct (count text))
(def rotations
(vec
(take text-ct
(map #(apply str %)
(partition text-ct 1 (cycle text))))))
(def pos (atom 0)) ;position in rotations vector being displayed
(def dir (atom 1)) ;direction of next position (-1 or 1)
(def label (JLabel. text))
(.addMouseListener label
(proxy [MouseAdapter] []
(mouseClicked [evt] (swap! dir -))))
(defn animator []
(while true
(Thread/sleep 100)
(swap! pos #(-> % (+ @dir) (mod text-ct)))
(.setText label (rotations @pos))))
(doto (JFrame.)
(.add label)
(.pack)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true))
(future-call animator) ;simple way to run animator on a separate thread

View file

@ -0,0 +1,26 @@
import Graphics.HGL.Units (Time, Point, Size, )
import Graphics.HGL.Draw.Monad (Graphic, )
import Graphics.HGL.Draw.Text
import Graphics.HGL.Draw.Font
import Graphics.HGL.Window
import Graphics.HGL.Run
import Graphics.HGL.Utils
import Control.Exception (bracket, )
runAnim = runGraphics $
bracket
(openWindowEx "Basic animation task" Nothing (250,50) DoubleBuffered (Just 110))
closeWindow
(\w -> do
f <- createFont (64,28) 0 False False "courier"
let loop t dir = do
e <- maybeGetWindowEvent w
let d = case e of
Just (Button _ True False) -> -dir
_ -> dir
t' = if d == 1 then last t : init t else tail t ++ [head t]
setGraphic w (withFont f $ text (5,10) t') >> getWindowTick w
loop t' d
loop "Hello world ! " 1 )

View file

@ -0,0 +1 @@
*Main> runAnim

View file

@ -0,0 +1,59 @@
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Rotate extends JFrame {
String text = "Hello World! ";
JLabel label = new JLabel(text);
boolean rotRight = true;
int startIdx = 0;
public Rotate() {
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
rotRight = !rotRight;
}
});
add(label);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
final Rotate rot = new Rotate();
TimerTask task = new TimerTask() {
public void run() {
if (rot.rotRight) {
rot.startIdx++;
if (rot.startIdx >= rot.text.length()) {
rot.startIdx -= rot.text.length();
}
} else {
rot.startIdx--;
if (rot.startIdx < 0) {
rot.startIdx += rot.text.length();
}
}
rot.label.setText(getRotatedText(rot.text, rot.startIdx));
}
};
Timer timer = new Timer(false);
timer.schedule(task, 0, 500);
}
public static String getRotatedText(String text, int startIdx) {
String ret = "";
int i = startIdx;
do {
ret += text.charAt(i) + "";
i++;
i = i % text.length();
} while (i != startIdx);
return ret;
}
}

View file

@ -0,0 +1,23 @@
<svg xmlns="http://www.w3.org/2000/svg"
width="100" height="40">
<script type="text/javascript">
function animate(element) {
var textNode = element.childNodes[0]; // assuming no other children
var text = textNode.data;
var reverse = false;
element.onclick = function () { reverse = !reverse; };
setInterval(function () {
if (reverse)
text = text.substring(1) + text[0];
else
text = text[text.length - 1] + text.substring(0, text.length - 1);
textNode.data = text;
}, 100);
}
</script>
<rect width="100" height="40" fill="yellow"/>
<text x="2" y="20" onload="animate(this);">Hello World! </text>
</svg>

After

Width:  |  Height:  |  Size: 802 B

View file

@ -0,0 +1,11 @@
use XUL::Gui;
my $dir = '(.+)(.)';
interval {
ID(lbl)->value =~ s/$dir/$2$1/;
} 75;
display Label
id => 'lbl',
value => "Hello World! ",
onclick => sub {toggle $dir => '(.+)(.)', '(.)(.+)'};

View file

@ -0,0 +1,14 @@
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(prin "^[[?9h") # Mouse reporting on
(setq Dir 1 Text (chop "Hello World! "))
(loop
(prin (do Dir (rot Text)))
(when (= "^[" (key 200))
(key) (key)
(when (= " " (key)) # Left button
(setq Dir (if (= 1 Dir) 12 1)) )
(key) (key) )
(do (length Text) (prin "^H")) )

View file

@ -0,0 +1,18 @@
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
(one *Dir)
(de start ()
(app)
(action
(html 0 "Animation" "@lib.css" NIL
(form NIL
(gui '(+Button)
'(pack (do *Dir (rot '`(chop "Hello World! "))))
'(setq *Dir (if (= 1 *Dir) 12 1)) )
(gui '(+Click +Auto +Button) 400 'This 1000 "Start") ) ) ) )
(server 8080 "!start")
(wait)

View file

@ -0,0 +1,22 @@
#!ersatz/pil
(setq
Dir 1
Text (chop "Hello World! ")
Frame (java "javax.swing.JFrame" T "Animation")
Label (java "javax.swing.JLabel" T (pack Text)) )
(java Label 'addMouseListener
(interface "java.awt.event.MouseListener"
'mouseClicked '((Ev) (setq Dir (if (= 1 Dir) 12 1)))
'mouseEntered nil
'mouseExited nil
'mousePressed nil
'mouseReleased nil ) )
(java Frame 'add Label)
(java Frame 'pack)
(java Frame 'setVisible T)
(loop
(wait 200)
(java Label 'setText (pack (do Dir (rot Text)))) )

View file

@ -0,0 +1,74 @@
:- use_module(library(pce)).
animation :-
new(D, window('Animation')),
new(Label, label(hello, 'Hello world ! ')),
send(D, display, Label, point(1,10)),
new(@animation, animation(Label)),
send(D, recogniser,
new(_G, my_click_gesture(left, ''))),
send(D, done_message, and(message(@animation, free),
message(@receiver, destroy))),
send(D, open),
send(@animation?mytimer, start).
:- pce_begin_class(animation(label), object).
variable(label, object, both, "Display window").
variable(delta, object, both, "increment of the angle").
variable(mytimer, timer, both, "timer of the animation").
initialise(P, W:object) :->
"Creation of the object"::
send(P, label, W),
send(P, delta, to_left),
send(P, mytimer, new(_, timer(0.5,message(P, anim_message)))).
% method called when the object is destroyed
% first the timer is stopped
% then all the resources are freed
unlink(P) :->
send(P?mytimer, stop),
send(P, send_super, unlink).
% message processed by the timer
anim_message(P) :->
get(P, label, L),
get(L, selection, S),
get(P, delta, Delta),
compute(Delta, S, S1),
new(A, name(S1)),
send(L, selection, A).
:- pce_end_class.
:- pce_begin_class(my_click_gesture, click_gesture,
"Click in a window").
class_variable(button, button_name, left,
"By default click with left button").
terminate(G, Ev:event) :->
send(G, send_super, terminate, Ev),
get(@animation, delta, D),
( D = to_left -> D1 = to_right; D1 = to_left),
send(@animation, delta, D1).
:- pce_end_class.
% compute next text to be dispalyed
compute(to_right, S, S1) :-
get(S, size, Len),
Len1 is Len - 1,
get(S, sub, Len1, Str),
get(S, delete_suffix, Str, V),
get(Str, append, V, S1).
compute(to_left, S, S1) :-
get(S, sub, 0, 1, Str),
get(S, delete_prefix, Str, V),
get(V, append, Str, S1).

View file

@ -0,0 +1,55 @@
import pygame, sys
from pygame.locals import *
pygame.init()
YSIZE = 40
XSIZE = 150
TEXT = "Hello World! "
FONTSIZE = 32
LEFT = False
RIGHT = True
DIR = RIGHT
TIMETICK = 180
TICK = USEREVENT + 2
TEXTBOX = pygame.Rect(10,10,XSIZE,YSIZE)
pygame.time.set_timer(TICK, TIMETICK)
window = pygame.display.set_mode((XSIZE, YSIZE))
pygame.display.set_caption("Animation")
font = pygame.font.SysFont(None, FONTSIZE)
screen = pygame.display.get_surface()
def rotate():
index = DIR and -1 or 1
global TEXT
TEXT = TEXT[index:]+TEXT[:index]
def click(position):
if TEXTBOX.collidepoint(position):
global DIR
DIR = not DIR
def draw():
surface = font.render(TEXT, True, (255,255,255), (0,0,0))
global TEXTBOX
TEXTBOX = screen.blit(surface, TEXTBOX)
def input(event):
if event.type == QUIT:
sys.exit(0)
elif event.type == MOUSEBUTTONDOWN:
click(event.pos)
elif event.type == TICK:
draw()
rotate()
while True:
input(pygame.event.wait())
pygame.display.flip()

View file

@ -0,0 +1,23 @@
import Tkinter as tki
def scroll_text(s, how_many):
return s[how_many:] + s[:how_many]
direction = 1
tk = tki.Tk()
var = tki.Variable(tk)
def mouse_handler(point):
global direction
direction *= -1
def timer_handler():
var.set(scroll_text(var.get(),direction))
tk.after(125, timer_handler)
var.set('Hello, World! ')
tki.Label(tk, textvariable=var).pack()
tk.bind("<Button-1>", mouse_handler)
tk.after(125, timer_handler)
tk.title('Python Animation')
tki.mainloop()

View file

@ -0,0 +1,39 @@
rotate_string <- function(x, forwards)
{
   nchx <- nchar(x)
   if(forwards)
   {                                  
      paste(substr(x, nchx, nchx), substr(x, 1, nchx - 1), sep = "")
   } else
   {                                                          
      paste(substr(x, 2, nchx), substr(x, 1, 1), sep = "")
   }
}
handle_rotate_label <- function(obj, interval = 100)
{
  addHandlerIdle(obj,
    handler = function(h, ...)
    {
       svalue(obj) <- rotate_string(svalue(obj), tag(obj, "forwards"))
    },
    interval = interval
  )
}
handle_change_direction_on_click <- function(obj)
{
  addHandlerClicked(obj,
    handler = function(h, ...)
    {
      tag(h$obj, "forwards") <- !tag(h$obj, "forwards")
    }
  )
}
library(gWidgets)
library(gWidgetstcltk) #or library(gWidgetsRGtk2) or library(gWidgetsrJava)             
lab <- glabel("Hello World! ", container = gwindow())  
tag(lab, "forwards") <- TRUE
handle_rotate_label(lab)
handle_change_direction_on_click(lab)

View file

@ -0,0 +1,40 @@
#lang racket/gui
;; One of 'left or 'right
(define direction 'left)
;; Set up the GUI
(define animation-frame%
(class frame%
(super-new [label "Animation"])
;; reverse direction on a click
(define/override (on-subwindow-event win evt)
(when (send evt button-down?)
(set! direction
(if (eq? direction 'left)
'right
'left))))))
(define frame (new animation-frame%))
(define msg (new message%
[label "Hello World! "]
[parent frame]))
;; Timer callback to adjust the message
(define (callback)
(define old-label (send msg get-label))
(define len (string-length old-label))
(if (eq? direction 'left)
(send msg set-label
(string-append (substring old-label 1)
(substring old-label 0 1)))
(send msg set-label
(string-append (substring old-label (- len 1) len)
(substring old-label 0 (- len 1))))))
;; Set a timer and go
(define timer (new timer%
[notify-callback callback]
[interval 500]))
(send frame show #t)

View file

@ -0,0 +1,27 @@
require 'tk'
$str = TkVariable.new("Hello World! ")
$dir = :right
def animate
$str.value = shift_char($str.value, $dir)
$root.after(125) {animate}
end
def shift_char(str, dir)
case dir
when :right then str[-1,1] + str[0..-2]
when :left then str[1..-1] + str[0,1]
end
end
$root = TkRoot.new("title" => "Basic Animation")
TkLabel.new($root) do
textvariable $str
font "Courier 14"
pack {side 'top'}
bind("ButtonPress-1") {$dir = {:right=>:left,:left=>:right}[$dir]}
end
animate
Tk.mainloop

View file

@ -0,0 +1,11 @@
Shoes.app do
@direction = 1
@label = para "Hello World! ", :family => 'monospace'
click {|button, left, top| @direction *= -1 if button == 1}
animate(8) do |f|
t = @label.text
@label.text = @direction > 0 ? t[-1] + t[0..-2] : t[1..-1] + t[0]
end
end

View file

@ -0,0 +1,32 @@
import scala.actors.Actor.{actor, loop, reactWithin, exit}
import scala.actors.TIMEOUT
import scala.swing.{SimpleSwingApplication, MainFrame, Label}
import scala.swing.event.MouseClicked
case object Revert
object BasicAnimation extends SimpleSwingApplication {
val label = new Label("Hello World! ")
val rotator = actor {
var goingRight = true
loop {
reactWithin(250 /*ms*/) {
case Revert => goingRight = !goingRight
case TIMEOUT =>
if (goingRight)
label.text = label.text.last + label.text.init
else
label.text = label.text.tail + label.text.head
case unknown => println("Unknown message "+unknown); exit()
}
}
}
def top = new MainFrame {
title = "Basic Animation"
contents = label
}
listenTo(label.mouse.clicks) // use "Mouse" instead of "mouse" on Scala 2.7
reactions += {
case _ : MouseClicked => rotator ! Revert
}
}

View file

@ -0,0 +1,20 @@
package require Tk
set s "Hello World! "
set dir 0
# Periodic animation callback
proc animate {} {
global dir s
if {$dir} {
set s [string range $s 1 end][string index $s 0]
} else {
set s [string index $s end][string range $s 0 end-1]
}
# We will run this code ~8 times a second (== 125ms delay)
after 125 animate
}
# Make the label (constant width font looks better)
pack [label .l -textvariable s -font {Courier 14}]
# Make a mouse click reverse the direction
bind .l <Button-1> {set dir [expr {!$dir}]}
# Start the animation
animate