Uploaded by Manuel Giraldo Carro

Unit 1 Assignment 3 Programing

advertisement
Report Programming assignment
3
Interface – IDE - code
Manuel Giraldo Carro
0
Table of Contents
Introduction. .............................................................................................................................. 2
Program Interface and Program Code with ............................................................................... 2
Evaluation of developing application using the IDE ................................................................ 12
Evaluation of the debugging process in the IDE used how it helped with development........ 13
Bibliography: ............................................................................................................................ 18
1
Introduction.
In this task I am going to develop two applications and through this report, I will explain the
process and also some important points of view.
Program Interface and Program Code with
•
Program interface:
THE RPG INTERFACE
-------------------------------Get Ready---------------------------++++++++++++++++++The Game Begins+++++++++++++
Introduction text
******************* THE LION BRIDGE***************
Text
*******************THE DRAGON BRIDGE***********
Text
*******************THE WIZARD’S SHELTER***********
Text
******************THE GOLDEN VALLEY*************
--------------------------GAME OVER-------------------------------------
2
THE HANGMAN INTERFACE
----------------------THE HANGMAN GAME------------------Introduction text
Game begins 5
lifes (5 tries)
One error 4
lifes (4 tries)
Four errors
1lifes (1 tries)
Three errors 2
lifes (2 tries)
Two errors 3
lifes (3 tries)
Five error
Game Over
Program Code:
THE RPG CODE
Project proposal of my RPG code as Option 3 of this assignment suggests.
3
In this program, I will develop a text-based (RPG) which stands for Role-playing game. This
kind of game is about a player who advance through a story quest, this player will find
different scenarios where he finds different obstacles to solve.
Using the appropriate code, I will create these scenarios that will be visited by the player
depending on what options they choose to solve the obstacles.
Game will give to the player different possible answer or actions to do and make the player
interact.
The game will over whether the player solves correctly all obstacles, which will be declared
as winner or fail any of them, which will be declared game over.
Below is the flow chart of this program.
4
Developing code
#I will import the time module to speed down the text to read it easier.
import time
# Using the function def I will create some scenarios (packets) which I will recall
depending of the player choice.
# golden valley
def golden_valley():
# some text
print("")
print("************************* THE GOLDEN VALLEY***********************")
time.sleep(2)
print("Now you are in a beautiful valley called The Golden Valley!")
time.sleep (3)#time module to slow doen the text
print("There is a bridge too!")
time.sleep (1)
#I will create to option to be choosen by the player and make them interact with the
game
print("Choose one! (1 or 2)")
time.sleep (1)
print("1). Take some golden apples from any three.")
print("2). Just cross the bridge.")
# take input()
answer = input()
#depending on the answer given, the game will give differents scenarios.
if answer == "1":
print("Apples were poissoned")
time.sleep(1)
game_over("You ate them and you dead")#with this option choosen by the player, the
system return a response, in this case game over...
elif answer == "2":
print("Great. Apples were poissoned fortunately you didn't eat them ")
wizards_shelter()# With this option, the system takes the player to another scenario
#This methios will be used along all the game as can be seen below.
else:
# call game_over() with "reason"
game_over("You should learn how to type a number.")
# lion gate
def lion_bridge():
print("************************* THE LION BRIDGE***********************")
time.sleep(2)
print("You find a lion here.")
time.sleep (2)
print("Behind the lion is a bridge.")
time.sleep (2)
print("The lion is eating a delicious burger!")
time.sleep (2)
print("Choose an option. (1 or 2)")
print("1). Catch the burger.")
print("2). Mock the lion.")
# take input()
5
answer = input()
if answer == "1":
# the player is dead!
game_over("The lion killed you.")
elif answer == "2":
print("Nice, the lion moved out the bridge. You can cross it now!")
golden_valley()
else:
game_over("Don't you know how to type a simple number?")
# dragon bridge
def dragon_bridge():
# some prompts
print("")
print("************************* THE DRAGON BRIDGE***********************")
time.sleep(2)
print("Now you have found another bridge guarded by a dragon!")
time.sleep (2)
print("The dragon is sleeping")
time.sleep (2)
print("There is another bridge behind the dragon. Choose an option? (1 or 2)")
time.sleep (1)
print("1). Cross the bridge stealthily.")
print("2). Be brave and kill the dragon!")
answer = input()
if answer == "1":
print("Great! The dragon didn't hear you, you passed the bridge")
time.sleep(2)
golden_valley()
elif answer == "2":
game_over("The dragon woke up and burned you.")
else:
game_over("Again??. Go and learn how to type a number please.")
#The wizards shelter
def wizards_shelter():
print("")
print("************************* THE WIZARD'S SHELTER***********************")
time.sleep(2)
print("Now you are in the wizard's shelter")
time.sleep(2)
print("You have to play with him")
time.sleep(2)
print("Let's play a game")
time.sleep(2)
print("Guess the movie")
time.sleep(2)
movie = input("Guess the title of the movie. \nChoose and option. Only one chance,
if you fail you loss. (1 or 2)." )
if movie == "1":
6
title1 = input("The movie is H---- -OTT-R. Complete the title." ).upper()
if title1 == "HARRY POTTER":
print("Great!!! You have good knowledge about movies.")
time.sleep(2)
print("------YOU WIN-----")
else:
print("Wrong answer")
print("You have been hanged")
game_over("------------GAME OVER-----------")
elif movie == "2":
title2 = input ("The movie is S-A- W-R-. Complete the title." ).upper()
if title2 == "STAR WARS":
print("Great!!! You have good knowledge about movies.")
time.sleep(2)
print("------YOU WIN-----")
play_again()
else:
print("Wrong answer")
print("You have been hanged")
game_over("------------GAME OVER-----------")
else:
print("WRONG ANSWER")
game_over("Learn how to type a number")
play_again
# function to ask the player to play again or not
def play_again():
print("")
print("Would you like to play again? (Y or N)")
answer = input().lower()
if "y" in answer:
start()
else:
exit()
# game_over with "reasons"
def game_over(reason):
print("\n" + reason)
print("----------------------GAME OVER!----------------------------")
play_again()
7
#With this function the game start. Some text to guide and welcome to the player and
ready.
def start():
print()
print("-----------Get ready---------")
time.sleep(3)
print("+++++++++++The game begins!!!++++++++++++++")
time.sleep (1)
print("You are a brave Knight serving to your King.")
time.sleep (1)
print("You are in a mountain with a dark and deep precipice in front of you.")
time.sleep (1)
print("There is a bridge to your LEFT and another to your RIGHT, which one do you want
to cross? (L or R )")
answer = input().lower()
if "l" in answer:
lion_bridge()
elif "r" in answer:
dragon_bridge()
else:
game_over("Don't you know how to type something properly?")
# start the game
start()
THE HANGMAN GAME CODE:
#first of all I will import the module (time) to set a timer in the text and give time
to be read.
#Then I will import the module (random) to tell the system to make a random choice
from a list
import time
import random
#now I will create a list to be used by the system as random
movie_list = ["spiderman","hook","superman","cinderella","allien","godfellas"]
#Below I will write the introduction of the game to guide the player
print("")
print("---------------------THE HANGMAN GAME-------------------")
time.sleep(2)
print("Year 1556\nYou are in the middle of the main square in Salem.")
time.sleep(1)
print("Here, people is sentenced to death for witchcraft ")
time.sleep(1)
print("You have been sentenced to be hanged because you are suspictious\nto poisoned
people with magic pocimas")
time.sleep(1)
print("Population is shouting up. They want you dead")
time.sleep(1)
8
print("The only way to scape is playing the game, The HangMan Game")
time.sleep(1)
#Notice the use of time.sleep to speed down the text
time.sleep(1)
print("")
time.sleep(3)
print("A random word will be given to you")
time.sleep(2)
print("I will give you a clue. MOVIES")
time.sleep(3)
print("ok. Start!!!!")
#Now, using the function "def" I will create "boxes" with code to built the game,
those boxes can be called later on
#to create a loop depending on the answer given by the player.
def get_word():
word = random.choice(movie_list)#Here we use random module implemented at the
beginning to choose a word
return word.upper()#upper to convert all letters in capital and avoid error if the
player write lower case.
def play(word):
word_completion = "_" * len(word)#To create underscores same lenght that the word
choosen.
guessed = False
guessed_letters = []#the player can guess a letter...
guessed_words = []#...or a whole word
tries = 6 #six tries to choose the word, counting the head,body,both arms and legs
print("Let's play Hangman!")
print(display_hangman(tries))#below I have created a few basic drawings to be
showed as the player
#starts the game and makes any error.
print(word_completion)
print("\n")
while not guessed and tries > 0:#while loop to create the conditions for rounds
guess = input("WITCH!!!! Guess a letter or word: ").upper()
if len(guess) == 1 and guess.isalpha():#conditional isalpha for ony
characteres from the alphabet(letters)
if guess in guessed_letters:#when the player type the same letter again
print("You already tried the letter", guess)
elif guess not in word:#when the player makes a mistake
print(guess, "is not in the word.")
tries -= 1#if player fail in their guess then a life(try) will be
taken away from the total(6)
guessed_letters.append(guess)
else:
print("Damnit!! you guessed it,", guess, "is in the
word!")#condicional else when none of above options
guessed_letters.append(guess)
#is met so
when the player guesses the letter
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print("You already tried this letter", guess)
elif guess != word:
print(guess, "is not the word.")
9
tries -= 1
guessed_words.append(guess)#The append() method in python adds a
single item to the existing list.
#It doesn’t return a new list of items but will modify the original
list by adding the item to the end of the list.
else:
guessed = True
word_completion = word
else:
print("Not a valid guess.")
print(display_hangman(tries))
print(word_completion)
print("\n")
if guessed:
print("Congrats, you guessed the word! You win!")
time.sleep(1)
print("but...")
time.sleep(2)
print("This confirm our suspicions that you are a witch")
time.sleep(1)
print("so...")
time.sleep(1)
print("You will die hanged ANYWAY!!!!")
time.sleep(2)
print("HAHAHAHAHAHAHAHAHAHAHA")
time.sleep(1)
print("DIIIIIEEEEEEEEEEEE!!!!!")
else:
print("Sorry, you ran out of tries. The word was " + word + ". So finally you
will be hanged to deadth!")
time.sleep(2)
print("DDDIIIIIIIIIEEEEEEEEEEEEEEE!!!!!")
def display_hangman(tries):#these are the drawings mentioned above
stages = [ # final state: head, body, arms and legs
"""
-------|
|
|
O
|
\\|/
|
|
|
/ \\
""",
# head, body, arms and one leg
"""
-------|
|
|
O
|
\\|/
|
|
|
/
""",
# head, body and arms
"""
-------|
|
|
O
10
|
\\|/
|
|
|
""",
# head, torso, and one arm
"""
-------|
|
|
O
|
\\|
|
|
|
""",
# head and torso
"""
-------|
|
|
O
|
|
|
|
|
""",
# head
"""
-------|
|
|
O
|
|
|
""",
# initial empty state
"""
-------|
|
|
|
|
|
"""
]
return stages[tries]
def main():
word = get_word()
play(word)
while input("Would you like to play again? (Y/N) ").upper() == "Y":
word = get_word()
play(word)
if __name__ == "__main__":
main()
11
Evaluation of developing application using the IDE
The Integrated Creation Environment (IDE) is a software application that provides a user
interface for code development, testing, and debugging. It aids in the organisation of project
artefacts that are important to the software application's source code. It includes a number
of tools and features that simplify and standardise development based on the programming
language in which the code is written. Compiling and interpreting the programme are also
features of the IDEs. Eclipse for Java programming, Microsoft Visual Studio, Android Studio
for mobile app development, RStudio for R scripts, and PyCharm for Python programming are
some of the most widely used IDs.
What is an IDE? It is a software application that simplifies the visual representation of file
location and makes it more understandable for the user. It includes development tools
including text editors, code libraries, compilers, and test platforms, as well as build
automation and debugging.
Net Beans and Eclipse are two examples of integrated development environments (IDEs) that
include a compiler, interpreter, or both; other IDEs, such as Sharp Develop and Lazarus, do
not. Multiple programming processes can be combined into a single process using the
flexibility of an IDE. Some IDEs are focused on a single programming language, although they
also include cross-language capabilities. Multiple languages are supported by IDEs such as
Eclipse, ActiveState Komodo, IntelliJ IDEA, My Eclipse, Oracle JDeveloper, Net Beans,
Codenvy, and Microsoft Visual Studio.
Advantages
− Software applications, drivers, and utilities can all be created using IDEs.
− It allows you to write applications in any programming language without having to
spend a lot of time learning the syntax.
− The IDE can correct syntax, warn about memory leaks, and help with code quality,
among other things.
− It has improved efficiency, allowing you to code faster with less effort, and its features
aid in the organisation of resources, the prevention of errors, and the provision of
shortcuts.
− It facilitates collaboration by allowing a group of programmers to effortlessly
collaborate within an IDE.
− It gives easy-to-use software materials.
− When developing programmes, the IDE keeps track of resources like as library files,
header files, and so on.
− Pre-installed libraries for a specific programming language are an example of this.
− The use of syntax highlight features makes development easier.
− It simplifies the development of database applications. They offer database sorting,
searching, retrieval, and processing services.
12
− At the compile or build stage, IDEs can convert code from high-level languages to the
object code of the targeted platform.
− It aids in the organisation of code, creates code, and enables for searching.
Evaluation of the debugging process in the IDE used how it helped with development.
Debugging is the act of finding and eliminating current and potential errors (often known as
"bugs") in software code that might cause it to behave abnormally or crash. Debugging is used
to detect and fix bugs or problems in software or systems to prevent them from
malfunctioning. Debugging becomes more difficult when several subsystems or modules are
tightly connected, as each modification in one module may cause more bugs to arise in
another. Debugging a program can take longer than programming it.
To debug the program, the user must first identify the problem, isolate the source code, and
then correct it. Because knowledge of problem analysis is expected, a user of the program
must know how to fix the problem. The software will be ready to use after the bug has been
repaired. Debugging tools (sometimes known as debuggers) are used to detect coding
mistakes at various stages of development. They're used to recreate the error conditions,
then look at the program state at the moment to figure out what went wrong. Programmers
can follow the execution of the program step by step by assessing the value of variables and
stopping it if necessary to obtain the value of variables or reset program variables. Some
programming language packages include a debugger that can be used to check for flaws in
the code as it is being written at run time.
The debugging procedure is as follows:
1. Recreate the issue.
2. Describe the bug in detail. To get the specific explanation, try to get as much information
from the user as possible.
3. Take a screenshot of the software when the bug appears. Attempt to obtain all of the
program's variable values and states at that time.
4. Examine the snapshot in light of its current status and action. As a result, try to figure out
what's causing the bug.
5. Fix the existing bug while also making sure no new ones appear.
Evaluation of coding standards and the benefits to organisation using them.
Coding standard are a collection of procedures that can be defined for a specific programming
language, specifying a programming style, methods, and various procedures. These
13
procedures could be for different aspects of the program written in that language. They can
be regarded as essential characteristics of software development.
A coding standard ensures that all developers working on a project adhere to certain
guidelines. The code is simple to understand, and proper consistency is maintained.
Consistency has a positive impact on program quality and should be maintained while coding.
It should also be ensured that coding rules are followed consistently across all levels of the
system and do not contradict one another. The finished program code should appear to have
been written in a single session by a single developer.
− Use the features of PEP8 (Python Enhancement Proposal) for Better Syntax
PEP 8 has emerged as the style guide that most Python projects follow; it encourages a
readable and appealing code style. Every Python developer should read it at some point; here
are some of the most significant points:
Use 4-space indentation and no tabs.
Examples:
# Aligned with opening delimiter.
grow = function_name(variable_one, variable_two,
variable_three, variable_four)
# First line contains no argument. Second line onwards
# more indentation included to distinguish this from
# the rest.
def function_name(
variable_one, variable_two, variable_three,
variable_four):
print(variable_one)
The 4-space rule is not always mandatory and can be overruled for continuation line.
2. Use docstrings: There are both single and multi-line docstrings that can be used in Python.
However, the single line comment fits in one-line, triple quotes are used in both cases. These
are used to define a particular program or define a particular function.
Example:
def exam():
"""This is single line docstring"""
"""This is
a
14
multiline comment"""
3. Wrap lines so that they don’t exceed 79 characters
The Python standard library is conservative and requires limiting lines to 79 characters. The
lines can be wrapped using parenthesis, brackets, and braces. They should be used in
preference to backslashes.
Example:
with open('/path/from/where/you/want/to/read/file') as file_one, \
open('/path/where/you/want/the/file/to/be/written', 'w') as
file_two:
file_two.write(file_one.read())
4. Use of regular and updated comments are valuable to both the coders and users :
There are also various types and conditions that if followed can be of great help from
programs and users point of view. Comments should form complete sentences. If a comment
is a full sentence, its first word should be capitalized, unless it is an identifier that begins with
a lower case letter. In short comments, the period at the end can be omitted. In block
comments, there are more than one paragraphs and each sentence must end with a period.
Block comments and inline comments can be written followed by a single ‘#’.
Example of inline comments:
geek = geek + 1
# Increment
5. Use of trailing commas : This is not mandatory except while making a tuple.
Example:
tup = ("geek",)
6. Use spaces around operators and after commas, but not directly inside bracketing
constructs:
a = f(1, 2) + g(3, 4)
7. Naming Conventions :
15
There are few naming conventions that should be followed in order to make the program less
complex and more readable. At the same time, the naming conventions in Python is a bit of
mess, but here are few conventions that can be followed easily.
There is an overriding principle that follows that the names that are visible to the user as
public parts of API should follow conventions that reflect usage rather than implementation.
Here are few other naming conventions:
b (single lowercase letter)
B (single upper case letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords (or CamelCase). This is also sometimes known as StudlyCaps.
Note: While using abbreviations in CapWords, capitalize all the letters
of the abbreviation. Thus HTTPServerError is better than HttpServerError.
mixedCase (differs from CapitalizedWords by initial lowercase character!)
Capitalized_Words_With_Underscores
In addition to these few leading or trailing underscores are also considered.
Examples:
single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not
import objects whose name starts with an underscore.
single_trailing_underscore_: used to avoid conflicts with Python keyword.
Example:
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore:
when
naming
a
class
attribute,
(inside class FooBar, __boo becomes _FooBar__boo;).
invokes
name
mangling.
8. Characters that should not be used for identifiers :
‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single
character variable names as these are similar to the numerals one and zero.
9. Don’t use non-ASCII characters in identifiers if there is only the slightest chance
peoplespeaking a different language will read or maintain the code.
10. Name your classes and functions consistently: The convention is to use CamelCase for
16
classes and lower_case_with_underscores for functions and methods. Always use self as the
name for the first method argument.
11. While naming of function of methods always use self for the first argument to instance
methods and cls for the first argument to class methods. If a functions argument name
matches with reserved words then it can be written with a trailing comma. For e.g., class_
You can refer to this simple program to know how to write an understandable code:
Output:
The factorial of 7 is 5040
(Lenka, 2021)
17
Bibliography:
Lenka, C., 2021. PEP 8 : Coding Style guide in Python - GeeksforGeeks. [online] GeeksforGeeks.
Available at: <https://www.geeksforgeeks.org/pep-8-coding-style-guide-python/> [Accessed 26
December 2021].
18
Download