ziglings/exercises/047_methods.zig

103 lines
2.7 KiB
Zig
Raw Normal View History

2021-02-27 16:52:57 -05:00
//
// Help! Evil alien creatures have hidden eggs all over the Earth
// and they're starting to hatch!
//
// Before you jump into battle, you'll need to know four things:
//
// 1. You can attach functions to structs:
//
// const Foo = struct{
// pub fn hello() void {
// std.debug.print("Foo says hello!\n", .{});
// }
// };
2021-02-27 16:52:57 -05:00
//
// 2. A function that is a member of a struct is a "method" and is
// called with the "dot syntax" like so:
//
// Foo.hello();
//
// 3. The NEAT feature of methods is the special parameter named
// "self" that takes an instance of that type of struct:
//
// const Bar = struct{
// number: u32,
//
// pub fn printMe(self: Bar) void {
2021-02-27 16:52:57 -05:00
// std.debug.print("{}\n", .{self.number});
// }
// };
2021-02-27 16:52:57 -05:00
//
2021-08-30 17:55:10 -04:00
// (Actually, you can name the first parameter anything, but
// please follow convention and use "self".)
//
2021-02-27 16:52:57 -05:00
// 4. Now when you call the method on an INSTANCE of that struct
// with the "dot syntax", the instance will be automatically
// passed as the "self" parameter:
//
// var my_bar = Bar{ .number = 2000 };
2021-02-27 16:52:57 -05:00
// my_bar.printMe(); // prints "2000"
//
// Okay, you're armed.
//
// Now, please zap the alien structs until they're all gone or
// Earth will be doomed!
//
const std = @import("std");
// Look at this hideous Alien struct. Know your enemy!
const Alien = struct {
health: u8,
// We hate this method:
pub fn hatch(strength: u8) Alien {
return Alien{
.health = strength * 5,
};
}
};
// Your trusty weapon. Zap those aliens!
const HeatRay = struct {
damage: u8,
2021-02-27 16:52:57 -05:00
// We love this method:
pub fn zap(self: *HeatRay, alien: *Alien) void {
alien.health -= if (self.damage >= alien.health) alien.health else self.damage;
2021-02-27 16:52:57 -05:00
}
};
pub fn main() void {
// Look at all of these aliens of various strengths!
var aliens = [_]Alien{
Alien.hatch(2),
Alien.hatch(1),
Alien.hatch(3),
Alien.hatch(3),
Alien.hatch(5),
Alien.hatch(3),
};
var aliens_alive = aliens.len;
var heat_ray = HeatRay{ .damage = 7 }; // We've been given a heat ray weapon.
2021-02-27 16:52:57 -05:00
// We'll keep checking to see if we've killed all the aliens yet.
while (aliens_alive > 0) {
aliens_alive = 0;
// Loop through every alien...
for (aliens) |*alien| {
2022-07-31 11:32:51 -04:00
// *** Zap the alien with the heat ray here! ***
???.zap(???);
2021-02-27 16:52:57 -05:00
// If the alien's health is still above 0, it's still alive.
if (alien.health > 0) aliens_alive += 1;
}
std.debug.print("{} aliens. ", .{aliens_alive});
}
std.debug.print("Earth is saved!\n", .{});
}