Concept explainers
import random
from typing import Tuple, Optional
from typing import List
def make_grid(w: int, h: int, player_coord: Tuple[int, int],
gold_coord: Tuple[int, int]) -> List[List[str]]:
"""
Given two integers width w and height h, create a list
of lists to represent a grid of the given width and height.
The coordinates for the player and the gold
is also given as two two-element tuples. For each tuple,
the first element has the x-coordinate and the
second element has the y-coordinate. The player
and the gold should be included in the grid in
the positions specified by these tuples.
The player is represented with the string '(x)'
The gold is represented with the string '(o)'
All other spaces are represented with the string '(_)'
Return this list.
>>> make_grid(2, 3, (0, 0), (1, 2))
[['(x)', '(_)'], ['(_)','(_)'], ['(_)', '(o)']]
"""
grid = [['(_)' for i in range(w)] for j in range(h)]
x, y = player_coord
grid[y][x] = '(x)'
x, y = gold_coord
grid[y][x] = '(o)'
return grid
def print_grid(grid: List[List[str]]) -> None:
"""
Print out the grid stored in the variable "grid".
It should print out as described in the assignment
instructions.
e.g. if grid = [['(x)', '(_)'], ['(_)','(_)'], ['(_)', '(o)']]
this function should print out:
(x)(_)
(_)(_)
(_)(o)
."""
s = ''
for row in range(len(grid)):
s += ''.join(element for element in grid[row]) + "\n"
print(s)
def update_grid(grid: List[List[str]], w: int, h: int, px: int, py: int,
dx: int, dy: int) -> Optional[Tuple[int, int]]:
"""
Given the player's current position as px and py,
and the directional changes in dx
and dy, update the given grid to change the player's
x-coordinate by dx, and their y-coordinate by dy.
More information:
Use the given w and h (representing the grid's width
and height) to figure out whether or not the move is valid.
If the move is not valid (that is, if it is outside
of the grid's boundaries), then NO change occurs to the grid.
The grid stays the same, and nothing is returned.
If the move IS possible, then the grid is updated
by adding dx to the player's x-coordinate,
and adding dy to the player's y-coordinate.
The new position in the grid is changed to the player
icon '(x)', and the old position the player used to be in
is changed to an empty space '(_)'. The new x- and y- coordinates
of the player is returned as a tuple.
This function does NOT create or return a new grid.
It modifies the "grid" list that is passed into it directly.
>>> L = [['(x)', '(_)'], ['(_)', '(o)'], ['(_)', '(_)']]
>>> update_grid(L, 2, 3, 0, 0, 1, 0)
(1, 0)
>>> L
[['(_)', '(x)'], ['(_)', '(o)'], ['(_)', '(_)']]
>>> L = [['(x)', '(_)'], ['(_)', '(o)'], ['(_)', '(_)']]
>>> update_grid(L, 2, 3, 0, 0, 0, 1)
(0, 1)
>>> L
[['(_)', '(_)'], ['(x)', '(o)'], ['(_)', '(_)']]
>>> L = [['(x)', '(_)'], ['(_)', '(o)'], ['(_)', '(_)']]
>>> print(update_grid(L, 2, 3, 0, 0, -1, 0))
None
>>> L
[['(x)', '(_)'], ['(_)', '(o)'], ['(_)', '(_)']]
"""
if px + dx >= w or py + dy >= h or px+dx < 0 or py+dy < 0:
return
grid[py+dy][px+dx] = grid[py][px]
grid[py][px] = '(_)'
return (px+dx,py+dy)
def get_moves(d: str) -> Tuple[int, int]:
"""
Given a direction that is either 'N', 'S', 'E' or 'W'
(standing for North, South, East or West), return
a tuple representing the changes that would occur
to the x- and y- coordinates if a move is made in that
direction.
e.g. If d is 'W', that means the player should move
to the left. In order to do so, their x-coordinate should
decrease by 1. Their y-coordinate should stay the same.
These changes can be represented as the tuple (-1, 0),
because the x-coordinate would have -1 added to it,
and the y-coordinate would have 0 added to it.
>>> get_moves('W')
(-1, 0)
>>> get_moves('E')
(1, 0)
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
"""
if d == "N":
return 0, -1
elif d == "S":
return 0, 1
elif d == "E":
return 1, 0
else:
return -1, 0
def get_direction() -> str:
"""
Ask the user for a direction that is N, S, E or W.
Once a valid direction is given, return this direction.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
"""
d = input("Which way would you like to move? Choose N, S, E, W. ")
while (len(d) != 1) or (d.upper() not in 'NSEW'):
d = input("Invalid input. Choose N, S, E, W. ")
return d.upper()
if __name__ == "__main__":
w = int(input("Width: "))
h = int(input("Height: "))
p_x = p_y = 0
gold_x = random.randint(1, w - 1)
gold_y = random.randint(1, h - 1)
game_won = False
grid = make_grid(w, h, (p_x, p_y), (gold_x, gold_y))
while not game_won:
print_grid(grid)
d = get_direction()
# the following line unpacks the tuple returned by get_moves
# this means the first element in the returned tuple gets assigned
# to dx, the second element in the tuple assigned to dy
dx, dy = get_moves(d)
new_xy = update_grid(grid, w, h, p_x, p_y, dx, dy)
if new_xy:
p_x, p_y = new_xy
game_won = (p_x == gold_x) and (p_y == gold_y)
print("Congratulations! You won.")
Question: Show how many steps it takes and Make the treasure able to move away from the player as well
Trending nowThis is a popular solution!
Step by stepSolved in 2 steps with 1 images
- Has to be done in Java, import ArrayListarrow_forwardComplete the doctring.def average_daily_temp(high_temps: List[int], low_temps: List[int]) -> List[float]: """high_temps and low_temps are daily high and low temperatures for a series of days. Return a new list of temperatures where each item is the daily average. Precondition: len(high_temps) == len(low_temps) >>> average_daily_temp([26, 27, 27, 28, 27, 26], [20, 20, 20, 20, 21, 21]) [23.0, 23.5, 23.5, 24.0, 24.0, 23.5] """arrow_forwardpython LAB: Subtracting list elements from max When analyzing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalizing to values between 0 and 1, or throwing away outliers. Write a program that adjusts a list of values by subtracting each value from the maximum value in the list. The input begins with an integer indicating the number of integers that follow.arrow_forward
- a Strings > Exercise-Making a List Exercise: Making a List Lists are great. Here are some constants describing some of the things you've learned about strings so far: 6 let constants = "Declaring string constants" 7 let unicode = "Unicode characters ()" 8 let combining = "Combining strings using +" 9 let interpolation = "String interpolation (aka Fill in the Blanks)" 10 let escaping = "Escape characters for \"special powers\"" 11 let newline = "Making new lines" Experiment Make a new string constant that is a list of the things you've learned, with each entry on a new line. Make sure you add the result to the playground page so that you can see the list properly. 15 16 17 18 19 Previous | page 13 of 16 | Next: Exercise: A Restaurant 22arrow_forwardInstructions Write a program to test various operations of the class doublyLinkedList. Your program should accept a list of integers from a user and use the doubleLinkedList class to output the following: The list in ascending order. The list in descending order. The list after deleting a number. A message indicating if a number is contained in the list. Output of the list after using the copy constructor. Output of the list after using the assignment operator. An example of the program is shown below: Enter a list of positive integers ending with -999: 83 121 98 23 57 33 -999 List in ascending order: 23 33 57 83 98 121 List in descending order: 121 98 83 57 33 23 Enter item to be deleted: 57 List after deleting 57 : 23 33 83 98 121 Enter item to be searched: 23 23 found in the list. ********Testing copy constructor*********** intList: 23 33 83 98 121 ********Testing assignment operator*********** temp: 23 33 83 98 121 Your program should use the value -999 to denote the end of the…arrow_forwardPython Code Create a code that can plot a distance versus time graph by importing matplotlib and appending data from a text file to a list. Follow the algorithm: Import matplotlib. Create two empty lists: Time = [ ] and Distance = [ ] Open text file named Motion.txt (content attached). Append data from Motion.txt such that the first column is placed in Time list and the second column is placed in Distance list. Plot the lists (Distance vs Time Graph). You may use this following link as a source for matplotlib functions: https://datatofish.com/line-chart-python-matplotlib/ Show Plot.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education