Reorg and orgmode test

This commit is contained in:
2025-03-27 09:28:52 +01:00
parent 8719f4c140
commit d57e32a8b8
14 changed files with 169 additions and 72 deletions

View File

@@ -0,0 +1,164 @@
#+TITLE: Informatik Vorkurs Project 1
#+AUTHOR: JirR02
* Project 1: Guess A Number (Task 1)
** Table of Contents :toc:
- [[#project-1-guess-a-number-task-1][Project 1: Guess A Number (Task 1)]]
- [[#about-this-task][About this task]]
- [[#solution][Solution]]
** About this task
*** Project overview
The goal of the first project is to program a simple number guessing game: the player needs to correctly guess a number, chosen from an interval $$\[1,N \]**, with at most $$K$$ guesses.
In the lecture, a first version of the game was presented, in which the player had only one chance of guessing the correct number. In order to implement the full game, you will have to extend this version by allowing the player to guess up to $$K$$ times.
The first project consists of two tasks: *task 1* /(this task)/ is to reimplement the first version of the game that was presented in the lecture, *task 2* is to implement the full game.
*** General development advice
Develop your program step-by-step, and save, run and compile it often. I.e. implement a single feature, such as inputting the guess, or comparing the guess and the correct number, and then compile and run the program to see if your code (still) works as intended. Small changes and repeated testing make it easier for you to observe problems, to work out what causes them, and to finally solve them.
*** Fulfilling requirements and testing programs
A particular goal of this task is to make you understand how strongly connected requirements and testing (and thus grading submissions) are. E.g. if the task description requires output of the shape "I␣saw␣$$n$$␣cat(s).", where $$n$$ is a number and ␣ represents blanks/whitespaces, your program will not be considered correct if it outputs a text that is "basically the same", but does not precisely match the requirements. E.g. the following outputs, while very close to the expected output, do not match the shape specified above: "i␣saw␣3␣cat(s).", "I␣saw␣3␣cats.", "I␣saw␣1␣cat.", "I␣saw␣2␣cat(s)" and "i␣saw␣2␣␣cat(s)␣.".
Meeting such requirements precisely is necessary for testing: we automatically (at least to some extent) test correctness of your programs by comparing the expected output to the output produced by your program. Since these comparisons are performed by a computer, it is much much easier to do them syntactically, i.e. letter-by-letter.
However, being able to precisely fulfil requirements is more generally important, in particular when working with customers: imagine you order a black smartphone, but then get delivered a dark blue one (same make and model). Although "basically the same", it's just not what you ordered. The same holds for software — it's the details that matter.
*** Your task
To solve this task, proceed as follows:
1. Look at the template program, in particular main.cpp, and see what's already there (e.g. variable declarations) and what's still missing. The latter is hinted at by TODO comments.
1. The template already contains code for picking the number to guess. By default, the number is randomly choosen from the interval $$\[1,3\]$$:
#+begin_src cpp
number_to_guess = choose_a_number(3);
#+end_src
/During development/, you might want to change this line: e.g. read the number from the keyboard:
#+begin_src cpp
std::cin >> number_to_guess;
#+end_src
or even hard-code (i.e. fix) a specific number, e.g.
#+begin_src cpp
number_to_guess = 3;
#+end_src
However, in order to run the automatic tests, and /when submitting your final version/, your program /must/ either read the word from the keyboard or use the ~choose_a_number~ function.
1. Now address the first TODO comment: by outputting the text "Your␣guess:␣" (as before, ␣ denotes a blank/whitespace character), followed by inputting the guess from the keyboard into variable guess.
2. Now address the second TODO comment: by comparing the two numbers for equality. If they are, output the line
#+begin_src shell
Congratulations,␣you␣correctly␣guessed␣X!
#+end_src
where X is the correctly guessed number. Since the output is expected to be a /line/, don't forget to end it with either ~\n~ or ~std::endl~.
If the guess was wrong, however, output the line
#+begin_src shell
Sorry,␣but␣Y␣is␣wrong,␣X␣was␣the␣number␣to␣guess.
#+end_src
where Y is the incorrectly guessed number.
*** Examples
As an illustration, consider the following example in- and outputs of two games (in which the number to guess was randomly chosen). A successfully completed game:
#+begin_src shell
Number to guess: ?
Your guess: 3
Congratulations, you correctly guessed 3!
#+end_src
And a lost game:
#+begin_src shell
Number to guess: ?
Your guess: 2
Sorry, but 2 is wrong, 1 was the number to guess.
#+end_src
*** Testing your program
You can always test your program manually: click the "play" button in the bottom panel, run your program and see if it behaves as expected.
Relevant for your final submission, however, is if it passes the automated tests: to run those, click the "chemistry flask" button in the bottom panel and wait for the output to appear. If your program passes all tests — everything is green and your score is 100% — then your program is ready to be submitted.
Otherwise, /carefully/ compare the expected output to the actual output to find out what went wrong.
*Reminder*: The devil is in the detail! Pay attention to whitespace and newline characters, and in general check that your output fulfils all requirements, even the "boring" ones.
*** Submitting your solution
Finally, submit your solution (your program) by clicking the corresponding button in the top right corner of the Code Expert IDE (open Task/History first). Your program will be tested automatically, and your score will be shown in the "History" view, which can be opened by clicking on the corresponding tab on the right of the Code Expert IDE. Note that you can submit arbitrarily often (before the exercise deadline, of course), and your last submission will be considered for grading.
For this task, all tests need to pass in order to successfully solve this task. This should be rather easy, though, since there isn't much that can go wrong.
You can also see the results for your submission on the "Enrolled Courses" tab of Code Expert, as green or red percentage values to the left of the task's name.
** Solution
Front End to import libraries and files.
#+begin_src cpp
#include <iostream>
#include "guess_a_number.h"
#+end_src
Main function where the code runs.
#+begin_src cpp
int main() {
#+end_src
Declaring Variable which will be used.
#+begin_src cpp
int number_to_guess; // The number to guess
int guess; // The guessed number
#+end_src
Front end terminal output.
#+begin_src cpp
std::cout << "Number to guess: ";
#+end_src
~choose_a_number()~ function is called to choose a number between 1 and 3
#+begin_src cpp
number_to_guess = choose_a_number(3);
#+end_src
Input front end.
#+begin_src cpp
std::cin >> guess;
#+end_src
Output the input of the user.
#+begin_src cpp
std::cout << "Your guess: ";
#+end_src
Depending on the guess, the output in the terminal is different, if the input of the user is the same with the random number, it will output ~Congratulations, you correctly guessed x!~. Otherwise it will output something else.
#+begin_src cpp
if (guess == number_to_guess) {
std::cout << "Congratulations, you correctly guessed " << number_to_guess << "!";
} else {
std::cout << "Sorry, but " << guess << " is wrong, " << number_to_guess << " was the number to guess.";
}
}
#+end_src

View File

@@ -0,0 +1,49 @@
#include <cstdlib>
#include <iostream>
#include <string>
#include "guess_a_number.h"
// NOTE: You cannot change this file, and you don't need to understand its
// content in order to solve your task. Feel free to look around, however,
// in case you're interested.
const std::string action = std::getenv("ACTION");
void print_attempts_left(int attempts_left) {
std::cout << "You have " << attempts_left << " attempt(s) left.\n";
}
void print_you_won(int correct_guess) {
std::cout << "Congratulations, you correctly guessed " << correct_guess << "!\n";
}
void print_wrong_guess(int wrong_guess) {
std::cout << "Sorry, but " << wrong_guess << " is wrong.\n";
}
void print_you_lost(int number_to_guess, int attempts) {
std::cout << "You lost after " << attempts << " attempt(s) :-( The number to guess was " << number_to_guess << ".\n";
}
// This function returns a randomly chosen integer from the interval [1, max].
int randomly_choose_a_number(int max) {
return std::rand() % max + 1;
}
int choose_a_number(int max) {
if (action == "run") {
std::cout << "?\n";
// Just here to achieve the same output behaviour, in terms of newlines,
// when a user replaces
// std::cin >> number_to_guess;
// by
// number_to_guess = choose_a_number(MAX);
return randomly_choose_a_number(max);
} else {
int guess;
std::cin >> guess;
return guess;
}
}

View File

@@ -0,0 +1,82 @@
#ifndef PROJECT_H
#define PROJECT_H
// NOTE: You cannot change this file. It "only" contains declarations and
// short descriptions of the functionality we provided to you.
// This function outputs the number of attempts that are left.
//
// Example: the function call print_attempts_left(3) results in the output
// "You have 3 attempt(s) left".
void print_attempts_left(int attempts_left);
// This function outputs the winning message.
//
// Example: the function call print_you_won(9) results in the output
// "Congratulations, you correctly guessed 9!".
void print_you_won(int correct_guess);
// This function outputs a message telling the user that their guess was wrong.
//
// Example: the function call print_wrong_guess(1) results in the output
// "Sorry, but 1 is wrong.".
void print_wrong_guess(int wrong_guess);
// This function outputs the losing message.
//
// Example: the function call print_you_lost(2, 5) results in the output
// "You lost after 5 attempts :-( The number to guess was 2.".
void print_you_lost(int number_to_guess, int attempts);
// This function returns a randomly chosen integer from the interval [0, max].
int randomly_choose_a_number(int max);
// This function returns a number from the interval [1, max].
// The number is randomly chosen if we're in interactive mode and parameter
// choose_randomly is true, and read from the keyboard (std::cin) otherwise.
int choose_a_number(int max);
// Master implementation for part 1: reads the next guess from the keyboard
// and stores it in the passed variable.
//
// Example: given the function call PART1_read_next_guess(my_guess) and
// assuming that the player enters 1, variable my_guess will afterwards
// have the value 1.
void PART1_read_next_guess(int& guess);
// Master implementation for part 2: compares guess to number_to_guess,
// outputs a result-depending message (correct/wrong) and updates
// variable play to false if the guess was correct.
//
// Example: given the function call
// PART2_handle_guess(1, 2, continue_playing), a wrong-guess message
// will be outputted.
//
// Example: given the function call
// PART2_handle_guess(2, 2, continue_playing), a correct-guess message
// will be output and variable continue_playing will be set to false.
void PART2_handle_guess(int guess, int number_to_guess, bool& play);
// Master implementation for part 3: increments the number of guessing
// attempts the player made (variable attempts), and if the maximum
// number of guesses has been made, outputs a corresponding message and
// sets variable play to false.
//
// Example: given the function call
// PART3_finish_round(2, 10, performed_attempts, continue_playing), and
// assuming that performed_attempts has a value of 5, then the only
// effect of the function call is that performed_attempts will be updated
// to 6.
//
// Example: given the function call
// PART3_finish_round(2, 10, performed_attempts, continue_playing), and
// assuming that performed_attempts has a value of 9, then
// performed_attempts will be incremented to 10, a you-lost message will
// be output and continue_playing will be set to false.
void PART3_finish_round(int number_to_guess, int max_attempts, int& attempts, bool& play);
#endif

View File

@@ -0,0 +1,48 @@
#include <iostream>
#include "guess_a_number.h"
int main() {
int number_to_guess; // The number to guess
int max_attempts; // The guessed number
std::cout << "Number to guess: ";
number_to_guess = choose_a_number(10); // Randomly choose a number from the interval [1, 10]
std::cout << "Number of attempts: ";
std::cin >> max_attempts;
// Make sure that the player has at least one attempt
if (max_attempts < 1) max_attempts = 1;
int attempts = 0; // Attempts made so far
bool play = true; // false once the game is over
while (play) {
print_attempts_left(max_attempts - attempts);
// *** Part 1: input the next guess ****************************************
int guess; // The user's guess
//PART1_read_next_guess(guess);
std::cout << "Your guess: ";
std::cin >> guess;
// *** Part 2: handle the guess the user made *****************************
//PART2_handle_guess(guess, number_to_guess, play);
if (guess == number_to_guess) {
print_you_won(guess);
play = false;
} else {
print_wrong_guess(guess);
}
// *** Part 3: finish up the round ****************************************
if (play) {
//PART3_finish_round(number_to_guess, max_attempts, attempts, play);
attempts += 1;
if (attempts == max_attempts) {
print_you_lost(number_to_guess, attempts);
play = false;
}
}
}
}

View File

@@ -0,0 +1,50 @@
# Projekt 2: Hangman
## Layers
### Start (Optional)
Beim Starten des Spiels soll ein Welcome screen erscheinen mit den Optionen, das Spiel zu starten und das Spiel zu beenden. Damit der Welcome screen gut aussieht soll es Terminal Art beinhalten. Nach dem Start Vorgang wird der Anzahl der Spieler gefragt.
Daraus entstehen 2 Szenarien:
1. Falls es im Einzelspieler Modus ist, wird ein Wort aus der Liste ausgesucht.
1. Falls im Mehrspieler Modus, darf der andere Spieler ein Wort zum Raten auswählen.
- [ ] Start input
- [ ] End input
- [ ] Invalid Input
- [ ] Single or Multiplayer
- [ ] Terminal Art
### Game
Das zu ratende Wort wird verdeckt im Terminal gezeigt. Es wird dann ein Input als Buchstabe verlangt. Wenn der Input zu lang oder ein invalid character ist, wird der Spieler nochmals dazu aufgefordert, ein Buchstabe einzugeben.
Daraus entstehen 2 Szenarien:
1. Ist der Buchstabe in der Zahl enthalten, wird der Buchstabe aufgedeckt und ein positiver Satz erscheint im Terminal.
1. Ist der Buchstabe falsch, so wird ein Leben abgezogen und ein negativer Satz wird ausgespuckt.
Während des ganzen Spiels wird der Terminal Art aktualisiert.
- [ ] Wort verdeckt im Terminal anzeigen
- [ ] Input von einem Buchstaben verlangen
- [ ] Input kontrollieren
- [ ] Buchstabe kontrollieren
- [ ] Positiver Satz
- [ ] Buchstabe aufdecken
- [ ] Negativer Satz
- [ ] (Optional) Terminal Art
### End
Es entstehen daraus zwei Endszenarien:
1. Wurden alle Buchstaben eraten, so wird ein Gewinner Satz ausgesprochen und gefragt ob das Spiel neugestartet werden soll.
1. Wurden alle Versuche verbraucht, so wird ein verlierer Satz ausgesprochen, das Wort aufgelöst und gefragt, ob das Spiel neugestartet werden soll.
Falls das Programm geschlossen wird, wird ein Abschiedssatz gezeigt.
- [ ] Gewinner Satz
- [ ] Verlierer Satz
- [ ] (Optional) Fragen für eine neue Runde
- [ ] Abschiedssatz

View File

@@ -0,0 +1,69 @@
#include "hangman.h"
#include "termcolor.h"
// NOTE: You cannot change this file, and you don't need to understand its
// content in order to solve your task. Feel free to look around, however,
// in case you're interested.
const string action = std::getenv("ACTION");
const string words[] = {
#include "words.csv"
"sentinel"
};
string color(string c) {
return action == "run" ? c : "";
}
string chooseWord() {
string word;
if (action == "test" || action == "submit") {
std::cin >> word;
} else {
int i = rand() % (sizeof(words)/sizeof(*words) - 1); // don't take the last word (which is 'sentinel')
word = words[i];
std::cout << "A random (english) word with " << word.length() << " characters has been chosen." << std::endl;
return word;
}
return word;
}
string createWorkingCopy(string word){
string result = word;
for (unsigned int i = 0; i < result.length(); ++i) {
result.at(i) = '_';
}
return result;
}
void showHangman(int wrongGuesses) {
std::cout
<< "<cx:html>\n"
// << "<p>Attempts left: " << maxWrongGuesses - wrongGuesses << "</p>\n"
<< "<img alt='' src='https://lec.inf.ethz.ch/mavt/et/2019/img/hangman/hang_" << wrongGuesses + 1 << ".gif'/>\n"
<< "</cx:html>" << std::endl;
}
void printGameState(int maxWrongGuesses, int wrongGuesses){
std::cout << color(gray) << "\nAttempts left: " << (maxWrongGuesses - wrongGuesses) << color(reset) << "\n";
}
void printWorkingCopy(string workingCopy){
std::cout << color(blue) << "[ " ;
for (unsigned int i = 0; i < workingCopy.length(); ++i) {
std::cout << workingCopy.at(i) << " ";
}
std::cout << "]\n" << color(reset);
}
void printYouLost(string word){
std::cout << "The word was: " << color(white) << word << color(red) << "\nYou lost!\n" << color(reset);
}
void printYouWon(string word){
std::cout << "\n";
printWorkingCopy(word);
std::cout << color(green) << "You won!\n" << color(reset);
}

View File

@@ -0,0 +1,97 @@
#ifndef HANGMAN_H
#define HANGMAN_H
#include <iostream>
#include <string>
using std::string;
// NOTE: You cannot change this file. It "only" contains declarations and
// short descriptions of the functionality we provided to you.
/**
* This function returns a random english word. Use this to generate a new
* word to guess. It is imperative that you use this function to get a word,
* otherwise, the auto-grader will not work properly when testing or
* submitting your project.
*/
string chooseWord();
/**
* This function creates a "working copy" based on a given word. It returns a
* string with the same amount of characters than the word, but all of them
* are initially set to "_" (underscore)
*/
string createWorkingCopy(string word);
/**
* You may call this function to render a little hangman figure in the HTML view.
* This is completely optional, the tests don't rely on this function being
* called. As argument, the function takes the number of wrong guesses and
* selects the correct hangman picture to show.
*/
void showHangman(int wrongGuesses);
/**
* This function prints the number of remaining attempts (based on the provided
* number of wrong guesses. Call this method before each attempt.
*
* Example: The call 'printGameState(2)' will output: "Attempts left: 4"
* because MAX_WRONG_GUESSES is 6, and 6 - 2 = 4
*/
void printGameState(int maxWrongGuesses, int wrongGuesses);
/**
* This function prints the partly uncovered word (the working copy) in the
* desired format.
*
* Example: If workingCopy is "_xp_rt", a call to printWorkingCopy(workingCopy)
* will print "[ _ x p _ r t ]" - this is the format that is expected by the
* autograder.
*/
void printWorkingCopy(string workingCopy);
/**
* This function must be called if the game was lost (that is, on the 6th
* wrong guess).
*
* Example: If the correct word was "expert", its outputs
* "The word was: expert
* You lost!"
*/
void printYouLost(string word);
/**
* This function must be called if the game was won (that is, the word was
* guessed with less than 6 wrong guesses).
*
* Example: If the correct word was "expert", its outputs
* "[ e x p e r t ]
* You won!"
*/
void printYouWon(string word);
// THE FOLLOWING FUNCTIONS CAN BE USED INTERACTIVELY TO IMPLEMENT THE INDIVIDUAL
// PARTS, BUT THEY DONT'T WORK DURING SUBMISSION
/**
* Part 1: Ask the user to enter a character and update parameter 'guess'
*/
void PART1_readCharacter(char& guess);
/**
* Part 2: Set the guessed character in the working copy. Updates parameter
* 'workingCopy' and sets parameter 'found' to either true or false
*/
void PART2_updateWorkingCopy(string word, char guess, string& workingCopy, bool& found);
/**
* Part 3: Check if game is finished and update wrongGuesses variable.
* Print the approriate messages in the console. Updates parameters 'done' and
* 'wrongGuesses'
*/
void PART3_updateGameState(string word, string workingCopy, bool found, int maxWrongGuesses, bool& done, int& wrongGuesses);
#endif

View File

@@ -0,0 +1,69 @@
#include <iostream>
#include <string>
#include "hangman.h"
using std::string;
int main() {
// Word the player needs to guess (randomly selected)
string word = chooseWord();
//string word = "success";
// Initialise the "uncovered" word that is shown to the player: the uncovered
// word is obtained by replacing each letter from the original word (variable
// word) with an underscore (i.e. _).
string workingCopy = createWorkingCopy(word);
// This variable indicates whether or not the game is over
bool done = false;
int wrongGuesses = 0; // Number of wrong guesses
int maxWrongGuesses = 6; // Maximum number of wrong guesses (don't change)
// Draw the empty gallow
showHangman(0);
// Game loop (each iteration is a round of the game)
while (!done) {
printGameState(maxWrongGuesses, wrongGuesses);
printWorkingCopy(workingCopy);
/** Part 1: input next guess **********************************************/
char guess = '\0';
// TODO: replace the following line with your implementation
//PART1_readCharacter(guess);
std::cout << "Your guess: ";
std::cin >> guess;
/** Part 2: update working copy *******************************************/
bool found = false;
// TODO: replace the following line with your implementation
//PART2_updateWorkingCopy(word, guess, workingCopy, found);
for (int i = 0; i != word.length(); i++) {
if (guess == word.at(i)) {
found = true;
workingCopy.at(i) = guess;
}
}
/** Part 3: update game state *********************************************/
// TODO: replace the following line with your implementation
//PART3_updateGameState(word, workingCopy, found, maxWrongGuesses, done, wrongGuesses);
if (workingCopy == word) {
done = true;
printYouWon(word);
} else if (found == false) {
wrongGuesses += 1;
}
if (wrongGuesses == maxWrongGuesses) {
done = true;
printYouLost(word);
}
}
return 0;
}

View File

@@ -0,0 +1,20 @@
#ifndef TERMCOLOR_H
#define TERMCOLOR_H
// NOTE: You cannot change this file, and you don't need to understand its
// content in order to solve your task. Feel free to look around, however,
// in case you're interested.
const auto red = "\033[31;1m";
const auto green = "\033[32;1m";
const auto yellow = "\033[33;1m";
const auto blue = "\033[34;1m";
const auto magenta = "\033[35;1m";
const auto cyan = "\033[36;1m";
const auto gray = "\033[39;2m";
const auto white = "\033[39;1m";
const auto reset = "\033[0m";
#endif

100
Vorkurs/Projekt_2/words.csv Normal file
View File

@@ -0,0 +1,100 @@
"available",
"exaggerate",
"ancestor",
"architect",
"neighborhood",
"curriculum",
"promotion",
"opera",
"frequency",
"excavation",
"guarantee",
"reflection",
"benefit",
"development",
"average",
"ghostwriter",
"unlikely",
"disturbance",
"initiative",
"hospitality",
"mastermind",
"eyebrow",
"consciousness",
"operational",
"vehicle",
"housewife",
"capital",
"execution",
"terrify",
"disagree",
"exclusive",
"equinox",
"essential",
"imperial",
"publicity",
"secretary",
"nationalist",
"attention",
"established",
"magnitude",
"orientation",
"contraction",
"intention",
"seminar",
"forecast",
"manufacturer",
"reception",
"fabricate",
"mosquito",
"cooperative",
"parachute",
"exotic",
"demonstrate",
"production",
"spontaneous",
"minimum",
"abolish",
"holiday",
"formation",
"admission",
"handicap",
"continuous",
"presentation",
"constituency",
"unique",
"violation",
"radical",
"notebook",
"custody",
"dictionary",
"comprehensive",
"dominant",
"requirement",
"opponent",
"business",
"national",
"manufacture",
"nominate",
"liberal",
"continuation",
"galaxy",
"interest",
"ignorant",
"indirect",
"illustrate",
"proportion",
"projection",
"philosophy",
"acceptable",
"aluminium",
"continental",
"potential",
"vegetarian",
"elephant",
"advantage",
"recording",
"agenda",
"electronics",
"engagement",
"lonely",
1 available
2 exaggerate
3 ancestor
4 architect
5 neighborhood
6 curriculum
7 promotion
8 opera
9 frequency
10 excavation
11 guarantee
12 reflection
13 benefit
14 development
15 average
16 ghostwriter
17 unlikely
18 disturbance
19 initiative
20 hospitality
21 mastermind
22 eyebrow
23 consciousness
24 operational
25 vehicle
26 housewife
27 capital
28 execution
29 terrify
30 disagree
31 exclusive
32 equinox
33 essential
34 imperial
35 publicity
36 secretary
37 nationalist
38 attention
39 established
40 magnitude
41 orientation
42 contraction
43 intention
44 seminar
45 forecast
46 manufacturer
47 reception
48 fabricate
49 mosquito
50 cooperative
51 parachute
52 exotic
53 demonstrate
54 production
55 spontaneous
56 minimum
57 abolish
58 holiday
59 formation
60 admission
61 handicap
62 continuous
63 presentation
64 constituency
65 unique
66 violation
67 radical
68 notebook
69 custody
70 dictionary
71 comprehensive
72 dominant
73 requirement
74 opponent
75 business
76 national
77 manufacture
78 nominate
79 liberal
80 continuation
81 galaxy
82 interest
83 ignorant
84 indirect
85 illustrate
86 proportion
87 projection
88 philosophy
89 acceptable
90 aluminium
91 continental
92 potential
93 vegetarian
94 elephant
95 advantage
96 recording
97 agenda
98 electronics
99 engagement
100 lonely