How Many Hits?

Time for a small project! In this checkpoint, you'll write a whole program on your own, using what you've learned in the first three lessons: printing, variables, arithmetic and conditions.

The exercises here are a bit different from the ones so far. The instructions say what the program should print, not how to write it. There are many correct ways, so pick the one that makes sense to you. If you get stuck, look back at the lesson where you learned what you need.

The project. Games are one of the things C++ is used for most. Over three exercises, you'll write the heart of a small role-playing game: a fight between a hero and a dragon. Your program will work out how the fight goes, who wins it and what the hero gets for winning. Each exercise continues where the previous one ended: the editor starts with a finished program from the previous step, which may look different from yours. That's fine.

The data. The variables at the top of main describe the fighters: heroAttack is how much health the hero takes from the dragon with one hit, dragonHealth is how much health the dragon has, and dragonAttack is how much health the dragon takes from the hero with one strike. In a real game, these values would come from the game itself. Here, the program gets them from the variables, and your code should work with the variables, not with their numbers copied into it: when you change a variable, the program should still print the right result. To check that, each exercise also runs your program with other values, and it has to get those right too.

The task. The hero strikes first. Each hit takes heroAttack health from the dragon, and the dragon is defeated when its health drops to 0 or below. After every hit that doesn't defeat it, the dragon strikes back. With 150 health, the dragon survives 6 hits of 23, because 6 × 23 is only 138. The 7th hit defeats it. So the dragon strikes back 6 times, and the hero loses 6 × 18 = 108 health. The program prints:

Hits needed: 7
Dragon's strikes: 6
Damage taken: 108

A tip: remember / and % from the lesson on variables. One tells you how many whole hits fit into the dragon's health, the other whether some health is left after them that needs one more hit.

Watch out for a fight in which the hits take exactly all of the dragon's health. With heroAttack = 25, 6 hits take exactly 150 health, so the hero needs only 6 hits, and the dragon strikes back 5 times.

Instructions

Print how many hits the hero needs to defeat the dragon, as in the example.

Below that, print how many times the dragon strikes back and how much health the hero loses.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

1/3