tinyevil

Untitled

Dec 20th, 2018
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // The "struct" keyword establishes a namespace and a new type name
  2. // This block directly describes the layout of the type
  3. // I don't want to mix data with the behavior so this block is
  4. // strictly for the instance fields.
  5. struct Turtle{
  6.     var x y: f32;
  7.     var heading: f32;
  8.     var shell_color: u32;
  9. }
  10.  
  11. // The "implementation" block lets you put the stuff into the type's namespace
  12. // This stuff will be accessible with the `Turtle.name` syntax and is also
  13. // allowed to access private stuff within the namespace, like private fields.
  14. implementation Turtle{
  15.     // 'ref' is lifetime-checked non-nullable pointer
  16.     // functions return void by default
  17.     function advance(self: ref Turtle){
  18.         // '.' lets us access Turtle's fields here because ref T implements
  19.         // proxy[T] protocol - so when a name lookup fails on the `ref Turtle`
  20.         // type itself, it continues to search on the `T`
  21.         self.x += cos(self.heading);
  22.         self.y += sin(self.heading);
  23.     }
  24.    
  25.     function rotate(self: ref Turtle, delta: f32){
  26.         self.heading += delta;
  27.     }
  28.    
  29.     // 'private' means private to the namespace - it is not possible to invoke
  30.     // color_multiply from the outside
  31.     private function color_mix(first second: u32): u32{
  32.         // x `identifier` y lets you use a two-argument function as an infix operator
  33.         // and is in fact a syntactic sugar for identifier(x, y)
  34.         // all such operators are left-associative and have the same priority
  35.         var r1: u32 = (first `shr` 16) `bitand` 0xff;
  36.         var g1: u32 = (first `shr` 8) `bitand` 0xff;
  37.         var b1: u32 = (first `shr` 0) `bitand` 0xff;
  38.        
  39.         var r2: u32 = (second `shr` 16) `bitand` 0xff;
  40.         var g2: u32 = (second `shr` 8) `bitand` 0xff;
  41.         var b2: u32 = (second `shr` 0) `bitand` 0xff;
  42.        
  43.         var r: u32 = (r1 + r2) / 2;
  44.         var g: u32 = (g1 + g2) / 2;
  45.         var b: u32 = (b1 + b2) / 2;
  46.        
  47.         return (r `shl` 16) `bitor` (g `shl` 8) `bitor` (b `shl` 0);
  48.     }
  49.    
  50.     function breed(first second: ref Turtle): Turtle{
  51.         // constructor expression - struct name followed by JSON-like object
  52.         // creates a new instance of the type
  53.         return Turtle{
  54.             x: (first.x + second.x) / 2,
  55.             y: (first.y + second.y) / 2,
  56.             heading: (first.heading + second.heading) / 2,
  57.             shell_color: color_mix(first.shell_color, second.shell_color)
  58.         };
  59.     }
  60. }
Add Comment
Please, Sign In to add comment