Last active
December 7, 2021 02:47
-
-
Save LaPingvino/8b3ad674e2643a2f8b47c69ccf8a1a22 to your computer and use it in GitHub Desktop.
Tic Tac Toe in Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const stdout = std.io.getStdOut().writer(); | |
const stdin = std.io.getStdIn().reader(); | |
const print = stdout.print; | |
const trit = enum(u2) { e, x, o, d }; | |
const field = [9]trit; | |
var inb: u8 = 0; | |
var play: u8 = 10; | |
var turnx = true; | |
var winner: trit = .e; | |
var board: field = .{ .e, .e, .e, .e, .e, .e, .e, .e, .e }; | |
fn win(f: field, who: trit) bool { | |
const check = .{ | |
.{ 0, 1, 2 }, | |
.{ 3, 4, 5 }, | |
.{ 6, 7, 8 }, | |
.{ 0, 4, 8 }, | |
.{ 6, 4, 2 }, | |
.{ 0, 3, 6 }, | |
.{ 1, 4, 7 }, | |
.{ 2, 5, 8 }, | |
}; | |
inline for (check) |c| { | |
if (f[c[0]] == who and f[c[1]] == who and f[c[2]] == who) return true; | |
} | |
return false; | |
} | |
fn showfield(f: field) void { | |
for (f) |c, i| { | |
if (c == .e) print("{d}", .{i}) catch unreachable | |
else if (c == .x) print("x", .{}) catch unreachable | |
else if (c == .o) print("o", .{}) catch unreachable; | |
if (i % 3 == 2) print("\n", .{}) catch unreachable; | |
} | |
} | |
pub fn main() !void { | |
var i: u8 = 0; | |
while (winner == .e) { | |
showfield(board); | |
play = 10; // guarantee that the while loop will run at least once | |
var turns = if (turnx) "x" else "o"; | |
try print("Give a number for {s} to play on: ", .{turns}); | |
while (play > 8) { // discard everything that is not a valid board number | |
inb = try stdin.readByte(); | |
play = inb -% '0'; // convert ascii/utf-8 to number | |
} | |
while (inb != '\n') { // don't permit inputting the whole game at once | |
inb = try stdin.readByte(); | |
} | |
if (board[play] == .e) { | |
if (turnx) board[play] = .x | |
else board[play] = .o; | |
turnx = !turnx; | |
} | |
i += 1; | |
if (i > 8) { // last turn, if the last turn makes a win, the last check should overwrite it | |
winner = .d; | |
} | |
for (std.enums.values(trit)) |t| { | |
if (win(board, t)) winner = t; | |
} | |
} | |
try switch (winner) { | |
.x => print("x has won!\n", .{}), | |
.o => print("o has won!\n", .{}), | |
.d => print("it's a draw!\n", .{}), | |
.e => unreachable, | |
}; | |
showfield(board); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment