Skip to content

CS50x Week 0 Solution: Explore my solution for CS50x Week 0, complete with in-depth explanations of the exercises. Read through detailed insights and explanations of the code and concepts involved. Learn how to make a game, where you control a spaceship, dodge obstacles, collect points. Learn to make blocks, cloning, events.

License

Notifications You must be signed in to change notification settings

InfectedDuck/CS50x-Week0-Solution-With-Deep-Explanation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 

Repository files navigation

CS50x-Week0-my-solution-and-notes

⭐️ Star this repository! It really motivates me to make better explanations and produce more work!! ⭐️

Introduction

Space Adventures is an interactive Scratch game where players control a spaceship, avoiding obstacles and collecting points to achieve high scores. Experience thrilling gameplay with intuitive controls and dynamic challenges in this engaging space-themed adventure. This game is hard and consists of 2 phases, will you try to beat it?

Features

  • Interactive Gameplay: Players control a spaceship navigating through space using intuitive controls.
  • Obstacle Avoidance: Players must avoid various obstacles to survive, adding dynamic challenges to the game.
  • Point Collection: Points are collected by destroying obstacles, encouraging skillful play.
  • Score Tracking: The game keeps track of the highest score achieved, motivating players to beat their previous records.
  • High-Quality Musical Accompaniment: Various musical compositions enhance the gameplay experience, triggered by special events.
  • Enemy Spaceship: In the second stage, a special enemy spaceship appears and glides towards the player, adding an additional layer of challenge.
  • Super Fire: Every 10 shots, a super fire is launched that can destroy all objects in its path quickly and efficiently.

How to Play

  1. Start the Game: Open the Space Adventures project in Scratch.
  2. Controls: Use the arrow keys to move the spaceship up, down, left, and right.
  3. Objective: Avoid obstacles and collect points to achieve the highest score.
  4. End of Game: The game ends when the spaceship crashes into an obstacle. The final score is displayed.
  5. How to win To win the game 100 points should be obtained.

Installation

To play Space Adventures, follow these steps:

  1. Download Scratch: If you haven't already, download and install Scratch from Scratch's official website.
  2. Open the Project: Download the Space Adventures project file (Space Adventures.sb3) and open it in Scratch.

Gameplay Mechanics

  • Spaceship Movement: Use the arrow keys to move the spaceship up, down, left, and right.
  • Obstacle Generation: Obstacles appear randomly with varying sizes and move towards the spaceship, requiring quick reflexes.
  • Enemy Spaceship: The enemy spaceship appears in the second stage and steadily moves towards the player's spaceship, forcing evasive maneuvers.
  • Super Fire: After every 10 shots, a powerful super fire is activated, passing through and destroying all obstacles rapidly.
  • Point System: Points are awarded for each obstacle destroyed and for the distance traveled, encouraging players to stay alive as long as possible.

Project Structure

Stage

  • Role: Manages the overall game environment, including backgrounds and game states. It also tracks the score and handles game start and end events. The stage controls the transitions between different phases of the game.
  • Costumes: The stage has different costumes to represent various backgrounds and game states. These may include:
    • Background 1: The initial space background for the first phase of the game.
    • Background 2: A different background or a more intense space scene for the second phase when the enemy spaceship appears.

Sprite1 (Spaceship)

  • Role: The player's controllable spaceship. Handles movement using arrow keys and shooting projectiles to destroy obstacles. It is the primary element the player interacts with.

Rocks

  • Role: Represents the obstacles in the game. These rocks appear randomly and move towards the player's spaceship. The player must avoid or destroy these rocks to survive.

Enemy Spaceship

  • Role: A special enemy that appears in the second phase of the game. It steadily moves towards the player's spaceship, adding an additional layer of challenge that the player must evade.

Letter Sprites

  • Role: Display messages indicating game status, such as win/loss, game over, or instructional text. These sprites are shown at various points during the game.
  • Costumes: Each letter sprite has a costume that displays a specific letter or message component. For example:
    • Y, O, U, W, O, N: Sprites that spell out "YOU WON" when the winning condition is met.
    • G, A, M, E, O, V, E, R: Sprites that spell out "GAME OVER" at the end of the game.

Button1 (Bullets)

  • Role: Represents the bullets fired by the player's spaceship. These bullets are used to destroy obstacles (rocks) and enemy spaceships. The Button1 sprite handles the shooting mechanics, including bullet movement and collision detection.

Super Fire

  • Role: A powerful shot that the player's spaceship can fire every 10 shots. It passes through and destroys all obstacles in its path, providing a temporary advantage.

Game Phases

  • Phase 1: The game starts with the player controlling the spaceship and avoiding rocks that appear randomly. The main objective is to survive and collect points by destroying obstacles.
  • Phase 2: After a certain score threshold is reached, the game transitions to the second phase. In this phase, the enemy spaceship appears and starts gliding towards the player's spaceship. The player must continue avoiding rocks while also evading the enemy spaceship, increasing the difficulty of the game.

Technical Details

Techniques Used

  • Event-Driven Programming: The game heavily relies on event-driven programming, using Scratch's broadcasting and event listening features to manage game states and transitions.
  • Randomization: Random functions are used to generate obstacles at random positions and with random sizes to ensure the game remains unpredictable and challenging.
  • Collision Detection: Scratch's built-in collision detection is used to manage interactions between the spaceship, bullets, and obstacles.
  • State Management: Variables are used to keep track of game states such as score, game phase, and bullet count.
  • Message Broadcasting: Scratch's message broadcasting system is used to trigger changes between game phases and to handle the appearance of messages like "Game Over" and "You Won".

Implementation of Mechanics

Spaceship Movement

The spaceship is controlled using the arrow keys. The scripts attached to the spaceship sprite listen for key press events and move the spaceship accordingly:

  • Up Arrow: Moves the spaceship up.
  • Down Arrow: Moves the spaceship down.
  • Left Arrow: Moves the spaceship left.
  • Right Arrow: Moves the spaceship right.

Shooting Bullets

The player can shoot bullets by pressing the spacebar. Each time the spacebar is pressed, a bullet sprite (Button1) is cloned and set to move forward from the spaceship's position:

  • Bullet Creation: A new clone of the Button1 sprite is created.
  • Bullet Movement: The cloned bullet moves forward until it collides with an obstacle or goes off-screen.
  • Collision Handling: When a bullet collides with an obstacle, both the bullet and the obstacle are destroyed, and the player earns points.

Super Fire Mechanism

Every 10 shots, a super fire is activated which destroys all obstacles in its path:

  • Super Fire Activation: A counter keeps track of the number of bullets fired. When it reaches 10, a super fire is triggered.
  • Super Fire Behavior: The super fire moves quickly across the screen, destroying any obstacles it touches.

Obstacle Generation

Obstacles (rocks) are generated at random intervals and positions:

  • Random Positioning: Obstacles appear at random positions on the right edge of the screen.
  • Random Sizes: Obstacles are assigned random sizes to add variety and difficulty.
  • Movement: Obstacles move leftward towards the spaceship, increasing the challenge for the player.

Enemy Spaceship

In the second phase of the game, an enemy spaceship appears and glides towards the player’s spaceship:

  • Appearance Trigger: The enemy spaceship appears once a certain score threshold is reached.
  • Movement: The enemy spaceship steadily moves towards the player’s spaceship, forcing the player to evade it while still avoiding obstacles.

Explanation of the code

Sound, end-game events

Sound Events
  1. Event: "Congratulations, you won!"
    • Actions: Stops all current sounds. Plays the "Dubstep" sound until it is completed.
    • Purpose: To provide a celebratory audio cue when the player wins the game.
  2. Event: "Game Over"
    • Actions:
      • Stops all current sounds.
      • Plays the "Cave" sound until it is completed.
    • Purpose: To signal to the player that the game has ended with a distinct sound.
  3. Event: "SECOND PHASE"
    • Actions:
      • Plays the "Alert" sound until it is completed.
      • Plays the "Alien Creak1" sound until it is completed.
    • Purpose: To indicate the start of a new phase in the game with a combination of alerting and eerie sounds.
  4. Event: When the green flag is clicked
    • Actions:
      • Repeatedly plays the "Space Ambience" sound.
    • Purpose: To provide continuous background ambiance, immersing the player in a space-themed environment throughout the game. The syntax is simple, when the signal about event is gone, other actions will be played. Something like If condition is met, do this. And songs will start playing. Forever loop means, it will always launch the music another time, when it meets it's end.
  5. The syntax is simple, when the sygnal about event will gone, other actions will be played. Something like If condition is met, do this. And songs will start playing. Forever loop means, it will always launch the music another time, when it meets it's end.

Enemy Spaceship Base

Enemy Spaceship Base

This image shows the setup process for initializing the enemy spaceship in the game. The blocks are designed to position the spaceship correctly and hide it at the start of the game. Here's what each block does:

  1. Event: When the green flag is clicked
    • Purpose: This block is triggered when the game starts (or is restarted). It ensures that the following actions happen right at the beginning of the game.
  2. Block: Go to x: 180 y: 150
    • Action: This block moves the enemy spaceship to a specific position on the screen, with coordinates (180, 150).
    • Purpose: Setting the initial position of the spaceship so that it starts from a predefined location, ensuring consistent gameplay each time the game begins.
  3. Block: Hide
    • Action: This block makes the enemy spaceship invisible.
    • Purpose: Initially hiding the spaceship until it's needed in the game. This can be useful for setting up the game environment without showing all elements right away, creating a more controlled and engaging experience for the player.

Together, these blocks ensure that the enemy spaceship is placed correctly and hidden when the game starts, ready to be revealed at the appropriate moment in the gameplay.

Enemy Spaceship Movements

Enemy Spaceship Movements

This image shows how the enemy spaceship behaves during the second phase of the game. Each block in the script plays a crucial role in creating a dynamic and engaging challenge for the player. Here's what each part does:

  1. Event: When I receive "SECOND PHASE"
    • Purpose: This block is triggered when the game reaches the second phase. It ensures that the following actions start specifically at this stage of the game.
  2. Block: Show
    • Action: This block makes the enemy spaceship visible.
    • Purpose: To reveal the enemy spaceship at the beginning of the second phase, adding an element of surprise and increasing the difficulty.
  3. Repeat Until: touching "Sprite1"
    • Action: This block repeats the enclosed actions until the enemy spaceship touches "Sprite1" (which could be the player's spaceship or another target).
    • Purpose: To keep the enemy spaceship moving towards its target until it makes contact, creating a continuous challenge for the player.
  4. Block: Glide 8 secs to "Sprite1"
    • Action: This block moves the enemy spaceship towards "Sprite1" over a period of 8 seconds.
    • Purpose: To create a smooth, gliding motion towards the target, making the enemy's movement predictable yet challenging to avoid.
  5. Block: Broadcast "Game Over"
    • Action: This block sends a "Game Over" message when the enemy spaceship touches "Sprite1".
    • Purpose: To trigger the end of the game, indicating that the player has been caught by the enemy spaceship.
  6. Block: Stop all
    • Action: This block stops all scripts in the game.
    • Purpose: To halt all game activities immediately after the game is over, ensuring a clear and definitive end to the game session.

This script ensures that the enemy spaceship appears and actively targets the player during the second phase, creating a tense and exciting gameplay experience.

Letters Visibility

Letters Visibility

This image shows two separate scripts that control the visibility of letters in the game, both when the game starts and when it ends. Here's what each block does:

  1. Event: When I receive "Game Over"
    • Action: This block is triggered when the game sends a "Game Over" message.
    • Block: Show
      • Action: Makes the letters visible.
      • Purpose: To display the letters on the screen when the game ends, possibly to spell out a "Game Over" message for the player.
  2. Event: When the green flag is clicked
    • Action: This block is triggered when the game starts (or is restarted).
    • Block: Hide
      • Action: Hides the letters.
      • Purpose: To ensure that the letters are not visible when the game starts, keeping the screen clear until they are needed (like when the game ends).

These scripts manage the visibility of the letters in the game, ensuring they only appear at the appropriate times to communicate the game status effectively to the player.

Spaceship Movements

Spaceship Movement

This image shows a script that allows the player to control the movement of a spaceship using the keyboard. Each block checks for a specific key press and moves the spaceship accordingly. Here's how it works:

  1. Event: When the green flag is clicked
    • Action: This block is triggered when the game starts (or is restarted).
    • Purpose: To initialize the control script, making sure the spaceship can be moved as soon as the game begins.
  2. Forever Loop
    • Action: This block continuously checks for key presses.
    • Purpose: To allow continuous movement of the spaceship as long as the game is running.
  3. If key "w" pressed?
    • Action: Checks if the "w" key is pressed.
    • Block: Change y by 5
      • Action: Moves the spaceship up by 5 units.
      • Purpose: To move the spaceship up when the "w" key is pressed, simulating forward movement.
  4. If key "a" pressed?
    • Action: Checks if the "a" key is pressed.
    • Block: Change x by -5
      • Action: Moves the spaceship left by 5 units.
      • Purpose: To move the spaceship left when the "a" key is pressed, simulating leftward movement.
  5. If key "s" pressed?
    • Action: Checks if the "s" key is pressed.
    • Block: Change y by -5
      • Action: Moves the spaceship down by 5 units.
      • Purpose: To move the spaceship down when the "s" key is pressed, simulating backward movement.
  6. If key "d" pressed?
    • Action: Checks if the "d" key is pressed.
    • Block: Change x by 5
      • Action: Moves the spaceship right by 5 units.
      • Purpose: To move the spaceship right when the "d" key is pressed, simulating rightward movement.

This script provides basic but effective keyboard controls for moving the spaceship in four directions, enhancing the player's ability to navigate the game environment.

Rocks Function

Rocks Function

This image shows a custom function called "rocks" that manages the behavior of rocks in the game. This function handles their movement, interactions with the edges of the screen, and interactions with buttons. Here's a breakdown of what each part does:

  1. Define "rocks"
    • Purpose: This block defines a custom function named "rocks." The actions within this function can be reused whenever this function is called in the game.
  2. If touching edge?
    • Action: Checks if a rock is touching the edge of the screen.
    • Block: Go to x: (pick random -220 to 220) y: 150
      • Action: Moves the rock to a random horizontal position at the top of the screen.
      • Purpose: To reset the rock's position when it touches the edge, making it appear at the top again to fall down.
  3. If touching Button2 or touching Button3?
    • Action: Checks if a rock is touching either Button2 or Button3.
    • Block: Go to x: (pick random -220 to 220) y: 150
      • Action: Moves the rock to a random horizontal position at the top of the screen.
      • Purpose: To reset the rock's position when it touches a button, making it appear at the top again to fall down.
  4. Set pitch effect to (pick random 1 to 100)
    • Action: Changes the pitch effect to a random value between 1 and 100.
    • Purpose: To create a variety of sound effects when the rock interacts with a button, adding auditory interest to the game.
  5. Start sound "pop"
    • Action: Plays the "pop" sound.
    • Purpose: To provide immediate audio feedback when the rock touches a button, enhancing the player's experience.
  6. Change whirl effect by 25
    • Action: Applies a whirl effect to the rock, increasing the effect by 25.
    • Purpose: To visually indicate the interaction, making the game more visually engaging.
  7. Change score by 1
    • Action: Increases the player's score by 1.
    • Purpose: To reward the player for successful interactions with the buttons, providing a sense of achievement and progress.

This function ensures that rocks in the game have dynamic interactions with the screen edges and buttons, providing both visual and auditory feedback while also contributing to the game's scoring system.

Shooting Mechanism

Shooting Mechanism

Shooting Mechanism Code Explanation

This code block manages the shooting mechanism for a sprite in a game. It defines the behavior when the green flag is clicked and continuously monitors for the space key to be pressed, triggering the shooting action.

  • Event: When the green flag is clicked
    • Block: Hide
      • Action: Initially hides the sprite to manage its visibility during gameplay.
      • Purpose: Ensures the sprite is only visible when it should be active.
    • Forever Loop
      • Block: Go to Sprite1
        • Action: Positions the sprite at the location of Sprite1.
        • Purpose: Aligns the shooting sprite with the main sprite for accurate shooting.
      • Block: Change y by 5
        • Action: Moves the sprite upward by 5 units.
        • Purpose: Simulates the upward movement of the bullet when fired.
      • Condition: If key space pressed?
        • Block: Wait 0.1 seconds
          • Action: Introduces a brief delay between shots.
          • Purpose: Prevents continuous firing, simulating a realistic shooting rate.
        • Block: Create clone of myself
          • Action: Creates a clone of the current sprite.
          • Purpose: Simulates firing a bullet by creating a clone of the sprite.
        • Block: Play sound Laser2
          • Action: Plays the "Laser2" sound effect to simulate shooting.
          • Purpose: Provides auditory feedback for the shooting action.
        • Block: Change firesuntilmegafire by -1
          • Action: Decrements the counter for shots until the mega fire mode is triggered.
          • Purpose: Tracks the number of shots fired to trigger a special action after a set number of shots.
        • Condition: If firesuntilmegafire = 0
          • Block: Create clone of Button3
            • Action: Creates a clone of Button3, possibly for a special shooting action or power-up.
            • Purpose: Activates a special power-up or action when the counter reaches zero.
          • Block: Set shots to 10
            • Action: Resets the counter to 10 for the next cycle of shots.
            • Purpose: Prepares for the next cycle of tracking shots for the mega fire action.

Bullet Clone Initialization Code

Clone Initialization Code

Clone Initialization Code Explanation

This code block defines the behavior for a sprite when it starts as a clone. It manages the movement, interactions, and events triggered by the clone during the game.

  • Event: When I start as a clone
    • Block: Show
      • Action: Makes the clone visible.
      • Purpose: Ensures the clone can be seen when it is active.
    • Block: Go to x: (pick random -220 to 220) y: 150
      • Action: Positions the clone at a random x-coordinate within the range -220 to 220 and at y-coordinate 150.
      • Purpose: Randomizes the initial position of the clone to add variety to its spawning.
    • Block: Set speed to (pick random -1 to -10)
      • Action: Sets the speed of the clone to a random value between -1 and -10.
      • Purpose: Adds variability to the speed of the clone, making the game more challenging.
    • Loop: Repeat until touches sprite1
      • Action: Loop continues until rock will touch the spaceship.
      • Purpose: To set an action to avoid rocks.
    • Block: Broadcast game over
      • Action: Sends a broadcast message indicating that the game is over.
      • Purpose: Provides feedback to the player that the game has ended.
      • Block: Change y by speed
        • Action: Moves the clone downward by the set speed value.
        • Purpose: Simulates the falling movement of the clone.
      • Block: rocks
        • Action: Executes the custom "rocks" function, which defines additional behaviors (not fully shown in this block).
        • Purpose: Adds complex behaviors to the clone, defined in the "rocks" function.
      • Condition: If score = 50
        • Block: Switch backdrop to Galaxy
          • Action: Changes the backdrop to "Galaxy".
          • Purpose: Indicates a transition to a new phase of the game.
        • Block: Broadcast phase 2
          • Action: Sends a broadcast message to initiate the second phase of the game.
          • Purpose: Coordinates the transition to the next phase with other sprites and scripts.
      • Condition: If score > 150
        • Block: Broadcast you win
          • Action: Sends a broadcast message indicating that the player has won the game.
          • Purpose: Provides feedback to the player for winning the game.
        • Block: Stop all
          • Action: Stops all scripts, effectively ending the game.
          • Purpose: Concludes the game when the winning condition is met.
      • Block: Stop all
        • Action: Stops all scripts, effectively ending the game.
        • Purpose: Ensures the game concludes properly when the game over condition is met.

Rock Clones Behavior

Rock Clones Behavior

Rock Clones Behavior Code Explanation

This code block defines the behavior for a sprite when it starts as a clone. It manages the movement and interactions of the clone in the game.

  1. Event: When I start as a clone
    • Block: show
      • Action: Makes the clone visible.
      • Purpose: Ensures the clone can be seen when it is active.
    • Block: repeat until touching edge or touching Rocks
      • Action: Moves the clone downward by 5 units continuously until it touches the edge of the screen or another sprite named "Rocks".
      • Purpose: Simulates the falling movement of the clone, adding interaction with the game environment.
    • Block: hide
      • Action: Hides the clone once the repeat condition is met.
      • Purpose: Removes the clone from view once it has completed its movement or interaction.

Game Start

Game Start Code

Game Start Code Explanation

This code block defines the actions that occur when the green flag is clicked, typically indicating the start of the game.

  1. Event: When green flag clicked
    • Block: play sound [Space Ripple] until done
      • Action: Plays the "Space Ripple" sound effect completely before moving to the next block.
      • Purpose: Provides an auditory cue to signal the start of the game.
    • Block: switch backdrop to [Stars]
      • Action: Changes the background of the stage to "Stars".
      • Purpose: Sets the initial scene for the game environment.
    • Block: hide
      • Action: Hides the sprite executing this script.
      • Purpose: Ensures the sprite is not visible until it is needed.
    • Block: set [score] to [0]
      • Action: Initializes the score to 0 at the start of the game.
      • Purpose: Resets the game score for a new playthrough.
    • Block: repeat [7]
      • Block: set size to [pick random 30 to 60] %
        • Action: Randomly sets the size of the sprite to a value between 30% and 60%.
        • Purpose: Adds variety to the size of the clones, making the game more interesting.
      • Block: create clone of [myself]
        • Action: Creates a clone of itself.
        • Purpose: Continuously generates new clones to simulate ongoing action in the game.

Super Bullet Base

Super Bullet Base Code

Super Bullet Base Code Explanation

This code block defines the base behavior of the super bullet sprite, ensuring it follows another sprite continuously.

  • Event: When green flag clicked
    • Block: Hide
      • Action: Hides the sprite executing this script.
      • Purpose: Ensures the sprite is not visible until needed.
    • Forever Loop
      • Block: Go to (Sprite1)
        • Action: Continuously moves the sprite to the location of "Sprite1".
        • Purpose: Keeps the sprite aligned with "Sprite1" for accurate positioning.

Super Bullet Movement

Super Bullet Movement Code

Super Bullet Movement Code Explanation

This code block defines the behavior of a cloned sprite, likely a bullet, that moves vertically until it touches the edge of the screen.

  • Event: When I start as a clone
    • Block: Show
      • Action: Makes the cloned sprite visible.
      • Purpose: Ensures the clone can be seen when active.
    • Repeat Until Loop: Touching Edge
      • Block: Change y by 15
        • Action: Moves the sprite upward by 15 units each iteration.
        • Purpose: Simulates the upward movement of the bullet.
    • Block: Hide
      • Action: Hides the sprite once it touches the edge of the screen.
      • Purpose: Removes the sprite from view after it has completed its movement.

Credits

CS50 Logo

Credits to CS50x

This project was inspired by and developed as part of the CS50x course offered by Harvard University. CS50x is Harvard University's introduction to the intellectual enterprises of computer science and the art of programming for majors and non-majors alike, with or without prior programming experience.

  • Course: CS50x: Introduction to Computer Science
  • Institution: Harvard University
  • Instructor: David J. Malan
  • Website: CS50x Official Site

Thank you to the CS50x team for providing such a comprehensive and engaging introduction to computer science.

About

CS50x Week 0 Solution: Explore my solution for CS50x Week 0, complete with in-depth explanations of the exercises. Read through detailed insights and explanations of the code and concepts involved. Learn how to make a game, where you control a spaceship, dodge obstacles, collect points. Learn to make blocks, cloning, events.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published