Moving Position of Character Within an Item in List

Move an item inside a list?

Use the insert method of a list:

l = list(...)
l.insert(index, item)

Alternatively, you can use a slice notation:

l[index:index] = [item]

If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:

l.insert(newindex, l.pop(oldindex))

Moving a a character on a map using list indexes

I'll start from the secondary question you had. Here's a reconstruction of your map-drawing function using loops.

world_map = [
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],
[' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K'],
]


def draw_map(world_map):
width = len(world_map[0])
header = "---".join(["+"] * (width + 1)) # Compute header line.
for row in world_map:
print(header) # Print header leading each line.
print("| {} |".format(" | ".join(row))) # Format and print the row.
print(header) # Print final header (well, footer).


draw_map(world_map)

Okay, cool beans, now what about the player character?

In general, games like this are structured in a way that your moving entities, such as characters, enemies, etc. are separate entities and the static map is stored in an array like yours.

Firstly, we'll need a modification to the draw_map function so we can keep track of each X/Y coordinate as we render the map:

def draw_map(world_map):
width = len(world_map[0])
header = "---".join(["+"] * (width + 1)) # Compute header line.
for y, row in enumerate(world_map):
print(header) # Print header leading each line.
# Figure out which characters to print in each cell.
chars = []
for x, c in enumerate(row):
chars.append(str(c))
print("| {} |".format(" | ".join(chars)))
print(header) # Print final header (well, footer).

(The output is still the same.)

Now let's store the hero position in a variable, hero_position sounds good enough. Let's also figure out a position for a big evil monster, and come up with some suitable characters for the two. And now for the rendering magic... Since each cell of the map can only render one thing – either the ground tile or the hero or the evil thing, we can pass their coordinates in as a dict, character_positions (and if you have a list of characters, it's easy to form such a dict).

The magic is character_positions.get() here with the second parameter; basically, we see if the x/y coordinate we're drawing exists in the coordinates dict, and use that character instead.

def draw_map(world_map, character_positions):
width = len(world_map[0])
header = "---".join(["+"] * (width + 1)) # Compute header line.
for y, row in enumerate(world_map):
print(header) # Print header leading each line.
# Figure out which characters to print in each cell.
chars = []
for x, c in enumerate(row):
chars.append(str(character_positions.get((x, y), c)))
print("| {} |".format(" | ".join(chars)))
print(header) # Print final header (well, footer).

hero_position = (1, 1) # 0, 0 would be boring.
evil_position = (5, 6)
hero_character = '@'
evil_character = '%'

draw_map(world_map, character_positions={
hero_position: hero_character,
evil_position: evil_character,
})

The result now is

+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | @ | | T | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | T | | |
+---+---+---+---+---+---+---+---+
| | T | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | T | % | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | K |
+---+---+---+---+---+---+---+---+

As you can see, the @ and % appeared there!

And now, the interactivity – for the simple case here, let's just use input() in a loop to ask the user what to do and modify hero_position accordingly.

while True:
draw_map(world_map, character_positions={
hero_position: hero_character,
evil_position: evil_character,
})
command = input("WASDQ?").lower()
if command == "w" and hero_position[1] > 0:
hero_position = (hero_position[0], hero_position[1] - 1)
if command == "a" and hero_position[0] > 0:
hero_position = (hero_position[0] - 1, hero_position[1])
if command == "s" and hero_position[1] < len(world_map) - 1:
hero_position = (hero_position[0], hero_position[1] + 1)
if command == "d" and hero_position[0] < len(world_map[0]) - 1:
hero_position = (hero_position[0] + 1, hero_position[1])
if command == "q":
break
if hero_position == evil_position:
print("You were eaten!")
break

python move characters based on string position

[Update]

Thank you for all the great responses. I found a solution to my own question after messing with it for a while. I hope this helps someone else! :-)

x= "th i s. i s. a. n i^ c e. s s t. s t r i ng."
for i in range(len(x)):
if x[i] == '^':
j = i + 1
if x[j] == ' ':
j = j + 1
while j < len(x) and x[j] != ' ':
j = j + 1
print x
x= x[0:i] + x[i+1:]
x= x[0:j-1] + "^" + x[j-1:]
print x
exit()

result:
th i s. i s. a. n i c^ e. s s t. s t r i ng.

Move an element in a list

You mean, like, changing C and the dot position? You could have something like:

list_ = [A, B, C, ., D]
list_[2], list_[3] = list_[3], list_[2]

The list_ would look like [A, B, ., C, D].

Move elements in a list one position backward without mutating the original list

Easy task then, return a copy with the elements shifted:

def cycle(input_list):
return input_list[1:] + input_list[:1]

Best way to move all items in a list by one position in C#

List<Measurement> measurements;

void AddMeasurement(Measurement measurement)
{
if (measurements.Count == 8)
{
measurements.RemoveAt(0); // Indices of all remaining elements will reduce by 1
}
mesurements.Add(measurement);
}

Python move all elements of a list one position back with same len

Just use list slicing:

def list_move_back(new_value, list_of_values):
return [new_value] + list_of_values[:-1]

Explanation: list_of_values[:-1] returns all the elements except for the last. By appending it to the new value, you get the wanted result. This answer has a pretty cool explanation of how list slicing works.

Also, if for some reason you'd like the "verbose" way to do this (maybe for an exercise or whatever), here's a way to go about it:

def list_move_back(new_value, list_of_values):

for i in range(len(list_of_values)-1, 0, -1):
list_of_values[i] = list_of_values[i-1]
list_of_values[0] = new_value

return list_of_values

I'd recommend list slicing over this method 9/10 times but again, I'm just leaving this here because there might be a case where someone wants to do this as some sort of mental exercise for indexing.



Related Topics



Leave a reply



Submit