• Home

Maze 1 – 5 5
#####
# C D
# C #
P C #
#####

Maze 2 – 7 8
########
P #
###### #
# #
# ######
# #
######D#

Maze 1 – 5 5
#####
# C D
# C #
P C #
#####

Maze 2 – 7 8
########
P M H #
###### #
#LL M A#
#L######
#LLL #
######D#

## Python programming

Maze 1 – 5 5
#####
# C D
# C #
P CC#
#####

Maze 2 – 20 19
###################
# # # #M #
P ## # # ## # ### #
# #M C#C#C# M#
#########C#C#C# ###
# A #C#CCC# H#
# ##### ####### # #
# #CCC# # # #
# ###CCC##### ### #
# ##### # C#
# # # H #####C#
# #### ###### #C#
# # # # # #C#
### # ## # # ## ###
# M# # # # D
#C######## ## ### #
#C# # # #
#C# ######### #####
#C# A CCCC#
###################

## Python programming

LAVA = ‘L’
WALL = ‘#’
EMPTY = ‘ ‘
DOOR = ‘D’

PLAYER = ‘P’

ITEM = ‘I’
FOOD = ‘F’
DYNAMIC_ENTITY = ‘DE’
ABSTRACT_TILE = ‘AT’

COIN = ‘C’
POTION = ‘M’
HONEY = ‘H’
APPLE = ‘A’
WATER = ‘W’

APPLE_AMOUNT = -1
HONEY_AMOUNT = -5
WATER_AMOUNT = -5
POTION_AMOUNT = 20

UP = ‘w’
DOWN = ‘s’
LEFT = ‘a’
RIGHT = ‘d’
MOVE_DELTAS = {
UP: (-1, 0),
DOWN: (1, 0),
LEFT: (0, -1),
RIGHT: (0, 1),
}

MAX_HEALTH = 100
MAX_HUNGER = 10
MAX_THIRST = 10
LAVA_DAMAGE = 5

WIN_MESSAGE = ‘Congratulations! You have finished all levels and won the game!’
LOSS_MESSAGE = ‘You lose :(‘
ITEM_UNAVAILABLE_MESSAGE = ‘\nYou don\’t have any of that item!\n’

## Python programming

from __future__ import annotations
from typing import Optional
from a2_support import UserInterface, TextInterface
from constants import *

# Replace these <strings> with your name, student number and email address.

# Before submission, update this tag to reflect the latest version of the
# that you implemented, as per the blackboard changelog.
__version__ = 1.0

# Uncomment this function when you have completed the Level class and are ready
# to attempt the Model class.

# def load_game(filename: str) -> list[‘Level’]:
# “”” Reads a game file and creates a list of all the levels in order.

# Parameters:
# filename: The path to the game file

# Returns:
# A list of all Level instances to play in the game
# “””
# levels = []
# with open(filename, ‘r’) as file:
# for line in file:
# line = line.strip()
# if line.startswith(‘Maze’):
# _, _, dimensions = line[5:].partition(‘ – ‘)
# dimensions = [int(item) for item in dimensions.split()]
# levels.append(Level(dimensions))
# elif len(line) > 0 and len(levels) > 0:
# return levels

def main():
pass

if __name__ == ‘__main__’:
main()

## Python programming

from constants import PLAYER

class UserInterface:
“”” Abstract class providing an interface for any MazeRunner View class. “””
def draw(
self,
maze: ‘Maze’,
items: dict[tuple[int, int], ‘Item’],
player_position: tuple[int, int],
inventory: ‘Inventory’,
player_stats: tuple[int, int, int]
) -> None:
“”” Draws the current game state.

Parameters:
maze: The current Maze instance
items: The items on the maze
player_position: The position of the player
inventory: The player’s current inventory
player_stats: The (HP, hunger, thirst) of the player
“””
self._draw_level(maze, items, player_position)
self._draw_inventory(inventory)
self._draw_player_stats(player_stats)

def _draw_inventory(self, inventory: ‘Inventory’) -> None:
“”” Draws the inventory information. Implemented in subclasses.

Parameters:
inventory: The player’s current inventory
“””
raise NotImplementedError

def _draw_player_stats(self, player_stats: tuple[int, int, int]) -> None:
“”” Draws the players stats. Implemented in subclasses.

Parameters:
player_stats: The player’s current (HP, hunger, thirst)
“””
raise NotImplementedError

def _draw_level(
self,
maze: ‘Maze’,
items: dict[tuple[int, int], ‘Item’],
player_position: tuple[int, int]
) -> None:
“”” Draws the maze and all its items. Implemented in subclasses.

Parameters:
maze: The current maze for the level
items: Maps locations to the items currently at those locations
player_position: The current position of the player
“””
raise NotImplementedError

class TextInterface(UserInterface):
“”” A MazeRunner interface that uses ascii to present information. “””
def _draw_level(
self,
maze: ‘Maze’,
items: dict[tuple[int, int], ‘Item’],
player_position: tuple[int, int]
) -> None:
num_rows, num_cols = maze.get_dimensions()
for row in range(num_rows):
row_str = ”
for col in range(num_cols):
if (row, col) == player_position:
row_str += PLAYER
elif (row, col) in items:
row_str += items.get((row, col)).get_id()
else:
row_str += maze.get_tile((row, col)).get_id()
print(row_str)

def _draw_inventory(self, inventory: ‘Inventory’) -> None:
text = str(inventory) if inventory.get_items() != {} else ‘Empty’
print(‘—————\nInventory\n’ + text + ‘\n’ + ‘—————‘)

def _draw_player_stats(self, player_stats: tuple[int, int, int]) -> None:
hp, hunger, thirst = player_stats
print(f’HP: {hp}\nhunger: {hunger}\nthirst: {thirst}’)

## Python Programming

1. This HW will test your knowledge on Object Oriented Programming using Classes and Inheritance
2. Use meaningful names for classes, objects, attributes and methods
3. If there are two words in the variable use first word lowercase and first letter of second word upper case i.e., firstName, or underscore between the two words i.e first_name
4. Include appropriate comments in the code
5. Output should be displayed exactly as mentioned against each problem
6. Indent the lines of code appropriately

Q1: Employee.py : (50 points)

Write a class named Employee that holds the following data about an employee with attributes: name, ID number, department and job title.

Once you have written a class, write a program that creates three Employee objects to hold the following data:

Name

ID Number

Department

Job Title

Susan Meyers

47899

Accounting

Vice President

Mark Jones

39119

IT

Programmer

Joy Rogers

81774

Manufacturing

Engineer

The program should store this data in the three objects, then display the data for each employee on the screen.

Example OUTPUT:

Employee 1:
Name: Susan Meyers
ID number: 47899
Department: Accounting
Title: Vice President

Employee 2:
Name: Mark Jones
ID number: 39119
Department: IT
Title: Programmer

Employee 3:
Name: Joy Rogers
ID number: 81774
Department: Manufacturing
Title: Engineer

Q2: Customer.py : (50 points)

Write a class named Person with data attributes for a person’s name, address, and telephone number. Next, write another class named Customer that is a subclass of the Person class. The Customer class should have a data attribute for a customer number, and a Boolean data attribute indicating whether the customer wishes to be on a mailing list. Demonstrate an instance of the Customer class in a simple program.

Sample output:

Enter the name: john
Enter the address: 239 lovers lane
Enter the phone_number: 817-907-5367
Enter the customer number: 0011
Does the customer wish to be on the mailing list?(Yes/No) Yes

Customer information:
Name: john
Phone number: 817-907-5367
Customer Number: 0011
On Mailing List: True

## Python Programming

I’m looking for someone to help me with this task. It will run in Python IDLE, and all you have to do is read the file and follow the instructions. It MUST be implemented in the same way as it is in the file, and functions must run independently, as it will be marked if the functions are running or not, and it must be implemented in the correct structure.

## Python Programming

1. This homework tests your knowledge of Functions. So you need to use functions to get grades.
2. Adhere to the naming conventions discussed in class for variable names, program name and function names
3. Use meaningful names for variables
4. If there are two words in the variable use first word lowercase and first letter of second wordupper case i.e., firstName or underscore between 2 words i.e first_name
5. Include appropriate comments in the code
6. Output should be displayed exactly as mentioned against each problem
7. Indent the lines of code appropriately

Write a program that displays all of the prime numbers from 1 through 10. The program should have a loop that calls the is_prime function.

Hints:

Declare local variables under main() program

For each number, print whether or not it is prime.

Write for loop, use range function to loop through the total numbers.

Call is_prime function

print if the number is prime or not prime

Define is_prime function, ‘def is_prime(number):’

The is_prime function receives a number as an argument, and returns True if number is prime, False otherwise.

Sample Output:

number      is prime
————————
1      not prime
2      prime
3      prime
4      not prime
5      prime
6      not prime
7      prime
8      not prime
9      not prime
10      not prime

1. calories.py (25 points)

Write a program that calculates following and display Grams of fat, Fat calories, Grams of carbs, Carb calories in 2 decimal positions.

the number of calories that result from the fat using formula:

Calories from fat = fat grams * 9

the number of calories that result from the carbohydrates using formula:

Calories from carbs = carb grams * 4

Hints:

Declare local variables under main() program

Prompt the user to enter grams_fat and grams_carbs

Calculate calories from fat

Calculate calories from carbs

Define a function to display resulting calories –

def showCarbs(gramsFat, gramsCarbs, caloriesFat, caloriesCarbs):

Note: This function will be called from main()

Sample Output:

If fat grams consumed entered is 87

If carbohydrate grams consumed entered is 39 then the output would be:

Grams of fat:  87.00

Fat calories:  783.00

Grams of carbs:  39.00

Carb calories:  156.00

1. testscore.py (25 points)

Write a program that prompts the user to enter 5 test scores. The program should display a letter grade for each score and the average test score.

Hint:

Declare local variables under main() program

Prompts the user to enter 5 test scores

Define a function to calculate the average score: this should accept 5 test scores as argument and return the avg

Define a function to determine the letter grade: this should accept a test score as argument and return a letter grade based on the following grading scale.

90-100                A

80-89                   B

70-79                   C

60-69                   D

Below 60            F

Sample Output:

—————————————————-

score 1: 99.0                     A

score 2: 78.0                     C

score 3: 68.0                     D

score 4: 99.0                     A

score 5: 89.0                     B

—————————————————-

Average score:  86.6                     B

4. randomGuess.py (30 points)

Write a program that generates a random number in the range of 1 through 20, and asks the user to guess what the number is.

If the user’s guess is higher than the random number, the program should display “Too high, try again”.

If the user’ guess is lower than the random number, the program should display “Too low, try again”.

If the user guesses the number, the application should congratulate the user and generate a new random number so the game can start over.

The game continues until the user chooses to quit by entering 0 as input anytime.

Sample Output:

Enter a number between 1 and 20, or 0 to quit: 14
Too high, try again
Enter a number between 1 and 20, or 0 to quit: 5
Too low, try again
Enter a number between 1 and 20, or 0 to quit: 10
Too low, try again
Enter a number between 1 and 20, or 0 to quit: 13
Congratulations! You guessed the right number!
Enter a number between 1 and 20, or 0 to quit: 10
Too high, try again
Enter a number between 1 and 20, or 0 to quit: 5
Too low, try again
Enter a number between 1 and 20, or 0 to quit: 7
Too low, try again
Enter a number between 1 and 20, or 0 to quit: 9
Congratulations! You guessed the right number!
Enter a number between 1 and 20, or 0 to quit: 0
Thanks for playing!

## Python Programming

1. This homework tests your knowledge of File Handling and use of Lists data type.
2. Adhere to the naming conventions discussed in class for variable names, program name and function names
3. Use meaningful names for variables, functions etc
4. If there are two words in the variable use first word lowercase and first letter of second word upper case i.e., firstName or underscore between 2 words i.e first_name
5. Include appropriate comments in the code
6. Output should be displayed similar to as mentioned against each problem
7. Indent the lines of code appropriately

a ) write_num.py (30 points)

Create a num_list file to write a range of numbers from 1 through 101.

Hints:

Define main ():

Open a file named as num_list in write mode.

Use for loop to write a range of numbers from 1 through 101 into the file.

Close file

Use num_list file which got created in number 1.a. Write a program that will prompt the user to enter the name of the file (i.e. num_list.text), and display the first 10 lines of the file’s content. Use try/except construct to capture any file opening related errors such as invalid file name etc.

Hints:

Define main ():

Declare variables: line and counter, and initialize them

Prompt for file name: use input function

Open the file in read mode.

Use a while loop to read and display the first 10 lines

Use rstrip method to remove \n characters at the end of the line

Print the line

Update the counter when the line is read

Close file

Expected output:

Enter the name of the file: filename.txt

#

#

#

#

#

#

#

#

2. numanalysis.py (30 points)

Write a program that asks user to enter a series of 10 numbers. The program should store the numbers in a list then display the following data.

1. The list contents

2. The lowest number in the list

3.  The highest number in the list

4. The total of the number in the list

5. The average of the number in the list

Hints:

Define main ():

Declare variables and initialize them

Create an empty list

Use the for loop with the range function to loop through 10 numbers.

Prompt the User to enter the numbers from 1- 10.

Ex: Enter number 1 of 10:

Use append function to populate the  list

Use min, max, sum, functions to find the low , high and total number of the list.

Ex:  low = min(number_list)

Print the list contents

Print Low, high , total and average numbers of the list.

Expected output :

List: [#, #, #, #, #, #, #, #, #, #]

Low: #.##
High: #.##
Total: #.##
Average: #.##

## Python Programming

No one is unaware of the name of that famous English shipowner, Cunard.
In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons.
Eight years later, the company’s assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage.
In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas.
So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.
If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management.
No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success.
In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost.
Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents.
Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers.

## Python Programming

No one is unaware of the name of that famous English shipowner, Cunard.
In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons.
Eight years later, the company’s assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage.
In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas.
So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.

## Python Programming

Assignment Rules:
Open book and notes assignment

1. This homework tests your knowledge of File Handling, use of String methods, and use of Sets.
2. Adhere to the naming conventions discussed in class for variable names, program name and function names
3. Use meaningful names for variables, functions etc
4. If there are two words in the variable use first word lowercase and first letter of second word upper case i.e., firstName or underscore between 2 words i.e first_name
5. Include appropriate comments in the code
6. Output should be displayed similar to as mentioned against each problem
7. Indent the lines of code appropriately

1. char_analysis.py (40 points)

Write a program that reads the file’s contents and determine the following:

1. The number of Uppercase letters in the file
2. The number of Lowercase letters in the file
3. The number of digits in the file
4. The number of whitespace characters in the file

HINTS:

Define main():

Declare Local variables

Open file text.txt for reading. Use ‘text.txt’ file available under the Modules section in Canvas.

Use for loop to step through each character in the file.

Determine if the character is uppercase, lowercase, a digit, or space, and keep a running total of each.

Close the file.

Display the totals of uppercase, lowercase, digits, spaces.

Sample Output:

Uppercase letters: 29
Lowercase letters: 1228
Digits: 30

Spaces: 260

2. unique.py (30 points)

Write a program that opens a specified text file (text2.txt) and displays a list of all unique words found in the file.

HINTS:

Define main():

Declare Local variables

Open file text2.txt for reading. Use ‘text2.txt’ file available under the Modules section in Canvas.

Use ‘set’ method to find the unique words in the file and store each of them as an element of the set.

Close the file.

Display all the unique words from the set.

Sample output:

These are the unique words in the text:
management.
name
been
later,
canceled,
is
Eastern,
delay
Eight
1,820
at
it
1867
official
world
and
company,….

3. name.py (30)

Write a program that gets a string containing a person’s first, middle, and last names, and displays their first, middle, and last initials. For example, if the user enters Susan Smith Miller, the program should display S.S.M.

Define main():

Declare Local variables

Prompt user to enter the full name

Use ‘split’ method to split the full name

Use for loop to get first character of each name as an initial

Convert the first character to upper case if it is already not in upper case

Display output

Sample output:

Enter your full name: Susan Smith Miller
S.S.M.