
Plants vs. Zombies, in C
A course project: Plants vs. Zombies written in C with the EasyX graphics library, and the whole build written up in fifteen posts.
AWhat it is
A course project with a twist: you play the zombie. On a lawn of five rows and nine columns you move with WASD and press E to interact with plants, and you have to reach the left edge before time runs out.
BThe rules
Peashooters fire peas to the right, and each hit on the zombie costs 25 points; eating a sunflower buys more time, eating a peashooter is worth 100. Before playing you sign in on a login screen built from scratch, and the game shows the player’s name, the current score, the best score and a countdown.
CHow it’s built
Written in C with the EasyX graphics library in Visual Studio. Peas on the lawn live in a linked list and are freed as soon as they hit or leave the screen; the best score is kept in a binary file; the swaying plants and walking zombie are drawn frame by frame in the main loop, with the pace held steady.
DThe write-up
The build is written up in fifteen posts on my Hexo blog, from data structures and helper functions through the login screen, image loading, animation, collision checks and freeing memory, to saving scores and the release build. The code below, reading and writing the best score, is from one of them.
EThe lines that matter
int getScore() { int fileNumber = 0; FILE* file = fopen("score.bin", "rb"); if (file != NULL) { if (fread(&fileNumber, sizeof(int), 1, file) != 1) { fileNumber = 0; } fclose(file); } return fileNumber;}void compearScore(int Userscore) { int fileNumber = getScore(); if (Userscore > fileNumber) { FILE* file = fopen("score.bin", "wb"); if (file != NULL) { fwrite(&Userscore, sizeof(int), 1, file); fclose(file); } }}