logo
Tags down

shadow

How can I specify a general (x,y) position in Python lists?


By : Spencer
Date : October 14 2020, 02:21 PM
To fix the issue you can do To solve this problem, you really need to be keeping the coordinates of the player's location in a variable. You are correct that your for loops are unnecessary. Here is one way to make this work, hopefully the comments will help you understand. It can probably be made smoother but should cover the majority of functionality you need.
code :
level = [
    ["1"," ","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],
    ["1"," "," ","1","1","1","1","1","1","1"," "," "," "," "," "," "," "," "," "," ","1","1","1","1","1"],
    ["1"," "," ","1","1","1","1","1","1","1"," "," ","1","1","1","1","1","1"," "," ","1","1","1","1","1"],
    ["1"," "," "," "," "," "," "," ","1","1"," "," ","1","1","1","1","1","1"," "," ","1","1","1","1","1"],
    ["1"," "," "," "," "," "," "," ","1","1"," "," ","1","1","1"," "," "," "," "," "," "," "," ","1","1"],
    ["1"," ","1","1","1","1"," "," ","1","1"," "," ","1","1","1"," "," "," "," "," "," "," "," ","1","1"],
    ["1"," ","1","1","1","1"," "," ","1","1"," "," ","1","1","1","1","1","1"," "," ","1","1","1","1","1"],
    ["1"," ","1","1","1","1"," "," ","1","1"," "," "," "," ","1","1","1","1"," "," ","1","1","1","1","1"],
    ["1"," "," ","1","1","1"," "," "," "," "," "," "," "," ","1","1","1","1"," "," "," "," "," "," ","1"],
    ["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"," ","1"]
]

def print_level(level):
    """ Print level row-wise so that it retains its 2D shape """
    for row in level:
        print(row)

# Object to store the player coords
player = {'y': 0, 'x': 1}
level[player['y']][player['x']] = 'X'
print_level(level)

# Translate keywords into coordinate changes
move_modifications = {'UP': {'y': -1, 'x': 0},
                      'DOWN': {'y': 1, 'x': 0},
                      'LEFT': {'y':0, 'x': -1},
                      'RIGHT': {'y': 0, 'x': 1}}

# Main game loop
while True:
    move = input("Which direction?")

    # Give them the option to quit
    if move.lower() == 'exit':
        break

    if not move_modifications.get(move):
        print("Invalid input")
        continue

    coords = move_modifications[move]

    new_y = player['y'] + coords['y']
    new_x = player['x'] + coords['x']

    # Catch them if they try to leave the map
    try:
        maze_position = level[new_y][new_x]
    except IndexError:
        print("Not on map")
        continue

    if maze_position != '1':
        # Move on the map
        level[player['y']][player['x']] = ' '
        level[new_y][new_x] = 'X'

        # Update player coords
        player['y'] = new_y
        player['x'] = new_x

        # Print result
        print_level(level)
    else:
        print("Oops, there's a wall")
def print_window(level, player_y, player_x, window_size=2):
    """ Print only the immediate surroundings of the player """
    min_y = max(0, player_y - window_size)
    max_y = min(len(level), player_y + window_size)

    min_x = max(0, player_x - window_size)
    max_x = min(len(level[0]), player_x + window_size)

    for row in level[min_y:max_y]:
        print(row[min_x:max_x])


Share : facebook icon twitter icon

How to create general lists / template lists in C#


By : SturtN
Date : March 29 2020, 07:55 AM
Any of those help I have one main class with several inherited members who all overload the same Draw method of the parent class, but have different Initialize methods. Is it somehow possible to use the same list type for every inherited class, and thus be able to iterate through the Draw-methods? I am pretty sure you can do this with templates in C++, but can't seem to find a way to do it in C#. Here is an example: , Try:
code :
IList<ExpandingWindow> windows = new List<ExpandingWindow>();

// initialize them via constructor
windows.Add(new MainMenu(A, B));    
windows.Add(new SideMenu(A, B, C));

foreach(var window in windows) {
    window.Draw();
}

Selecting a position from a lists using Python


By : Aaron Hillegass
Date : March 29 2020, 07:55 AM
Any of those help I want to create a program that selects a team from a lists and display the players name and postion. , add this to the end of your code :
code :
if  'A' is team:
    print 'TEAM A\n', 'At Position ', position , TeamA[position - 1]
if  'B' is team:
    print 'TEAM B\n', 'At Position ', position , TeamB[position - 1]

How to check same position in two different lists in python


By : MrLeo
Date : March 29 2020, 07:55 AM
around this issue I am new to python. , Use enumerate along with list_comprehension.
code :
>>> A = [0,0,0,0,0,20,40,0]
>>> B = [0,0,0,0,0,3,0,0]
>>> [B[i] for i,j in enumerate(A) if j != 0]
[3, 0]
>>> [B[i] for i,j in enumerate(A) if j]
[3, 0]

Position in Python Lists


By : Roxana Bratosin
Date : March 29 2020, 07:55 AM
will help you I am trying to write a code for operation between each element with all the other elements of a list but not with itself. Below is the code. , You can use enumerate to get the index. This may do what you up to:
code :
lis = [10, 20, 30, 30, 40, 50, 50, 50, 60, 70]

for idx1, el1 in enumerate(lis):
    sum_ = el1
    for  idx2, el2 in enumerate(lis):
        if idx1 != idx2:
             sum_ += (50 - (el2 - el1)/2) * 0.13
        print("score of %d is %f"%(idx1, sum_))

Python: for a list of lists, get mean value in each position


By : Jovan Magalong
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have a list of lists: , Here is a vectorised numpy-based solution.
code :
import numpy as np

a = [[-1, 0.67, 0.23, 0.11],
     [-1],
     [0.54, 0.24, -1],
     [0.2, 0.85, 0.8, 0.1, 0.9]]

# first create non-jagged numpy array
b = -np.ones([len(a), max(map(len, a))])

for i, j in enumerate(a):
    b[i][0:len(j)] = j

# count negatives per column (for use later)
neg_count = [np.sum(b[:, i]==-1) for i in range(b.shape[1])]

# set negatives to 0
b[b==-1] = 0

# calculate means
means = [np.sum(b[:, i])/(b.shape[0]-neg_count[i]) \
         if (b.shape[0]-neg_count[i]) != 0 else 0 \
         for i in range(b.shape[1])]

# [0.37,
#  0.58666666666666667,
#  0.51500000000000001,
#  0.10500000000000001,
#  0.90000000000000002]
Related Posts Related Posts :
  • Read a text file and remove all characters except alphabets & spaces in Python
  • Compute all powerset intersections of two lists
  • Applying literal_eval on string of lists of POS tags gives ValueError
  • Modelling a logic puzzle
  • What is the meaning of Copy_X in sklearn linear models
  • selenium.common.exceptions.ElementNotInteractableException: Message: Element is not displayed
  • pydev debugger does not stop in breakpoint
  • Python windows path regex
  • Flask and selenium-hub are not communicating when dockerised
  • How to use groupby on a single column and perform comparisons for multiple columns in Pandas?
  • Locate a python script without absolute path
  • Custom-formatted Django form errors appearing twice
  • Matploblib: Paint cells of matrix based on indexes stored in array
  • How to repeat a drawing horizontally in pygame (drawing done in a class method)?
  • How to convert numpy array from numpy.int64 to datetime?
  • How do I pad values in the array so that I get this?
  • Numpy generate random whole number
  • How to find Price Tag with Dollar Sign, thousand delimiter AND decimal point by Python Regex
  • Python Scikit - bad input shape when calling sklearn.metrics.precision_recall_curve
  • struggle to understand tkinter multi classes
  • Wait for Button to be pressed after selecting Radiobutton then run command (Tkinter)
  • BeautifulSoup find() returns tags, but no value between the tags. Why is this?
  • Approximation of F using Hooke's Law
  • suggestion on filtering lists items that corresponds to other lists
  • Sort a list using a partial match in another list
  • Can filter() contain two conditions?
  • Kivy popup button content doesn't show in the button
  • Python - masking in a for loop?
  • Find which term is repeated in a string, when given a known number of N occurrences in the string
  • Replace all elements in list Python
  • How can I speed up my MySQL (InnoDB) inserts?
  • Can I input a Byte Tensor to my RNN/LSTM model?
  • Autoincrement file names
  • Problems transforming data in a dataframe
  • Cant send keys with the selenium webdriver in python
  • Conditionally replacing strings in Pandas column
  • How to process data after reading from QIODevice.read()?
  • Iterating over a list of integers using map and using a list of functions
  • How to rewrite this SQL query in Python with pandas?
  • Matplotlib: boxplot stops programme execution
  • Optimize for cumprod() with two variables
  • python responses - Not all requests have been executed
  • Guaranteed method to match longest string in regular expression alternation
  • Trouble when storing API data in Python list
  • Running a python script through Windows Scheduler not working
  • python beginner syntax statement if-elif
  • Why does python find the line 'ens' but not 'tun' when using `for line in open()`
  • How to add result of previous row to contents of present row?
  • Train LSTM with probabilistic labels
  • AWS Cloudwatch Logstream - What is the key, and how can I set it when getting the logstream
  • Page Pagination/Scraping with Requests/BeautifulSoup
  • How to fix NoReverseMatch on redirect
  • Using a list to name output files in Arcpy
  • Need help conditionally vectorizing a list
  • I want to apply a threshold to pixels in image using python. Where did I make a mistake?
  • Problems unsing Beautiful Soup
  • python binning data openAI gym
  • Python: Argparse with list of lists
  • Creating Columns in m x 1 dataframe based on spaces in each row?
  • Explicit relative imports within a package not using the keyword from
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org