C (programming language)

Rock-Paper-Scissor Game In C (Project-1)

Introduction

Ready to test your C programming skills and have some fun? Let’s create the classic Rock-Paper-Scissors game! This project will guide you through the process, covering fundamental C concepts like variables, input/output, conditional statements, and random number generation.

Understanding the Game Rules

  • Two players choose either rock, paper, or scissors simultaneously.
  • The winner is determined by these rules:
    • Rock beats scissors.
    • Paper beats rock.
    • Scissors beat paper.
    • If both players choose the same item, it’s a tie.

Project Structure

  1. Include Headers:

C

#include <stdio.h>
#include <stdlib.h>  // For the rand() function
#include <time.h>    // To seed the random number generator
  1. Declare Main Function:

C

int main() {
    // Game logic here
}
  1. Declare Variables:

C

char userChoice, computerChoice;
  1. Get User Input:

C

printf("Enter your choice (r for rock, p for paper, s for scissors): ");
scanf("%c", &userChoice);
  1. Generate Computer’s Choice:

C

srand(time(NULL));  // Seed the random number generator
int randomNumber = rand() % 3;  // Generate a random number between 0 and 2

switch (randomNumber) {
    case 0:
        computerChoice = 'r';
        break;
    case 1:
        computerChoice = 'p';
        break;
    case 2:
        computerChoice = 's';
        break;
}
  1. Determine the Winner:

C

if (userChoice == computerChoice) {
    printf("It's a tie!\n");
} else if ((userChoice == 'r' && computerChoice == 's') ||
           (userChoice == 'p' && computerChoice == 'r') ||
           (userChoice == 's' && computerChoice == 'p')) {
    printf("You win!\n");
} else {
    printf("Computer wins!\n");
}
  1. Print the Results:

C

printf("You chose: %c\n", userChoice);
printf("Computer chose: %c\n", computerChoice);

Complete Code Example:

C

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

int main() {
    char userChoice, computerChoice;

    // ... (rest of the code from steps 3-7)
}

Customization and Enhancements

  • Add a loop to play multiple rounds.
  • Track scores and display a final winner.
  • Implement a best-of-three or best-of-five format.
  • Improve user input validation.

Conclusion

Building the Rock-Paper-Scissors game in C offers a fun and engaging way to practice fundamental programming concepts. Experiment with different features and enhancements to create a more personalized and challenging experience!

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button