Browse Source

Initial commit

feedback
github-classroom[bot] 2 years ago committed by GitHub
commit
6330da2784
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 3
      .github/workflows/main.yaml
  2. 160
      .gitignore
  3. 21
      LICENSE
  4. 137
      README.md
  5. 188
      hangman.py

3
.github/workflows/main.yaml

@ -0,0 +1,3 @@
name: lab-0
# add your pipline description below

160
.gitignore vendored

@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

21
LICENSE

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Mark Patterson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

137
README.md

@ -0,0 +1,137 @@
# Hangman Game
It is a Python console app word guessing game.
The player guesses one letter at a time.
If the guessed letter is in the word, the game reveals where that letter appears in the word. For instance, if the player guesses "p" and the word is "python", the display would change to "p _ _ _ _ _".
If the guessed letter is not in the word, a part of the 'hangman' is drawn.
Python console app hangman game based on the [code](https://github.com/markpatterson27/hangman-game) by [Mark Patterson](https://github.com/markpatterson27)
# Assignment
> :warning: **Note**: **Lab is counted as done, if you have your app is running on server, and pipelines are passing.**
### Installing poetry:
#### Why Poetry ?
Poetry is a tool for dependency management and packaging in Python. It allows to declare the libraries project depends on and it will manage (install/update) them. Poetry offers a lockfile to ensure repeatable installs, and can build your project for distribution.
One of the core features of Poetry is that making project environment isolation. By default, Poetry will try to use the Python version used during Poetry’s installation to create the virtual environment for the current project.
> :warning: **Note**: Poetry requires Python 3.8+.
#### To install Poetry:
(Linux, macOS, Windows (WSL))
<pre>curl -sSL https://install.python-poetry.org | python3 -
</pre>
Windows (Powershell)
<pre>(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -
</pre>
Once Poetry is installed you can execute the following:
<pre> poetry --version
</pre>
### Initialize poetry:
To initialize poetry in your project:
<pre>cd path/to/your/project </pre>
<pre> poetry init</pre>
It will ask you to insert some information, or you can use:
<pre>poetry init -n</pre>
for default intiliazation.
Once intilization poetry a ``pyproject.toml`` will be added to the project folder. The toml file is a configuration file contains build system requirements and information, which are used by pip to build the package.
### Poetry commands:
1. <pre>poetry install</pre>
The install command reads the ``pyproject.toml`` file from the current project, resolves the dependencies, and installs them.
When you run this command, one of two things may happen:
* Installing without poetry.lock:
If you have never run the command before and there is also no poetry.lock file present, Poetry simply resolves all dependencies listed in your ``pyproject.toml`` file and downloads the latest version of their files.
When Poetry has finished installing, it writes all the packages and their exact versions that it downloaded to the ``poetry.lock`` file, locking the project to those specific versions. You should commit the ``poetry.lock`` file to your project repo so all people working on the project are locked to the same versions of dependencies.
* Installing with poetry.lock:
If there is already a ``poetry.lock`` file and a ``pyproject.toml`` file when you run poetry install, it means either you ran the install command before, and committed the ``poetry.lock`` file to the project. This will use the exact versions from there instead of resolving them. This ensures that everyone using the library will get the same versions of the dependencies.
2. <pre>poetry update</pre>
In order to get the latest versions of the dependencies and to update the ``poetry.lock`` file, you should use the update command.This will resolve all dependencies of the project and write the exact versions into ``poetry.lock``.
3. <pre>poetry run python -V</pre>
The run command executes the given command inside the project’s virtualenv. It can also execute one of the scripts defined in ``pyproject.toml``.
### Organizing project folder:
Create new folder with the same of your project name and another folder with name 'tests'.
Inside each folder, create an \_\_init\_\_.py file
In Ubuntu:
<pre>cd /path/to/your/project</pre>
<pre>mkdir app tests</pre>
<pre>touch app/__init__.py tests/__init__.py</pre>
<pre>
app/
├── pyproject.toml
├── app
   └── __init__.py
└── tests
└── __init__.py
</pre>
### Install pytest
<pre>poetry add pytest</pre>
### Add a simple test for the hangman
In the tests folder, add `test_hangman.py` to check with pytest. This test case should pass as it will be verified with CI later.
The project tree after adding the test file should look like:
<pre>
app/
├── pyproject.toml
|── poetry.lock
├── app
   └── __init__.py
 └── hangman.py
└── tests
└── __init__.py
└── test_hangman.py
</pre>
### Add simple workflow
In `.github/workflows` folder add `main.yaml` file, which automates testing every time code is commited to the repository.
The workflow should contain the basic components.
Specify when the workflow should run (on push or pull request), outline the steps to set up the environment, and a command to run `pytest`.
This GitHub Actions workflow ensures automated testing for code quality and reliability.
```YAML
name: code quality test
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.12'
- name: Run image
uses: abatilo/actions-poetry@v2
with:
poetry-version: '1.7.1'
- name: Install dependencies
run: poetry install; poetry add pytest
- name: Run pytest
run: poetry run pytest .
```
> :warning: **Note**: check the python version and poetry version so that they are in sync with your `pyproject.toml` file
# Slides
> :warning: **Note**: [ Link to the presentation](https://docs.google.com/presentation/d/1R_D5KL-crTSb_vvWP39-Quqz0h2KMuGHxAtizo7ThqE/edit?usp=sharing)
# Hint
Look in the [tutorial](https://testdriven.io/blog/python-environments/)

188
hangman.py

@ -0,0 +1,188 @@
# Console based hangman game.
import random
import os
# Constants
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "hangman",
"computer", "science", "programming", "mathematics", "player", "condition",
"reverse", "water", "board", "geeks", "keyboard", "laptop", "headphone",
"mouse", "printer", "scanner", "software", "hardware", "network", "server")
HANGMAN_STAGES = (
"""
-------
|/ |
|
|
|
|
|
/|\\
-----------
""","""
-------
|/ |
| O
|
|
|
|
/|\\
-----------
""","""
-------
|/ |
| O
| |
|
|
|
/|\\
-----------
""","""
-------
|/ |
| O
| |
| |
|
|
/|\\
-----------
""","""
-------
|/ |
| O
| /|
| |
|
|
/|\\
-----------
""","""
-------
|/ |
| O
| /|\\
| |
|
|
/|\\
-----------
""","""
-------
|/ |
| O
| /|\\
| |
| /
|
/|\\
-----------
""","""
-------
|/ |
| O
| /|\\
| |
| / \\
|
/|\\
-----------
""")
# Functions
def clear_screen():
"""Clears the screen."""
os.system("cls" if os.name == "nt" else "clear")
def get_random_word():
"""Returns a random word from the WORDS tuple."""
return random.choice(WORDS)
def splash_screen():
"""The splash screen."""
print("""
_ _ -----
| | | | __ _ _ __ __ _ _ __ ___ __ _ _ __ | o
| |_| |/ _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\ | /|\\
| _ | (_| | | | | (_| | | | | | | (_| | | | | | / \\
|_| |_|\\__,_|_| |_|\\__, |_| |_| |_|\\__,_|_| |_| |
|___/ v1.0
""")
input("Press enter to continue...")
clear_screen()
def hangman():
"""The hangman game."""
try:
# game outer loop
while True:
# Setup
word = get_random_word()
guessed_letters = []
guessed_word = ["_"] * len(word)
wrong_guesses = 0
# game inner loop
while True:
clear_screen()
print("Hangman game. Try to guess the word. (CTRL+C to quit)")
print(HANGMAN_STAGES[wrong_guesses])
print(" ".join(guessed_word), end=' ')
print("(Guessed letters: " + ", ".join(guessed_letters),")")
print()
# check if player has won
if "_" not in guessed_word:
print("You win!")
break
# check if player has lost
if wrong_guesses == len(HANGMAN_STAGES)-1:
print("You lose!")
break
# make sure player enters a single letter
while True:
guess = input("Guess a letter: ").lower()
if len(guess) == 1 and guess.isalpha():
# check if letter has already been guessed
if guess in guessed_letters:
print("You have already guessed that letter.")
else:
break
else:
print("Invalid guess. Please enter a single letter.")
# add guess to guessed letters
guessed_letters.append(guess)
# check if guess is in word
if guess in word:
# add guess to guessed word
for i in range(len(word)):
if word[i] == guess:
guessed_word[i] = guess
else:
# increment wrong guesses
wrong_guesses += 1
# Ask the player if they want to play again
play_again = input("Play again? (y/n): ").lower()
if play_again != "y":
break
print("\nGoodbye!")
except KeyboardInterrupt:
print("\nGoodbye!")
exit()
# Main
if __name__ == "__main__":
splash_screen()
hangman()
Loading…
Cancel
Save