Advertisement
Guest User

tic-tac-toe.zig

a guest
May 17th, 2020
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. const std = @import("std");
  2. const warn = std.debug.warn;
  3.  
  4. var board = [_]u8{'_'} ** 9;
  5.  
  6. fn askUserInput() !void {
  7. const stdin = std.io.getStdIn().inStream();
  8. while (true) {
  9. warn("Your turn, choose your move:\n", .{});
  10. const player_move = try stdin.readIntNative(u8);
  11. if (player_move >= '1' and player_move <= '9') {
  12. const board_field = player_move - '0' - 1;
  13. if (board[board_field] != '_') {
  14. const cell_value = [1:0]u8{board[board_field]};
  15. warn("Wrong board position, this cell is already {}\n", .{cell_value});
  16. } else {
  17. board[board_field] = 'O';
  18. return;
  19. }
  20. } else {
  21. warn("Wrong number, please write number from 1 to 9\n", .{});
  22. }
  23. }
  24. }
  25.  
  26. pub fn main() !void {
  27. // Pressing "a" and then Enter, which is invalid input renders this:
  28. //
  29. // Wrong number, please write number from 1 to 9
  30. // Your turn, choose your move:
  31. // Wrong number, please write number from 1 to 9
  32. // Your turn, choose your move:
  33. //
  34. // Why does it render these messages twice? Pressing Enter
  35. // without "a" renders it just once.
  36. try askUserInput();
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement