SlideShare a Scribd company logo
FINAL PROJECT
CIS 1051: INTRODUCTION TO PROBLEM SOLVING
AND PROGRAMMING IN PYTHON
MADE BY: SAMPRATEEK SINHA
New to coding?
If you know coding already you should be fine, but if you don’t know coding, don’t
worry I have provided links and the textbook. Practice and learn, you can become a
coding master in days… Let’s begin with the project.
About this course
This course introduces computer programming using Python, a computer language
which is widely used in industry, scientific research, game programming and web
applications. Students will learn how to design a program to solve a problem using
procedural programming constructs such as loops, branching structures, and
functions. Students will write programs that are testable (using assertions) and
maintainable (using good programming style, naming conventions, indentation, and
comments). Topics covered also include the general characteristics of computers,
techniques of problem solving, and algorithm specification. Students are also
introduced to software engineering practices, including unit testing techniques,
debugging techniques, and version control management.
If you want coding to be easy then… git
gud
 Here is the link to the book:
https://greenteapress.com/thinkpython2/thinkpython2.pdf
About the project
The program must include all of the following technical items:
 At least one list, At least one dictionary
 Use of user input
 Save and read files from a text file
 A loop, A conditional statement
 Exception handling
 The program must be broken into appropriate modules that encapsulate
the logic
 The program must have tests for at least five (5) functions.
The program must also include the following usability details... :
 Menus with letter based or numeric entries.
 The ability to quit the program cleanly at the appropriate times.
 The program should not crash if given bad input.
 The program should produce meaningful messages that inform the user how
to proceed if something is wrong.
Rules and Requirements
 Your program must contain at least two modules to separate logical concerns. You can have more
if it aids you in the program design.
 Your program must be run from a single entry point named "main.py". There can be other files that
aid your program but running this file should be the way to start the program.
 You may not use list comprehensions.
 You may not use regular expressions (regex or the re module). You must use loops and string
methods only. Any check that uses a regular expression will earn zero points.
 You may not use classes of your own creation to handle any of the main program logic.
 Your program should have one class that runs unit tests for your project. This class must be
contained within a file called "tests.py". The tests should not be imported into any of the main
program logic. That is, they should be totally isolated from the project but should test code from it.
PROJECT TOPIC: CARD GAMES
This card game is called Magical Animals. There are two players and a deck of 20 cards. The cards are
divided into two groups. The first group is attacking animals. They are:
1. Cat, 2. Eagle, 3. Liger, 4. Sea Serpent, 5. Gargoyle, 6. Hydra, 7. Vampire, 8. Giant, 9. Werewolf, 10. Dragon
The second group is defending animals. They are:
1. Dog, 2. Owl, 3. Gnome, 4. Mermaid, 5. Fairy, 6. Centaur, 7. Hippogriff, 8. Sphinx, 9. Gryphon, 10. Unicorn
The number next to each animal represents it's attacking or defending strength.
RULES OF THE GAME
To start, both players are dealt two cards from a shuffled deck of magical animal cards. The rules are as follows.
 If both players have defending animals, the game is a draw.
 If both players have attacking animals, the player whose animals have the higher total score wins.
 If one player has two attacking animals and the other has defending animals, then the player with the higher animal sum wins (Unicorn + Gryphon = 19 beats Hydra + Vampire = 13)
 If both players have one attacking animal and one defending animal, the player that delivers more damage wins. (Unicorn protects against 10 damage points and Giant delivers 8. This
beats a Werewolf and a Hippogriff because the 9 attacking points are stopped by the Unicorn and the 7 defense points aren't enough to stop the Giant).
 If one player has two attacking animals and the other has one attacking animal and one defending animal, then the sum of the two attacking animals is subtracted from the defending
animal and the player with the higher remaining attacking score wins.
 If one player has two defending animals and the other has one attacking animal and one defending animal, then the sum of the defending animals is subtracted from the attacking
animal. If the number is positive, the attacker wins, if it is negative, the defender wins.
 If either player has two attacking or two defending cards that total to 11 points, that player wins (for example: Dog + Unicorn = 11 and Eagle + Werewolf = 11). If both players have an
11 the victor is the defender. If both players have only defensive or attacking cards equaling 11, the victor is the player with the highest card.
 All cards are dealt on the table face up so the players can see one each other's cards.
 After the two cards are dealt to both players can decide to trade a card. The players must choose which card to trade and the cards will be dealt without them seeing the other player's
new card. That is to say, both players decide to trade a card and what card to trade in advance of seeing the other player's new card. Both new cards are revealed at the same time.
Some additional requirements
 The game must write to an external file the number of wins for each of the players
and the number of draws. The score should be loaded at the start of the game and
written back to the file after each round.
 This file must not be overwritten each time the game is played so that over many
runs of the program we can see which player is doing better.
 The cards must also be configurable and pull data from an external file. So if the
players want to change the names of the magical animals they can do so without
changing the actual program.
Now we know what to do let’s learn how
to do it
Don’t feel lost, this may seem daunting but we’ll get through with it. Don’t give up hope. Never gonna
give you up, never gonna let you down…..
Why Python is different
Python is one of the most popular coding languages that is being used currently in
the industry.
Unlike JavaScript, it does not require the use of semicolons or brackets to work. It is
based on indentation which means it uses spaces for its structure.
It is like a Swiss army knife in the programming world, due to its extensive use in
software development, web development, database analysis.
Click on this link to know more about Python:
https://www.w3schools.com/python/python_intro.asp
Technical terms you should know
List
Dictionary
Use of user input
Save and read files from a text file
A loop
A conditional statement
Exception handling
The program must be broken into appropriate modules that encapsulate the logic
The program must have tests for at least five (5) functions.
Python Collection (Arrays)
An array can hold many values under a single name, and you can access the values by referring to an
index number.
Ex: cars = [‘Audi’, ‘BMW’, ‘Toyota’], cars[0] = ‘Audi’
There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
For this project we are going to cover only Lists and Dictionaries only.
Lists
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
It behaves like a standard array. And is similar to the use of arrays in other coding languages like C and
JavaScript.
You can know more about lists and its different functions here:
https://www.w3schools.com/python/python_lists.asp
Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values. Unlike a
list where we access elements by
These are a bit similar to the use of a two dimensional array.
You can find out more about dictionaries here:
https://www.w3schools.com/python/python_dictionaries.asp
User Input
A good program is in which you can get an input from the user and be able to
process it. In python the way to get input from the user is by using input(). Inside the
parenthesis use strings to ask for input.
question = input(‘Please give me input: ‘)
Input can be taken in the form of strings as well as numeric. You do not need to
convert data type if you ask specific type of data. For example:
number = input(int(‘Please enter a number: ‘))
If the user enters an integer, they should be fine but if they enter a string then the
program will throw an error.
Saving and Reading Texts from File
In python you have the ability to read and write a text file.
If you want to read a file for example called numbers.txt, we write:
file_input = open(‘numbers.txt’)
This will store all the data from the text file into the variable called file_input. Be careful, this will also store the
non-essential line breaks, ‘n’ in the variable as well. If you need to remove them just use .strip() method to
remove all the line breaks and spaces.
By default Python uses the read method. If you need to write to it, use:
file_output = open(‘numbers.txt’, ‘w’)
The ‘w’ indicate write mode here. To write to the file, just use .write() and how you want the file to look like.
For example:
file_output.write(‘This is a text in a number file. ‘)
If you want to know more about Python read and write methods, click on the link.
https://www.geeksforgeeks.org/reading-writing-text-files-python/
Loops
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is
reached. There are two types of loops used in the Project, a for loop and a while loop.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming language, and works more like an iterator method as
found in other object-orientated programming languages. With the for loop we can execute a set of
statements, once for each item in a list, tuple, set etc. For more:
https://www.w3schools.com/python/python_for_loops.asp
With the while loop we can execute a set of statements as long as a condition is true.
You have to be careful while creating loops, if you create and do not specify when to stop it, you can create
an infinite loop. And while writing files you have to be even more careful, if you write to a file and if the loop
goes infinite… congratulations! Stop the execution otherwise it will fill up the storage.
In other words you just made a worm and did not even knew about it.
Conditional Statements
These are statements which support logical reasoning. In Python the use of an ‘if’ and ‘else’
statement is used to carry out the program.
For example, if the program asks the user to enter their age and if the age is grater than
65, it displays that they are eligible for pension, if not the program will display that they
are not eligible. The pseudocode would be:
Age = int(input(‘Please enter your age: ’)
If age > 65:
print(‘Eligible for pension’)
Else:
print(‘not eligible for pension’)
https://www.w3schools.com/python/python_conditions.asp
Exceptional Handling
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
Example:
try:
print(x)
except:
print("An exception occurred")
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
https://www.w3schools.com/python/python_try_except.asp
Breaking up program into modules – Functions
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
https://www.w3schools.com/python/python_functions.asp
Testing
 What happens if you write 1000 lines of your code and it does not run due to
some small spacing error or some misspelled functions? You should always test
the functions no matter what, to save time and also making the program more
streamlined. Python as these unit tests in which you can test each and every
function you created in order to not get any errors while running the program.
 https://docs.python.org/3/library/unittest.html
Now that you know the basics, lets work on the good
stuff, let’s talk about the project approach and the
project design…
Project Design
 This is the most fun part of the project, its basically how I came up with the design and logic for the
program. There are many ways to write a program and no two people will have the same way of making a
program.
 The process is made into different chunks and I will explain them in the upcoming slides with some
pseudocode as well.
 I will also show some of the snippets of code, which will help in understanding the logic and how python
codes are written.
 The codes will be available for you to download and play the game for yourselves.
If you feel creative…
 Go ahead and make some changes and customize the game, make it your own. After
all…
Making the Deck
The project starts with a deck, which is made of attacking animals and defending animals.
Attacking animals and Defending animals are made from text files containing the name of
animals and they are stored in order of their power. Once the deck is made, it gets shuffled
in order to ensure that the players get a random card. This was the basic setting up for the
game.
Example for making deck:
Get stripped data line by line from attack_animals.txt and defend_animals.txt
The values = line number in file
All cards are stored in deck
Deck is shuffled before playing the game
Player sees the cards
Now, two cards will be randomly taken from the deck and be displayed to the players with
total attack and defend scores. A hand is made for both players which will display two cards
at random. Then both of players will be given a choice to trade or stick with their cards. If
the player decide to trade their cards, they will be given a choice to choose which card to
trade, if player makes a choice between the cards, the cards are swapped and the game
results are declared.
Card swap function:
Make a trade or stick with card
If decision = trade, then call trade function
Else if decision = stick, do nothing
Trade function:
Which card to swap? 1 or 2?
If card = 1, change card 1
Else, change card 2
The Scoring System
The game is decided with the type and the score of each card that the players have to
themselves. The game gets the results from the game analysis function which contains all
rules for the game. There are three results, Player1 wins, or Player2 wins or there is a draw.
Once the results are taken, it gets stored in a list which is then written to a text file. The text
file helps in keeping a track of previous scores from the game.
Score function:
If player1 wins, then increase player1 score
Else if, player2 wins then then increase player2 score
Else if none of them win then increase draw score
Score write:
Write player1, player2, draw score to file.
If the file does not exists, make a new file with all the scores as zero.
How hands are compared
The result between the cards for two players is derived from the game rules. The
cards have
name, power and type attributes to them. For example I one rule is, if both players
have
defending animals, the game is a draw:
If player1’s card1 type is defend and player 1’s card 2 type is defend and player2’s
card1 type is defend and player2’s card2 type is defend, then game result is draw
PROJECT APPROACH – getting the card
names and values
The cards for the game were a lot similar to the playing cards in real life.
Using a list which has attack animals and defend animals by reading the text files
attack_animals.txt and defend_animals.txt
respectively.
PROJECT APPROACH – how a deck is
made
The deck is made by reading the elements of the animals and then added to the deck
which is a list. The deck contains multiple cards each made up of a dictionary. Then
the whole deck has a shuffle function which I got from Wikipedia (coding logic is all
about you but the rest is straight up plagiarism).
PROJECT APPROACH – creating hands
After the deck has been made, it randomly assigns two cards from the deck to both
the players. The hand function does this and returns a hand to the players.
PROJECT APPROACH – getting the result
The game starts and the attack scores and defends cores are displayed to the user.
After this the analysis function carries out the whole result and returns results either
win1, indicating player1 won or win2 which indicates that player2 won or draw which
means none of the players won the game. The analysis function contains the rules of
the game which checks for all the cards in the hand for each player. The result is
returned, and which used to update the scores.
PROJECT APPROACH – using functions for
result
When the game ends, the result is taken, and the score gets updated. The scores are read from the text file
with the first line indicating the draw point tally, the second line represents how many times player1 has won
and the third line shows the points for player2. For example, the game analysis function contains the game
rules, if both the players have attacking animals, the winner is declared from the total. So, If the type matches
from all cards, then a function compare total is called. This function then gets the total of both hands and
compares them and returns the result.
PROJECT APPROACH – player choice
 When the game is played, the cards are shown to players and players are given
the choice to trade or stick, I decided to call the function again if the user enters
anything else than trade or stick in order to make the program not break.
PROJECT APPROACH – player choice cont.
 Once the decisions are made, the game results is declared and score is updated.
PROJECT APPROACH – scoring system
 To figure out the scoring system, I decided
to store the scores in a text file, the first
represents draw, the second the player1
wins and the third line represents the
player2 win score. The scores is stored in a
list with the first index containing the draw
count, the first index containing player1
count, and the second index contains the
player2 count.
 The updated score is written to the same
file from where the scores were first taken
from. A menu is made to ask the user to
either see the scores, play the game or
quit. The game runs as long as the user
does not quit.
TESTING METHODOLOGY
 The testing for the project went similar to the cards lab, which involved making
various specific hands and testing the rules on them and returning the result. I
also used creating unittests to test the program by writing function specific tests
and running them.
Final Words…
 I have included the code files as well as scoring text for you to try it.
 Download Python3 and use IDLE to run the programs
 If you want to run the program, just open main.py
 If you want to see the unit tests, just run tests.py
 The other files are important for running main and there are files to rename the
attacking and defending animals. So go crazy
THANK YOU!
I hope you had fun reading and learning from the presentation. Please email me for feedback
and Keep Coding!

More Related Content

PPTX
Introduction to Python for Data Science and Machine Learning
PDF
Python-01| Fundamentals
PPTX
Python for Beginners(v1)
PPTX
Python second ppt
PPTX
Mastering Python lesson 4_functions_parameters_arguments
PPTX
Mastering Python lesson 3a
PPTX
Chapter 9 python fundamentals
PPTX
Mastering Python lesson 5a_lists_list_operations
Introduction to Python for Data Science and Machine Learning
Python-01| Fundamentals
Python for Beginners(v1)
Python second ppt
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 3a
Chapter 9 python fundamentals
Mastering Python lesson 5a_lists_list_operations

What's hot (20)

PPTX
Python-04| Fundamental data types vs immutability
PDF
Let’s Learn Python An introduction to Python
PPSX
Programming with Python
PPTX
Mastering python lesson2
PPTX
Python Session - 3
PPTX
Intro to Python Programming Language
PPT
Python Programming Language
PPTX
Fundamentals of Python Programming
PPTX
Mastering Python lesson3b_for_loops
PDF
Python programming msc(cs)
PPTX
11 Unit 1 Chapter 03 Data Handling
PPTX
Python training
PPTX
Learn Python The Hard Way Presentation
PDF
Lesson 03 python statement, indentation and comments
PPTX
Python introduction towards data science
PPTX
Python Tutorial Part 1
PPTX
Welcome to python workshop
DOCX
Python interview questions
PDF
CIS 1403 Lab 2- Data Types and Variables
PPTX
Python 3 Programming Language
Python-04| Fundamental data types vs immutability
Let’s Learn Python An introduction to Python
Programming with Python
Mastering python lesson2
Python Session - 3
Intro to Python Programming Language
Python Programming Language
Fundamentals of Python Programming
Mastering Python lesson3b_for_loops
Python programming msc(cs)
11 Unit 1 Chapter 03 Data Handling
Python training
Learn Python The Hard Way Presentation
Lesson 03 python statement, indentation and comments
Python introduction towards data science
Python Tutorial Part 1
Welcome to python workshop
Python interview questions
CIS 1403 Lab 2- Data Types and Variables
Python 3 Programming Language
Ad

Similar to Sam python pro_points_slide (20)

PPTX
python introduction initial lecture unit1.pptx
PPTX
PPt Revision of the basics of python1.pptx
PPTX
Python fundamentals
PPTX
Introduction on basic python and it's application
PPTX
Python (Data Analysis) cleaning and visualize
PDF
How To Tame Python
PDF
AI in FinTech Introduction chapter AI(MBA)
PDF
Python Interview Questions And Answers
PDF
Intro-to-Python-Part-1-first-part-edition.pdf
DOCX
Hey i have attached the required file for my assignment.and addi
PPT
Spsl iv unit final
PPT
Spsl iv unit final
DOCX
3 pagesPart 1Python comes with a program called an IDLE, wh.docx
PDF
Python Interview Questions PDF By ScholarHat.pdf
PDF
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
PPTX
Integrating Python with SQL (12345).pptx
DOCX
Python interview questions and answers
PDF
Python interview questions and answers
PDF
pyton Notes1
PDF
Tutorial machine learning with python - a tutorial
python introduction initial lecture unit1.pptx
PPt Revision of the basics of python1.pptx
Python fundamentals
Introduction on basic python and it's application
Python (Data Analysis) cleaning and visualize
How To Tame Python
AI in FinTech Introduction chapter AI(MBA)
Python Interview Questions And Answers
Intro-to-Python-Part-1-first-part-edition.pdf
Hey i have attached the required file for my assignment.and addi
Spsl iv unit final
Spsl iv unit final
3 pagesPart 1Python comes with a program called an IDLE, wh.docx
Python Interview Questions PDF By ScholarHat.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Integrating Python with SQL (12345).pptx
Python interview questions and answers
Python interview questions and answers
pyton Notes1
Tutorial machine learning with python - a tutorial
Ad

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Cell Types and Its function , kingdom of life
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Institutional Correction lecture only . . .
PDF
Complications of Minimal Access Surgery at WLH
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Pre independence Education in Inndia.pdf
01-Introduction-to-Information-Management.pdf
Final Presentation General Medicine 03-08-2024.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial disease of the cardiovascular and lymphatic systems
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Microbial diseases, their pathogenesis and prophylaxis
Cell Types and Its function , kingdom of life
FourierSeries-QuestionsWithAnswers(Part-A).pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
RMMM.pdf make it easy to upload and study
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Institutional Correction lecture only . . .
Complications of Minimal Access Surgery at WLH
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
human mycosis Human fungal infections are called human mycosis..pptx

Sam python pro_points_slide

  • 1. FINAL PROJECT CIS 1051: INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING IN PYTHON MADE BY: SAMPRATEEK SINHA
  • 2. New to coding? If you know coding already you should be fine, but if you don’t know coding, don’t worry I have provided links and the textbook. Practice and learn, you can become a coding master in days… Let’s begin with the project.
  • 3. About this course This course introduces computer programming using Python, a computer language which is widely used in industry, scientific research, game programming and web applications. Students will learn how to design a program to solve a problem using procedural programming constructs such as loops, branching structures, and functions. Students will write programs that are testable (using assertions) and maintainable (using good programming style, naming conventions, indentation, and comments). Topics covered also include the general characteristics of computers, techniques of problem solving, and algorithm specification. Students are also introduced to software engineering practices, including unit testing techniques, debugging techniques, and version control management.
  • 4. If you want coding to be easy then… git gud  Here is the link to the book: https://greenteapress.com/thinkpython2/thinkpython2.pdf
  • 5. About the project The program must include all of the following technical items:  At least one list, At least one dictionary  Use of user input  Save and read files from a text file  A loop, A conditional statement  Exception handling  The program must be broken into appropriate modules that encapsulate the logic  The program must have tests for at least five (5) functions. The program must also include the following usability details... :  Menus with letter based or numeric entries.  The ability to quit the program cleanly at the appropriate times.  The program should not crash if given bad input.  The program should produce meaningful messages that inform the user how to proceed if something is wrong.
  • 6. Rules and Requirements  Your program must contain at least two modules to separate logical concerns. You can have more if it aids you in the program design.  Your program must be run from a single entry point named "main.py". There can be other files that aid your program but running this file should be the way to start the program.  You may not use list comprehensions.  You may not use regular expressions (regex or the re module). You must use loops and string methods only. Any check that uses a regular expression will earn zero points.  You may not use classes of your own creation to handle any of the main program logic.  Your program should have one class that runs unit tests for your project. This class must be contained within a file called "tests.py". The tests should not be imported into any of the main program logic. That is, they should be totally isolated from the project but should test code from it.
  • 7. PROJECT TOPIC: CARD GAMES This card game is called Magical Animals. There are two players and a deck of 20 cards. The cards are divided into two groups. The first group is attacking animals. They are: 1. Cat, 2. Eagle, 3. Liger, 4. Sea Serpent, 5. Gargoyle, 6. Hydra, 7. Vampire, 8. Giant, 9. Werewolf, 10. Dragon The second group is defending animals. They are: 1. Dog, 2. Owl, 3. Gnome, 4. Mermaid, 5. Fairy, 6. Centaur, 7. Hippogriff, 8. Sphinx, 9. Gryphon, 10. Unicorn The number next to each animal represents it's attacking or defending strength.
  • 8. RULES OF THE GAME To start, both players are dealt two cards from a shuffled deck of magical animal cards. The rules are as follows.  If both players have defending animals, the game is a draw.  If both players have attacking animals, the player whose animals have the higher total score wins.  If one player has two attacking animals and the other has defending animals, then the player with the higher animal sum wins (Unicorn + Gryphon = 19 beats Hydra + Vampire = 13)  If both players have one attacking animal and one defending animal, the player that delivers more damage wins. (Unicorn protects against 10 damage points and Giant delivers 8. This beats a Werewolf and a Hippogriff because the 9 attacking points are stopped by the Unicorn and the 7 defense points aren't enough to stop the Giant).  If one player has two attacking animals and the other has one attacking animal and one defending animal, then the sum of the two attacking animals is subtracted from the defending animal and the player with the higher remaining attacking score wins.  If one player has two defending animals and the other has one attacking animal and one defending animal, then the sum of the defending animals is subtracted from the attacking animal. If the number is positive, the attacker wins, if it is negative, the defender wins.  If either player has two attacking or two defending cards that total to 11 points, that player wins (for example: Dog + Unicorn = 11 and Eagle + Werewolf = 11). If both players have an 11 the victor is the defender. If both players have only defensive or attacking cards equaling 11, the victor is the player with the highest card.  All cards are dealt on the table face up so the players can see one each other's cards.  After the two cards are dealt to both players can decide to trade a card. The players must choose which card to trade and the cards will be dealt without them seeing the other player's new card. That is to say, both players decide to trade a card and what card to trade in advance of seeing the other player's new card. Both new cards are revealed at the same time.
  • 9. Some additional requirements  The game must write to an external file the number of wins for each of the players and the number of draws. The score should be loaded at the start of the game and written back to the file after each round.  This file must not be overwritten each time the game is played so that over many runs of the program we can see which player is doing better.  The cards must also be configurable and pull data from an external file. So if the players want to change the names of the magical animals they can do so without changing the actual program.
  • 10. Now we know what to do let’s learn how to do it Don’t feel lost, this may seem daunting but we’ll get through with it. Don’t give up hope. Never gonna give you up, never gonna let you down…..
  • 11. Why Python is different Python is one of the most popular coding languages that is being used currently in the industry. Unlike JavaScript, it does not require the use of semicolons or brackets to work. It is based on indentation which means it uses spaces for its structure. It is like a Swiss army knife in the programming world, due to its extensive use in software development, web development, database analysis. Click on this link to know more about Python: https://www.w3schools.com/python/python_intro.asp
  • 12. Technical terms you should know List Dictionary Use of user input Save and read files from a text file A loop A conditional statement Exception handling The program must be broken into appropriate modules that encapsulate the logic The program must have tests for at least five (5) functions.
  • 13. Python Collection (Arrays) An array can hold many values under a single name, and you can access the values by referring to an index number. Ex: cars = [‘Audi’, ‘BMW’, ‘Toyota’], cars[0] = ‘Audi’ There are four collection data types in the Python programming language:  List is a collection which is ordered and changeable. Allows duplicate members.  Tuple is a collection which is ordered and unchangeable. Allows duplicate members.  Set is a collection which is unordered and unindexed. No duplicate members.  Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. For this project we are going to cover only Lists and Dictionaries only.
  • 14. Lists A list is a collection which is ordered and changeable. In Python lists are written with square brackets. It behaves like a standard array. And is similar to the use of arrays in other coding languages like C and JavaScript. You can know more about lists and its different functions here: https://www.w3schools.com/python/python_lists.asp
  • 15. Dictionaries A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. Unlike a list where we access elements by These are a bit similar to the use of a two dimensional array. You can find out more about dictionaries here: https://www.w3schools.com/python/python_dictionaries.asp
  • 16. User Input A good program is in which you can get an input from the user and be able to process it. In python the way to get input from the user is by using input(). Inside the parenthesis use strings to ask for input. question = input(‘Please give me input: ‘) Input can be taken in the form of strings as well as numeric. You do not need to convert data type if you ask specific type of data. For example: number = input(int(‘Please enter a number: ‘)) If the user enters an integer, they should be fine but if they enter a string then the program will throw an error.
  • 17. Saving and Reading Texts from File In python you have the ability to read and write a text file. If you want to read a file for example called numbers.txt, we write: file_input = open(‘numbers.txt’) This will store all the data from the text file into the variable called file_input. Be careful, this will also store the non-essential line breaks, ‘n’ in the variable as well. If you need to remove them just use .strip() method to remove all the line breaks and spaces. By default Python uses the read method. If you need to write to it, use: file_output = open(‘numbers.txt’, ‘w’) The ‘w’ indicate write mode here. To write to the file, just use .write() and how you want the file to look like. For example: file_output.write(‘This is a text in a number file. ‘) If you want to know more about Python read and write methods, click on the link. https://www.geeksforgeeks.org/reading-writing-text-files-python/
  • 18. Loops In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached. There are two types of loops used in the Project, a for loop and a while loop. A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. For more: https://www.w3schools.com/python/python_for_loops.asp With the while loop we can execute a set of statements as long as a condition is true. You have to be careful while creating loops, if you create and do not specify when to stop it, you can create an infinite loop. And while writing files you have to be even more careful, if you write to a file and if the loop goes infinite… congratulations! Stop the execution otherwise it will fill up the storage. In other words you just made a worm and did not even knew about it.
  • 19. Conditional Statements These are statements which support logical reasoning. In Python the use of an ‘if’ and ‘else’ statement is used to carry out the program. For example, if the program asks the user to enter their age and if the age is grater than 65, it displays that they are eligible for pension, if not the program will display that they are not eligible. The pseudocode would be: Age = int(input(‘Please enter your age: ’) If age > 65: print(‘Eligible for pension’) Else: print(‘not eligible for pension’) https://www.w3schools.com/python/python_conditions.asp
  • 20. Exceptional Handling The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks. Example: try: print(x) except: print("An exception occurred") When an error occurs, or exception as we call it, Python will normally stop and generate an error message. https://www.w3schools.com/python/python_try_except.asp
  • 21. Breaking up program into modules – Functions  A function is a block of code which only runs when it is called.  You can pass data, known as parameters, into a function.  A function can return data as a result. In Python a function is defined using the def keyword: def my_function(): print("Hello from a function") To call a function, use the function name followed by parenthesis: def my_function(): print("Hello from a function") my_function() https://www.w3schools.com/python/python_functions.asp
  • 22. Testing  What happens if you write 1000 lines of your code and it does not run due to some small spacing error or some misspelled functions? You should always test the functions no matter what, to save time and also making the program more streamlined. Python as these unit tests in which you can test each and every function you created in order to not get any errors while running the program.  https://docs.python.org/3/library/unittest.html
  • 23. Now that you know the basics, lets work on the good stuff, let’s talk about the project approach and the project design…
  • 24. Project Design  This is the most fun part of the project, its basically how I came up with the design and logic for the program. There are many ways to write a program and no two people will have the same way of making a program.  The process is made into different chunks and I will explain them in the upcoming slides with some pseudocode as well.  I will also show some of the snippets of code, which will help in understanding the logic and how python codes are written.  The codes will be available for you to download and play the game for yourselves.
  • 25. If you feel creative…  Go ahead and make some changes and customize the game, make it your own. After all…
  • 26. Making the Deck The project starts with a deck, which is made of attacking animals and defending animals. Attacking animals and Defending animals are made from text files containing the name of animals and they are stored in order of their power. Once the deck is made, it gets shuffled in order to ensure that the players get a random card. This was the basic setting up for the game. Example for making deck: Get stripped data line by line from attack_animals.txt and defend_animals.txt The values = line number in file All cards are stored in deck Deck is shuffled before playing the game
  • 27. Player sees the cards Now, two cards will be randomly taken from the deck and be displayed to the players with total attack and defend scores. A hand is made for both players which will display two cards at random. Then both of players will be given a choice to trade or stick with their cards. If the player decide to trade their cards, they will be given a choice to choose which card to trade, if player makes a choice between the cards, the cards are swapped and the game results are declared. Card swap function: Make a trade or stick with card If decision = trade, then call trade function Else if decision = stick, do nothing Trade function: Which card to swap? 1 or 2? If card = 1, change card 1 Else, change card 2
  • 28. The Scoring System The game is decided with the type and the score of each card that the players have to themselves. The game gets the results from the game analysis function which contains all rules for the game. There are three results, Player1 wins, or Player2 wins or there is a draw. Once the results are taken, it gets stored in a list which is then written to a text file. The text file helps in keeping a track of previous scores from the game. Score function: If player1 wins, then increase player1 score Else if, player2 wins then then increase player2 score Else if none of them win then increase draw score Score write: Write player1, player2, draw score to file. If the file does not exists, make a new file with all the scores as zero.
  • 29. How hands are compared The result between the cards for two players is derived from the game rules. The cards have name, power and type attributes to them. For example I one rule is, if both players have defending animals, the game is a draw: If player1’s card1 type is defend and player 1’s card 2 type is defend and player2’s card1 type is defend and player2’s card2 type is defend, then game result is draw
  • 30. PROJECT APPROACH – getting the card names and values The cards for the game were a lot similar to the playing cards in real life. Using a list which has attack animals and defend animals by reading the text files attack_animals.txt and defend_animals.txt respectively.
  • 31. PROJECT APPROACH – how a deck is made The deck is made by reading the elements of the animals and then added to the deck which is a list. The deck contains multiple cards each made up of a dictionary. Then the whole deck has a shuffle function which I got from Wikipedia (coding logic is all about you but the rest is straight up plagiarism).
  • 32. PROJECT APPROACH – creating hands After the deck has been made, it randomly assigns two cards from the deck to both the players. The hand function does this and returns a hand to the players.
  • 33. PROJECT APPROACH – getting the result The game starts and the attack scores and defends cores are displayed to the user. After this the analysis function carries out the whole result and returns results either win1, indicating player1 won or win2 which indicates that player2 won or draw which means none of the players won the game. The analysis function contains the rules of the game which checks for all the cards in the hand for each player. The result is returned, and which used to update the scores.
  • 34. PROJECT APPROACH – using functions for result When the game ends, the result is taken, and the score gets updated. The scores are read from the text file with the first line indicating the draw point tally, the second line represents how many times player1 has won and the third line shows the points for player2. For example, the game analysis function contains the game rules, if both the players have attacking animals, the winner is declared from the total. So, If the type matches from all cards, then a function compare total is called. This function then gets the total of both hands and compares them and returns the result.
  • 35. PROJECT APPROACH – player choice  When the game is played, the cards are shown to players and players are given the choice to trade or stick, I decided to call the function again if the user enters anything else than trade or stick in order to make the program not break.
  • 36. PROJECT APPROACH – player choice cont.  Once the decisions are made, the game results is declared and score is updated.
  • 37. PROJECT APPROACH – scoring system  To figure out the scoring system, I decided to store the scores in a text file, the first represents draw, the second the player1 wins and the third line represents the player2 win score. The scores is stored in a list with the first index containing the draw count, the first index containing player1 count, and the second index contains the player2 count.  The updated score is written to the same file from where the scores were first taken from. A menu is made to ask the user to either see the scores, play the game or quit. The game runs as long as the user does not quit.
  • 38. TESTING METHODOLOGY  The testing for the project went similar to the cards lab, which involved making various specific hands and testing the rules on them and returning the result. I also used creating unittests to test the program by writing function specific tests and running them.
  • 39. Final Words…  I have included the code files as well as scoring text for you to try it.  Download Python3 and use IDLE to run the programs  If you want to run the program, just open main.py  If you want to see the unit tests, just run tests.py  The other files are important for running main and there are files to rename the attacking and defending animals. So go crazy
  • 40. THANK YOU! I hope you had fun reading and learning from the presentation. Please email me for feedback and Keep Coding!