C: The Programming Language

I learned to program in C.

Connect Four

Theft again; alas.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/*-- Constants --*/

/// How many pieces we're trying to connect
#define CONNECT 4

/// The minimum and maximum board dimensions
#define MIN_BOARD_DIMENSION 4
#define MAX_BOARD_WIDTH     9
#define MAX_BOARD_HEIGHT    16

/// The three cell types
#define CELL_EMPTY  '.'
#define CELL_RED    'R'
#define CELL_YELLOW 'Y'

/// The winner conditions
#define WINNER_NONE   0
#define WINNER_RED    1
#define WINNER_YELLOW 2

/// Whose turn is it?
#define TURN_RED    0
#define TURN_YELLOW 1


/*-- Function prototypes --*/

void assert_board_dimension(int dimension, int min, int max);
void initialise_board(void);
void play_game(void);
int  play_turn(int whose_turn);
int  check_winner(void);
int  check_line(int start_row, int start_col, int offset_row, int offset_col);

// provided for you:
bool is_board_full(void);
void print_board(void);


/*-- Global variables --*/

char board[MAX_BOARD_HEIGHT][MAX_BOARD_WIDTH];
int board_width;
int board_height;


/*-- Code --*/

int main(void) {
	printf("Enter board width: ");
	scanf("%d", &board_width);
	assert_board_dimension(board_width, MIN_BOARD_DIMENSION, MAX_BOARD_WIDTH);

	printf("Enter board height: ");
	scanf("%d", &board_height);
	assert_board_dimension(board_height, MIN_BOARD_DIMENSION, MAX_BOARD_HEIGHT);

	initialise_board();
	print_board();
	play_game();

	return 0;
}

/// Make sure the board dimensions we're
/// given fit within the correct bounds
void assert_board_dimension(int dimension, int min, int max) {
	if (dimension < min) {
		printf("Board dimension too small (min %d)\n", min);
		exit(1);
	}

	if (dimension > max) {
		printf("Board dimension too large (max %d)\n", max);
		exit(1);
	}
}

/// Initialise the board to all empty cells
void initialise_board(void) {
	for (int row = 0; row < board_height; row++) {
		for (int col = 0; col < board_width; col++) {
			board[row][col] = CELL_EMPTY;
		}
	}
}

/// The main game loop
void play_game(void) {
	int whose_turn = TURN_RED;
	int winner;

	// Play a single turn
	do {
		whose_turn = play_turn(whose_turn);
		print_board();
		winner = check_winner();
	} while (winner == WINNER_NONE && !is_board_full());

	// Either we have a winner, or the board is full!
	if (winner == WINNER_NONE) {
		printf("The game is a draw!\n");
	} else if (winner == WINNER_RED) {
		printf("Game over, Red wins!\n");
	} else {
		printf("Game over, Yellow wins!\n");
	}
}

/// Play a single turn!
/// This in sequence:
/// - Reads in the column to insert,
/// - Makes sure it is valid,
/// - Inserts the color into that column,
/// - Switches the turn to the next player.
int play_turn(int whose_turn) {
	if (whose_turn == TURN_RED)	printf("[RED] ");
	else                        printf("[YELLOW] ");
	printf("Choose a column: ");

	int target_col = 0;
	scanf("%d", &target_col);
	target_col--; // user input is 1-indexed
	if (target_col < 0 || target_col >= board_width) {
		printf("Invalid column\n");
		return whose_turn;
	}

	int target_row = board_height - 1;
	while (target_row >= 0 && board[target_row][target_col] != CELL_EMPTY) {
		target_row--;

		if (target_row < 0) {
			printf("No space in that column!\n");
			return whose_turn;
		}
	}

	if (whose_turn == TURN_RED) {
		board[target_row][target_col] = CELL_RED;
		return TURN_YELLOW;
	} else {
		board[target_row][target_col] = CELL_YELLOW;
		return TURN_RED;
	}
}

/// Checks if the game has a winner yet!
/// For each position on the board, the
/// loop will check vertical, horizontal,
/// North-East vertical, and
/// North-West vertical for a connection.
int check_winner(void) {
	for (int row = 0; row < board_height; row++) {
		for (int col = 0; col < board_width; col++) {
			int check;

			check = check_line(row, col, 1, 0);
			if (check != WINNER_NONE) return check;

			check = check_line(row, col, 0, 1);
			if (check != WINNER_NONE) return check;

			check = check_line(row, col, 1, 1);
			if (check != WINNER_NONE) return check;

			check = check_line(row, col, 1, -1);
			if (check != WINNER_NONE) return check;
		}
	}

	return WINNER_NONE;
}

/// Checks if a particular line represents
/// a connect 4!
/// It uses a start_row and start_col,
/// and then checks if there are 3 further
/// tokens of the same color, offsetting by
/// offset_row and offset_col each time.
int check_line(int start_row, int start_col, int offset_row, int offset_col) {

	//printf("Debug1: \n%d\n%d\n%d\n%d\n", start_row, start_col, offset_row, offset_col);
	char first_cell = board[start_row][start_col];
	if (first_cell == CELL_EMPTY) return WINNER_NONE;

	int row = start_row + offset_row;
	int col = start_col + offset_col;
	for (int i = 0; i < CONNECT - 1; i++) {
		if (row < 0 || col < 0) return WINNER_NONE;
		if (row >= board_height || col >= board_width) return WINNER_NONE;

		char cell = board[row][col];
		if (cell != first_cell) return WINNER_NONE;

		row += offset_row;
		col += offset_col;
	}

	if (first_cell == CELL_RED) return WINNER_RED;
	else						return WINNER_YELLOW;
}

/// Checks if the board is completely full
/// i.e. there is no free space for a turn.
/// This is the condition that causes a draw
bool is_board_full(void) {
	for (int row = 0; row < board_height; row++) {
		for (int col = 0; col < board_width; col++) {
			if (board[row][col] == CELL_EMPTY) return false;
		}
	}

	return true;
}

/// Print the board out to the terminal,
/// with numbers at the top to indicate
/// the column indicies.
void print_board(void) {
	printf("\n");

	for (int col = 0; col < board_width; col++) {
		printf("%d ", col + 1);
	}

	printf("\n");

	for (int row = 0; row < board_height; row++) {
		for (int col = 0; col < board_width; col++) {
			printf("%c ", board[row][col]);
		}

		printf("\n");
	}
}

Cryptography Code

Caesar

some of the code I've written is so stupid I tell you.

this one basically fires up a REPL with a argv[1] as the number of forward caesar cipher steps you want to take.

really not worth running.

#include <stdio.h>
#include <stdlib.h>

int upper(int character, int shift) {
	character += shift;
	if (character > 90) {
		character = (character-90)%26 + 64;
	}
	else if (character < 65) {
		character = (65-character)%26;
		if (character == 0) return 65;
		character = 91 - character;
	}
	return character;
}

int lower(int character, int shift) {
	character += shift;
	if (character > 122) {
		character = (character-122)%26 + 96;
	}
	else if (character < 97) {
		character = (97-character)%26;
		if (character == 0) return 97;
		character = 123 - character;
	}
	return character;
}


int main(int argc, char* argv[]) {
	int shift = atoi(argv[1]);
	int character = getchar();
	while (character != EOF) {
		if (character >= 'A' && character <= 'Z') {
			putchar(upper(character, shift));
		}
		else if (character >= 'a' && character <= 'z') {
			putchar(lower(character, shift));
		}
		else putchar(character);
		character = getchar();
	}
}

File XOR

#include <stdio.h>

int main(int argc, char *argv[])
{
    FILE *fi, *fo;
    char *cp;
    int c;

    if ((cp = argv[1]) && *cp!='\0') {
        if ((fi = fopen(argv[2], "rb")) != NULL) {
            if ((fo = fopen(argv[3], "wb")) != NULL) {
                while ((c = getc(fi)) != EOF) {
                    if (!*cp) cp = argv[1];
                    c ^= *(cp++);
                    putc(c,fo);
                }
                fclose(fo);
            }
            fclose(fi);
        }
    }
}

Minesweeper in C

I have no idea where I got this from, however I do plan on remaking Minesweeper for the Arcade in Java so having an existing implementation syntax highlighted and version controlled does not hurt.

#include <stdio.h>
#include <stdlib.h>

// Possible square states.
#define VISIBLE_SAFE    0
#define HIDDEN_SAFE     1
#define HIDDEN_MINE     2

// The size of the starting grid.
#define SIZE              8

// The possible command codes.
#define DETECT_ROW      1
#define DETECT_SQUARE   2
#define REVEAL_CROSS    3
#define GAME_MODE       4
#define FLAG_MINE       5
#define DEFUSE          6

// Add any extra #defines here.

void initialise_field(int minefield[SIZE][SIZE]);
void print_debug_minefield(int minefield[SIZE][SIZE]);

// Function prototypes
void print_minefield(int minefield[SIZE][SIZE]);
int count_adjacent_mines(int minefield[SIZE][SIZE], int row, int col);
void reveal_square(int minefield[SIZE][SIZE], int row, int col);
void reveal_cross(int minefield[SIZE][SIZE], int row, int col);
int check_win(int minefield[SIZE][SIZE]);
void flag_mine(int minefield[SIZE][SIZE], int row, int col);
int defuse_mine(int minefield[SIZE][SIZE], int row, int col);

// Print the minefield in a user-friendly format
void print_minefield(int minefield[SIZE][SIZE]) {
    printf("  0 1 2 3 4 5 6 7\n");
    for (int i = 0; i < SIZE; i++) {
        printf("%d ", i);
        for (int j = 0; j < SIZE; j++) {
            if (minefield[i][j] == VISIBLE_SAFE) {
                int count = count_adjacent_mines(minefield, i, j);
                printf("%d ", count);
            } else if (minefield[i][j] == HIDDEN_SAFE) {
                printf(". ");
            } else if (minefield[i][j] == HIDDEN_MINE) {
                printf("* ");
            }
        }
        printf("\n");
    }
}

// Count adjacent mines for a given square
int count_adjacent_mines(int minefield[SIZE][SIZE], int row, int col) {
    int count = 0;
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            int new_row = row + i;
            int new_col = col + j;
            if (new_row >= 0 && new_row < SIZE && new_col >= 0 && new_col < SIZE) {
                if (minefield[new_row][new_col] == HIDDEN_MINE) {
                    count++;
                }
            }
        }
    }
    return count;
}

// Reveal a single square
void reveal_square(int minefield[SIZE][SIZE], int row, int col) {
    if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
        return;
    }
    
    if (minefield[row][col] == HIDDEN_SAFE) {
        minefield[row][col] = VISIBLE_SAFE;
        if (count_adjacent_mines(minefield, row, col) == 0) {
            // Reveal adjacent squares if no mines nearby
            for (int i = -1; i <= 1; i++) {
                for (int j = -1; j <= 1; j++) {
                    reveal_square(minefield, row + i, col + j);
                }
            }
        }
    }
}

// Reveal a cross pattern
void reveal_cross(int minefield[SIZE][SIZE], int row, int col) {
    if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
        return;
    }
    
    reveal_square(minefield, row, col);
    reveal_square(minefield, row - 1, col);
    reveal_square(minefield, row + 1, col);
    reveal_square(minefield, row, col - 1);
    reveal_square(minefield, row, col + 1);
}

// Check if the game is won
int check_win(int minefield[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            if (minefield[i][j] == HIDDEN_SAFE) {
                return 0;  // Game not won yet
            }
        }
    }
    return 1;  // Game won
}

// Flag a mine
void flag_mine(int minefield[SIZE][SIZE], int row, int col) {
    if (row >= 0 && row < SIZE && col >= 0 && col < SIZE) {
        if (minefield[row][col] == HIDDEN_MINE) {
            minefield[row][col] = VISIBLE_SAFE;
        }
    }
}

// Attempt to defuse a mine
int defuse_mine(int minefield[SIZE][SIZE], int row, int col) {
    if (row >= 0 && row < SIZE && col >= 0 && col < SIZE) {
        if (minefield[row][col] == HIDDEN_MINE) {
            minefield[row][col] = VISIBLE_SAFE;
            return 1;  // Successfully defused
        }
    }
    return 0;  // Failed to defuse
}

int main(void) {
    int minefield[SIZE][SIZE];
    int num_mines;
    int game_over = 0;
    int command, row, col;

    initialise_field(minefield);
    printf("Welcome to minesweeper!\n");
    printf("How many mines? ");
    scanf("%d", &num_mines);

    printf("Enter pairs:\n");
    for (int i = 0; i < num_mines; i++) {
        scanf("%d %d", &row, &col);
        if (row >= 0 && row < SIZE && col >= 0 && col < SIZE) {
            minefield[row][col] = HIDDEN_MINE;
        }
    }

    printf("Game Started\n");
    print_debug_minefield(minefield);

    while (!game_over && scanf("%d %d %d", &command, &row, &col) == 3) {
        switch (command) {
            case DETECT_ROW:
                for (int j = 0; j < SIZE; j++) {
                    reveal_square(minefield, row, j);
                }
                break;
            case DETECT_SQUARE:
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        reveal_square(minefield, row + i, col + j);
                    }
                }
                break;
            case REVEAL_CROSS:
                reveal_cross(minefield, row, col);
                break;
            case FLAG_MINE:
                flag_mine(minefield, row, col);
                break;
            case DEFUSE:
                if (!defuse_mine(minefield, row, col)) {
                    printf("Game Over!\n");
                    game_over = 1;
                }
                break;
        }

        if (!game_over) {
            print_minefield(minefield);
            if (check_win(minefield)) {
                printf("Game Won!\n");
                game_over = 1;
            }
        }
    }

    return 0;
}

// Set the entire minefield to HIDDEN_SAFE.
void initialise_field(int minefield[SIZE][SIZE]) {
    int i = 0;
    while (i < SIZE) {
        int j = 0;
        while (j < SIZE) {
            minefield[i][j] = HIDDEN_SAFE;
            j++;
        }
        i++;
    }
}

// Print out the actual values of the minefield.
void print_debug_minefield(int minefield[SIZE][SIZE]) {
    int i = 0;
    while (i < SIZE) {
        int j = 0;
        while (j < SIZE) {
            printf("%d ", minefield[i][j]);
            j++;
        }
        printf("\n");
        i++;
    }
}

Miscellaneous Exercises over the years

Hexadecimal Converter

I think I made this for integration into Alfred. This needs to be refactored if you want to use it!

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#define N_BITS 16

// Function declarations
void change_base(int base, int user_num);
char *convert_to_binary(int16_t value);

// Convert number to any base (2-36)
void change_base(int base, int user_num)
{
    int i = 0;
    int j = 0;
    int raised, ceiling, floored;
    int length = snprintf(NULL, 0, "%d", base);
    char base_name[20] = "";
    char output[55] = "";
    char floored_str[32] = "";
    char alphabet[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    for (raised = pow(base,i); user_num % raised < user_num; i++) {
        raised = pow(base, i);
        ceiling = i - 1;
    }
    
    for (j = ceiling; j > -1; j--) {
        floored = floor(user_num / pow(base, j));
        user_num -= floored*pow(base, j); 
        sprintf(floored_str, "%d", floored);
        if (floored > 9) {
            sprintf(floored_str, "%c", alphabet[floored - 10]);
        }    
        strcat(output, floored_str);
    }
    
    if (base == 2) strcpy(base_name, "Binary");
    else if (base == 16) strcpy(base_name, "Hexadecimal");
    else snprintf(base_name, length + 1, "%d", base);
    
    printf("<items><item uid=\"%s\" arg=\"%s\"><title>%s</title><subtitle></subtitle><icon>icon.png</icon></item></items>", base_name, output, output);
}

// Convert number to 16-bit binary
char *convert_to_binary(int16_t value) {
    char *buffer = malloc((N_BITS + 1) * sizeof(char));
    if (!buffer) {
        return NULL;
    }

    for (int i = 0; i < N_BITS; i++) {
        int16_t bit_mask = 1 << (N_BITS - i - 1);
        buffer[i] = (value & bit_mask) ? '1' : '0';
    }

    buffer[N_BITS] = '\0';
    return buffer;
}

void print_usage() {
    printf("Usage: %s <base> <number>\n", "base_changer");
    printf("\nBase must be between 2 and 36\n");
    printf("Number must be between 0 and 2147483647\n");
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        print_usage();
        return 1;
    }
    
    int base = atoi(argv[1]);
    int user_num = atoi(argv[2]);
    
    if (!(base >= 2 && base <= 36)) {
        print_usage();
        return 2;
    }
    if (user_num > 2147483647) {
        print_usage();
        return 2;
    }
    
    change_base(base, user_num);
    return 0;
}

output

<items><item uid="Hexadecimal" arg="FF"><title>FF</title><subtitle></subtitle><icon>icon.png</icon></item></items>

Binary Converter

Same bullshit with this:

Read more >

Snake in C

Again, not my code, but it was on my drive. It shall be helpful for when I reimplement it in Java for my arcade.

#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

// Macro-defined constants:
#define N_COLS        15
#define N_ROWS        15
#define MAX_SNAKE_LEN (N_COLS * N_ROWS)

#define EMPTY      0
#define SNAKE_HEAD 1
#define SNAKE_BODY 2
#define APPLE      3

#define NORTH 0
#define EAST  1
#define SOUTH 2
#define WEST  3

// Prototypes --- major game operations:
void init_snake(void);
void update_apple(void);
bool update_snake(int direction);
bool move_snake_in_grid(int new_head_row, int new_head_col);
void move_snake_in_array(int new_head_row, int new_head_col);

// Prototypes --- utility functions:
void set_snake(int row, int col, int body_piece);
void set_snake_grid(int row, int col, int body_piece);
void set_snake_array(int row, int col, int nth_body_piece);
void print_grid(void);
int input_direction(void);
int get_d_row(int direction);
int get_d_col(int direction);
void seed_rng(unsigned int seed);
unsigned int rand_value(unsigned int n);

// Constants:
const char symbols[4] = {'.', '#', 'o', '@'};

// Globals:
int8_t grid[N_ROWS][N_COLS] = { EMPTY };

int8_t snake_body_row[MAX_SNAKE_LEN] = { EMPTY };
int8_t snake_body_col[MAX_SNAKE_LEN] = { EMPTY };
int snake_body_len = 0;
int snake_growth   = 0;
int snake_tail     = 0;

// Code:

// `main' (not provided):
// Run the main game loop!
int main(void) {
	init_snake();
	update_apple();

	int direction;
	do {
		print_grid();
		direction = input_direction();
	} while (update_snake(direction));

	int score = snake_body_len / 3;
	printf("Game over! Your score was %d\n", score);

	return 0;
}


// `init_snake' (not provided):
// Set the snake's initial location.
void init_snake(void) {
	set_snake(7, 7, SNAKE_HEAD);
	set_snake(7, 6, SNAKE_BODY);
	set_snake(7, 5, SNAKE_BODY);
	set_snake(7, 4, SNAKE_BODY);
}


// `update_apple' (not provided):
// Pick a random new location to place an apple.
void update_apple(void) {
	int apple_row;
	int apple_col;

	do {
		apple_row = rand_value(N_ROWS);
		apple_col = rand_value(N_COLS);
	} while (grid[apple_row][apple_col] != EMPTY);

	grid[apple_row][apple_col] = APPLE;
}


// `update_snake' (not provided):
// Move the snake one step in `direction' by updating the snake
// locations on the grid and in the array.  Handle consuming apples.
// Trigger a game-over if we wander off the edges of the board.
bool update_snake(int direction) {
	int d_row = get_d_row(direction);
	int d_col = get_d_col(direction);

	int head_row = snake_body_row[0];
	int head_col = snake_body_col[0];

	grid[head_row][head_col] = SNAKE_BODY;

	int new_head_row = head_row + d_row;
	int new_head_col = head_col + d_col;

	if (new_head_row < 0)       return false;
	if (new_head_row >= N_ROWS) return false;
	if (new_head_col < 0)       return false;
	if (new_head_col >= N_COLS) return false;

	// Check if there is an apple where the snake's head will be
	// *before* we move the snake, and thus overwrite the apple.
	bool apple = (grid[new_head_row][new_head_col] == APPLE);

	snake_tail = snake_body_len - 1;

	if (! move_snake_in_grid(new_head_row, new_head_col)) {
		return false;
	}

	move_snake_in_array(new_head_row, new_head_col);

	if (apple) {
		snake_growth += 3;
		update_apple();
	}

	return true;
}


// `move_snake_in_grid' (not provided):
// Paint the snake onto the grid, moving the head along by a step,
// and removing tail segments.  Fail if this move would cause us
// to run into our own body.
bool move_snake_in_grid(int new_head_row, int new_head_col) {
	if (snake_growth > 0) {
		snake_tail++;

		snake_body_len++;
		snake_growth--;
	} else {
		int tail = snake_tail;

		int tail_row = snake_body_row[tail];
		int tail_col = snake_body_col[tail];

		grid[tail_row][tail_col] = EMPTY;
	}

	if (grid[new_head_row][new_head_col] == SNAKE_BODY) {
		return false;
	}

	grid[new_head_row][new_head_col] = SNAKE_HEAD;
	return true;
}


// `move_snake_in_array':
// Update record of where the snake's body segments are, when the head
// is now in a new location.
void move_snake_in_array(int new_head_row, int new_head_col) {
	for (int i = snake_tail; i >= 1; i--) {
		set_snake_array(snake_body_row[i - 1], snake_body_col[i - 1], i);
	}

	set_snake_array(new_head_row, new_head_col, 0);
}


////////////////////////////////////////////////////////////////////////
///
/// The following functions are already implemented in assembly for you.
///
/// You may find it very useful to read through these functions in C and
/// in assembly, but you do not need to do so.
///

// `set_snake' (provided):
// Set up the snake by painting it onto the grid and by recording where
// that piece of the body was.  Only really used in `init_snake'.
void set_snake (int row, int col, int body_piece)
{
	set_snake_grid(row, col, body_piece);
	set_snake_array(row, col, snake_body_len);
	snake_body_len++;
}

// `set_snake_grid' (provided):
// Place `body_piece' into the grid at `row' and `col'.
void set_snake_grid(int row, int col, int body_piece) {
	grid[row][col] = body_piece;
}

// `set_snake_array' (provided):
// Record that the nth piece of the snake's body is at `row' and `col'.
void set_snake_array(int row, int col, int nth_body_piece) {
	snake_body_row[nth_body_piece] = row;
	snake_body_col[nth_body_piece] = col;
}

// `print_grid' (provided):
// Draw the whole grid to the screen.
void print_grid(void) {
	putchar('\n');

	for (int i = 0; i < N_ROWS; i++) {
		for (int j = 0; j < N_COLS; j++) {
			char symbol = symbols[grid[i][j]];
			putchar(symbol);
		}

		putchar('\n');
	}
}


int last_direction = EAST;

// `input_direction' (provided):
// Read in the next direction that the user wants to move in.
// Handles invalid input by telling the user their input was bad.
// Handles inputs that the snake cannot move in by going bonk.
int input_direction(void) {
    int direction;
    do {
        if ((direction = getchar()) == EOF) {
            exit (0);
		}

        switch (direction) {
			case 'w': direction = NORTH; break;
			case 'a': direction = WEST;  break;
			case 's': direction = SOUTH; break;
			case 'd': direction = EAST;  break;

			case '\n': continue;

			case '\0':
			case '\004':
				exit(0);

			default: {
				printf("invalid direction: %c\n", direction);
				continue;
			}
		}

		if (
			0 <= direction && direction <= 3 &&
			abs(last_direction - direction) != 2
		) {
            last_direction = direction;
            return direction;
        }

        printf("bonk! cannot turn around 180 degrees\n");
    } while (true);
}


// `get_d_row' (provided):
// Determine the delta-row we want to move to.
int get_d_row(int direction) {
	if (direction == SOUTH) {
		return 1;
	} else if (direction == NORTH) {
		return -1;
	} else {
		return 0;
	}
}

// `get_d_col' (provided):
// Determine the delta-column we want to move to.
int get_d_col(int direction) {
	if (direction == EAST) {
		return 1;
	} else if (direction == WEST) {
		return -1;
	} else {
		return 0;
	}
}


///
/// A very simple pseudo-random number generator.
///
/// `rand_seed', `seed_rng', and `rand_value' implement a pseudo-random
/// number generator --- specifically, a linear congruential generator.
/// (You may like to read more about randomness and random numbers ---
/// it's very interesting!)
///

unsigned int rand_seed = 0;

// `seed_rng' (provided):
// Set the initial seed for our simple pseudo-random number generator.
// This is a bit like `srand(3)', but we can't use that on SPIM.
void seed_rng(unsigned int seed) {
	rand_seed = seed;
}

// `rand_value' (provided):
// Get a random number between 0 and `n', and mix in some randomness.
// This is a bit like `rand(3)', but we can't use that on SPIM.
unsigned int rand_value(unsigned int n) {
	rand_seed = (rand_seed * 1103515245 + 12345) & 0x7FFFFFFF;
	return rand_seed % n;
}