I am making an asteroid remake of sorts, on of the big things in asteroids is the fact that the bullets rotate to match the objects direction. I have managed to make the bullets come out of the ship, nut it stays the same upright rotation. I would Like to make the bullet match rotation with the ship, so it looks like the bullets are coming out of the ship. My code is long unfortunately, but I do not know what to take out to make it more compact. I just tried to add comments and hope I guess. Any help is greatly appreciated. The vast majority of the actions happens in the 'MOUSEBUTTONDOWN" code. I have a 'rotate" function for the ship already, I'm thinking maybe we have to just use that, but I am unable to implement it.
The Image for The Ship
Image for the bullet I Want to rotate
import pygame as game
import pygame.math as math
import random as r
'''
Here I defined things
'''
game.init()
game.display.set_caption("Asteroids")
screen = game.display.set_mode([800,600])
gameon=True
bgcolor = game.color.Color("#FFFFFF")
ship = game.image.load("ship.png")
ship = game.transform.scale(ship, (50, 50))
rect = ship.get_rect()
rect.x=400
rect.y=400
shipdir = 0
newship = ship
auto = False
arrow = game.image.load("bullet.png")
shiphitbox = ship.get_rect()
shiphitbox.x = 100
shiphitbox.y = 100
arrows=[]
#code to rotate the ship
def rotateship(shipdir):
newship = game.transform.rotate(ship, shipdir)
newrect = rect.copy()
newrect.center = newship.get_rect().center
return newship.subsurface(newrect).copy()
def getmove():
#returns x-y movement based on directrion facing
global shipdir
d=shipdir
if d >= 349 or d < 11:
return [0, -2]
elif d >=11 and d < 34:
return [-1,-2]
elif d >=34 and d < 56:
return [-2,-2] #
elif d >=56 and d < 79:
return [-2,-1]
elif d >=79 and d < 102:
return [-2,0]
elif d >=102 and d < 125:
return [-2,1]
elif d >=125 and d < 147:
return [-2,2] #
elif d >=147 and d < 170:
return [-1,2]
elif d >=170 and d < 191:
return [0,2]
elif d >=191 and d < 214:
return [1,2]
elif d >=214 and d < 237:
return [2,2] #
elif d >=237 and d < 260:
return [2,1]
elif d >=260 and d < 282:
return [2,0]
elif d >=282 and d < 305:
return [2,-1]
elif d >=305 and d < 328:
return [2,-2] #
elif d >=328 and d < 349:
return [1,-2]
##main loop of the game
while gameon:
screen.fill(bgcolor)
screen.blit(newship,(rect.x,rect.y))
key = game.key.get_pressed()
event=game.event.poll()
#controls
if key[game.K_a]:
if shipdir==0: shipdir=360
shipdir -= 1
newship = rotateship(shipdir)
if key[game.K_d]:
if shipdir==360: shipdir=0
shipdir += 1
newship = rotateship(shipdir)
if auto==True or key[game.K_SPACE] or key[game.K_w] :
move = getmove()
rect.x += move[0]
rect.y += move[1]
game.time.delay(5)
#shooting
if event.type==game.MOUSEBUTTONDOWN:
'''
This is where the shooting happens
'''
arrowbox = arrow.get_rect()
arrowbox.x = rect.x;
arrowbox.y = rect.y;
move = getmove()
data = [arrowbox, move[0], move[1]]
arrows.append(data)
if event.type==game.QUIT:
gameon=False;
#spawning projectiles
for bullet in arrows:
bullet[0].x += bullet[1]
bullet[0].y += bullet[2]
if bullet[0].x > 700 or bullet[0].x<0:
arrows.remove(bullet)
for bullet in arrows:
screen.blit(arrow,(bullet[0].x,bullet[0].y))
game.display.flip() #redraws / refreshes screen
##comes here when game is over
while True:
screen.fill(bgcolor)
game.display.flip()
event=game.event.poll()
if event.type == game.QUIT:
break
game.quit()
I would Like to make the bullet match rotation with the ship, so it looks like the bullets are coming out of the ship.
You have to know the angle of rotation for each separate bullet. Add the angle of rotation to the bullet data:
data = (arrowbox, move[0], move[1], shipdir)
arrows.append(data)
Create rotated bullets by pygame.transform.rotate and blit it:
for bullet in arrows:
rotBullet = pygame.transform.rotate(arrow, bullet[3])
screen.blit(rotBullet, (bullet[0].x, bullet[0].y))
Related
I'm trying to create a collision detection between 4 controllable characters on an RPG battle map. Here is the function I'm using
def player_collission(Lord_x,Lord_y,Journeyman_x,Journeyman_y,Archer_x,Archer_y,
Cleric_x,Cleric_y):
print("Running")
if abs(Lord_x - Journeyman_x) <= 0 and abs(Lord_y - Journeyman_y) <= 0:
print("Colission detected")
return True
elif abs(Lord_x - Archer_x) <= 0 and abs(Lord_y - Archer_y) <= 0:
print("Colission detected")
return True
elif abs(Lord_x - Cleric_x) <= 0 and abs(Lord_y == Cleric_y) <= 0:
print("Colission detected")
return True
elif abs(Journeyman_x - Archer_x) <= 0 and abs(Journeyman_y - Archer_y) <= 0:
print("Colission detected")
return True
elif abs(Journeyman_x - Cleric_x) <= 0 and abs(Journeyman_y - Cleric_y) <= 0:
print("Colission detected")
return True
elif abs(Archer_x - Cleric_x) <= 0 and abs(Archer_y == Cleric_y) <= 0:
print("Colission detected")
return True
else:
return False #I didnt use classes so it has alot of if statements
if player_up:
p_collide = player_collission(Lord_x,Lord_y,Journeyman_x,Journeyman_y,Archer_x,Archer_y,
Cleric_x,Cleric_y)
if current_player == "lord":
if p_collide != True:
Lord_y -= tile_increment
if Lord_y <= 0:
Lord_y = 50
What happens is that the characters still move into each other but it detects the collision after it has already moved into each other and freezes all movement. I'm not sure how to re arrange it to make it work properly.
You detect collision when it has already happened. This is why you see characters overlapping.
Instead, you should detect if a collision is going to happen, an prevent a motion that would lead to that.
An example:
def move(coords, velocity):
"""Moves coords according to velocity."""
x, y = coords # Unpack a 2-tuple.
vx, vy = velocity
return (x + vx, y + vy)
tom_coords = (0, 0) # Tom is in the corner.
tom_v = (1, 1) # Tom moves by diagonal.
jerry_coords = (5, 0) # Jerry is a bit away from Tom.
jerry_v = (0, 1) # Jerry moves vertically.
while True:
new_tom_coords = move(tom_coords, tom_v) # Tom moves without fear.
new_jerry_coords = move(jerry_coords, jerry_v)
if new_jerry_coords == new_tom_coords: # Would be a collision!
new_jerry_coords = jerry_coords # Back to previous tile.
vx, vy = jerry_v
jerry_v = (-vx, -vy) # Jerry runs back.
print("Collision imminent, Jerry runs away!")
else:
jerry_coords = new_jerry_coords # Only update if no collision.
# Could also check collisions with walls, etc.
tom_coords = new_tom_coords
# Not inside pygame, so just print it and wait for a key press.
print('Tom:', tom_coords, 'Jerry:', jerry_coords)
input("Enter to continue, Ctrl+C to stop ")
Run it in and see how Tom and Jerry come close to each other but never occupy the same tile.
Good Day. I'm a beginner in coding, and basically I made a simple maze game using python.
it's 3x3 so I made 9 dictionary variables that detailed the possible movement for each tile (North, south, east, west.)
my code consists of nested if-elif as well as a main while loop.
if level == 1: #level of difficulty.
i = 0
maplist1 = {'directions1':'south'}
maplist2 = {'directions1':'south','directions2':'east'}
maplist3 = {'directions1':'west'}
maplist4 = {'directions1':'north','directions2':'east','directions3':'south'}
....
....
current_position = 1 #local variable within the first if statement
Here's a snippet of the code block that would be repeated, with little to no variations (literally repeating) to it.
while i == 0: #to continuously loop the program
if current_position == 1:
directions = maplist1['directions1']
direction = input(f"What direction do you want to go: {directions} ").title() #choose the possible directions to go to.
if direction == "S" or direction == "South":
current_position = 4
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
if current_position == 2:
directions = maplist2['directions1']
directions2 = maplist2['directions2']
direction = input(f"What direction do you want to go: {directions} {directions2} ").title()
if direction == "S" or direction == "South":
current_position = 5
print(f"You are in cell {current_position}.")
elif direction == "E" or direction == "East":
current_position = 3
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
if current_position == 3:
directions = maplist3['directions1']
direction = input(f"What direction do you want to go: {directions} ").title()
if direction == "W" or direction == "West":
current_position = 2
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
if current_position == 4:
directions = maplist4['directions1']
directions2 = maplist4['directions2']
directions3 = maplist4['directions3']
direction = input(f"What direction do you want to go: {directions} {directions2} {directions3} ").title()
if direction == "N" or direction == "North":
current_position = 1
print(f"You are in cell {current_position}.")
elif direction == "S" or direction == "South":
current_position = 7
print(f"You are in cell {current_position}.")
elif direction == "E" or direction == "East":
current_position = 5
print(f"You are in cell {current_position}.")
else:
print("Cannot go in that direction.")
.......
......
.......
if current_position == 9:
print("Congratulations, you finished the game.")
i += 1 #to stop the loop
my question is how to make this simpler, and more compact?
Current location must be remembered every movement
I know how to use def but quite unsure on how to implement it in my maze game.
There are 3 levels to this game, basically 3x3, 4x4, and 5x5. that's the reason why I am asking for any ideas on how to shorten/compact the code.
I don't need you to give me your code, but some guidance would be great on how to proceed because i am feeling lost right now.
Try creating a maze data structure. One typical idea is to create a 2D array of cells, each with a north/west/south/east wall.
Let's create a class, just for better understanding. I want you to ignore everything except the can_move() method.
class Cell:
def __init__(self, walls):
self.walls = walls
def __str__(self):
"""Allows us to call print() on a Cell!"""
return '\n'.join(self.draw())
def _draw_wall(self, wall, s):
return s if wall in self.walls else ' ' * len(s)
def draw(self, inner=' '):
"""Draw top, mid, and bottom parts of the cell."""
n = self._draw_wall('N', '___')
w = self._draw_wall('W', '|')
e = self._draw_wall('E', '|')
s = self._draw_wall('S', '___')
top = ' ' + n + ' '
mid = w + inner + e
bot = w + s + e
return top, mid, bot
def can_move(self, direction):
return direction not in self.walls
Let's make some cells and see what they look like:
>>> Cell('NWSE')
___
| |
|___|
>>> Cell('NWS')
___
|
|___
Now, a maze is made out of a 2D list of cells. Here's a small maze:
maze = Maze(width=3, height=3, rows=[
[Cell('NWE'), Cell('NW'), Cell('NE')],
[Cell('WE'), Cell('WE'), Cell('WE')],
[Cell('WS'), Cell('SE'), Cell('WSE')]
])
Which looks like this:
>>> maze
___ ___ ___
| x || |
| || |
| || || |
| || || |
| || |
|___ ___||___|
But wait! We haven't defined what Maze is. Once again, ignore all the drawing related stuff and focus on move_direction().
class Maze:
def __init__(self, width, height, rows):
self.width = width
self.height = height
self.rows = rows
self.position = (0, 0)
def __str__(self):
return '\n'.join(self.draw_row(i) for i, _ in enumerate(self.rows))
def _inner(self, i, j):
return ' x ' if (i, j) == self.position else ' '
def draw_row(self, i):
triples = [
cell.draw(self._inner(i, j)) for j, cell in enumerate(self.rows[i])
]
return '\n'.join([
''.join(t for t, _, _ in triples),
''.join(m for _, m, _ in triples),
''.join(b for _, _, b in triples)])
def cell_at_position(self, i, j):
return self.rows[i][j]
def move_direction(self, direction):
curr_cell = self.cell_at_position(*self.position)
if not curr_cell.can_move(direction):
print("Can't go in that direction!")
return
deltas = {'N': (-1, 0), 'W': (0, -1), 'S': (1, 0), 'E': (0, 1)}
y, x = self.position
dy, dx = deltas[direction]
self.position = y + dy, x + dx
To use this, just create a simple small loop:
while True:
print(maze)
direction = input('What direction? ')
maze.move_direction(direction)
And watch the magic happen!
You can try it here.
Instead of thinking the maze in 1D i.e the current_position(1,2,3..,9), you should think and code it like a 2D matrix space((0,0),(0,1)).
And Instead of hard coding the base maze to 3, we should be thinking in terms of n x n maze, as now that you have implemented the logic for a 3 x 3, now you should be able to expand it to n x n.
And you handled the possible directions using your maps instead, we should write the logic for boundary conditions, like a method to check the directions possible on each step,
def possible_path(current_x, current_y, matrix_size=3):
# this returns like directions possible like current_x + 1 < matrix_size
# then the east direction is possible.
pass
Direction handling should be handled somewhat like this,
def position_handler(row, col, direction):
# can write the logic for mapping the direction to the movement in X and Y,
# if direction == 'NORTH'
# or can get the config from a map like,
# move = movement.get(direction)
# say NORTH config is =>movement= {'NORTH': {'x': 0, 'y':1}}
# and now move accordingly i.e
# row += move.get('x')
# col += move.get('y')
pass
Exploit rules instead of hardcoding anything.
If you have a 3x3 maze, your (x,y) indexes are somthing like
0,0 1,0 2,0
0,1 1,1 2,1
0,2 1,2 2,2
You can store this as list of lists:
field = [ ["one","two","three"],["four","five","six"],["seven","eight","nine"] ]
pos = (0,0)
p = field[pos[0]][pos[1]] # would be "one"
# rules for movement based on actual position:
move_right = pos[0] < (3-1)
move_left = pos[0] > 0
move_up = pos[1] > 0
move_down = pos[1] < (3-1)
You can use functions to code this:
# p is a coordinate (0,0) etc tuple of x and y
# as functions
def can_move_right(p, dim=3):
return p[0] < dim-1
def can_move_left(p,dim=3):
return p[0] > 0
def can_move_up(p, dim=3):
return p[1] > 0
def can_move_down(p,dim=3):
return p[1] < dim-1
def move_up(p):
if can_move_up(p):
return (p[0],p[1]-1)
# implicitly returns None if not possible
def move_down(p):
if can_move_down(p):
return (p[0],p[1]+1)
# etc
new_pos = move_up( (1,1) ) # => (1,0)
new_pos = move_down( (1,1) ) # => (1,2)
new_pos = move_up( (0,0) ) # None - need to handle it
if not new_pos:
print("Wrong move")
To adjust for n x n you just need to give other dim - the rules are the same.
So I am trying to create a series of "boids" at random locations, which fly at random speeds, but I am having some trouble moving the rects which are in a list, although I can draw them. I am using a provided vector module, the entire code and the module can be found here. The png I am using for the sprites.
Update: I got a rect moving, by using the instance position vector instead of the class vector. But now only one boid is drawn. I suspect that more boids are drawn at the same exact position.
class Boid():
def __init__(self, screen):
self.bird = pygame.image.load("birdie.png")
self._pos = Vector2D(random.randint(0, screen.get_width()),
random.randint(0, screen.get_height()))
self._vel = Vector2D((random.randint(1, 10) / 5.0),
(random.randint(1, 10) / 5.0))
self.speed = random.randint(1, 5)
self.bird_rect = self.bird.get_rect(center=(self._pos.x, self._pos.y))
self._boids = []
def add_boid(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self._boids.append(Boid(screen))
def move_boids(self):
s = Screen()
#self.bird_rect.move_ip(self._vel.x, self._vel.y)
self._pos += (self._vel * self.speed)
#bounds check
if self._pos.x + self.bird_rect.width >= s.width:
self._pos.x = s.width - self.bird_rect.width
self._vel.x *= -1
elif self._pos.x <= 0:
self._pos.x = 0
self._vel.x *= -1
if self._pos.y - self.bird_rect.height <= 0:
self._pos.y = self.bird_rect.height
self._vel.y *= -1
elif self._pos.y >= s.height:
self._pos.y = s.height - self.bird_rect.height
self._vel.y *= -1
def draw_boids(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
print(len(self._boids))
for boid in self._boids:
self.boidRect = pygame.Rect(self.bird_rect)
#edit: changed boid._pos.x and y to self._pos.x and y
self.boidRect.x = self._pos.x
self.boidRect.y = self._pos.y
screen.blit(self.bird, self.boidRect)
You have to iterate over all boids in the self._boids list and update their _pos and bird_rect attributes to move them.
def move_boids(self):
s = Screen()
for boid in self._boids:
boid._pos += boid._vel * boid.speed
boid.bird_rect.center = boid._pos
# Bounds check.
if boid._pos.x + boid.bird_rect.width >= s.width:
boid._pos.x = s.width - boid.bird_rect.width
boid._vel.x *= -1
elif boid._pos.x <= 0:
boid._pos.x = 0
boid._vel.x *= -1
if boid._pos.y - boid.bird_rect.height <= 0:
boid._pos.y = boid.bird_rect.height
boid._vel.y *= -1
elif boid._pos.y >= s.height:
boid._pos.y = s.height - boid.bird_rect.height
boid._vel.y *= -1
You can also simplify the draw method a bit.
def draw_boids(self):
# Blit all boids at their rects.
for boid in self._boids:
screen.blit(boid.bird, boid.bird_rect)
Hi I am trying to get the following github repo : https://github.com/lukekulik/solar-system
to work on my laptop and have installed all the modules required but for some reason when i try and run i get error cannot import module vis in from vis import ....
It is in every file and i a using python 3.6.
The code for one file is below:
from vis import scene, label, vector, norm, cross
Error is here when trying to import vis and below when trying to import wx
#from pygame.mixer import music
from parameters import planets, n, am
from wx import Exit
lbl = label(text=" Simulation is paused. \n Press any key to continue.",
visible=False, box=False)
# key_check function translates user keyboard into commands for the program:
def key_check(ship_mode, s, v, a, dt, sw_lbl, lbl_off, predraw, earthpos, t,
ship):
if scene.kb.keys: # check if there are any keys pressed in the queue
key = scene.kb.getkey() # retrieve the pressed key
# change simulation speed: (steps are small on purpose; user has to
press and hold for smooth transition)
if key == 'q' and 1 <= dt < 125:
dt += 2
elif key == 'q' and dt <= 0.95:
dt += 0.05
elif key == 'a' and dt > 1:
dt -= 2
elif key == 'a' and 0.2 < dt <= 1:
dt -= 0.05
elif key == 'esc':
Exit() # exit the program
elif key == 'p':
lbl.visible = True # show pause label
lbl.pos = scene.center # center the label on the screen
scene.kb.getkey() # wait for key input
lbl.visible = False # hide pause label
elif key == 'x':
if scene.stereo == 'nostereo':
scene.stereo = 'redcyan' # turn on 3D rendering mode (red-cyan)
elif scene.stereo == 'redcyan':
scene.stereo = 'crosseyed' # turn on 3D rendering mode (cross-eyed)
else:
scene.stereo = 'nostereo' # turn off 3D rendering mode
elif key == 'l':
sw_lbl = not sw_lbl # planet/spaceship label switch
lbl_off = not lbl_off
elif key == 's':
#if ship_mode:
# music.fadeout(2500) # fade out music when quitting spaceship mode
# else:
# music.play(-1) # turn on music when entering spaceship mode
ship_mode = not ship_mode # spaceship mode switch
a = vector(0, 0, 0) # reset acceleration
sw_lbl = True # turn on spaceship label
# spaceship thrusters control:
elif key == 'up':
#a += vector(0, 0, am) # old cartesian steering
a += am*norm(v) # accelerate into the direction of motion
elif key == 'down':
a -= am*norm(v) # accelerate against the direction of motion
elif key == 'left':
a -= am*cross(norm(v),cross(norm(v),norm(s))) # accelerate to the left of the velocity
elif key == 'right':
a += am*cross(norm(v),cross(norm(v),norm(s))) # accelerate to the right of the velocity
elif key == 'd':
a += am*cross(norm(v),norm(s)) # accelerate to the 'top' of the velocity
elif key == 'c':
a -= am*cross(norm(v),norm(s)) # accelerate to the 'bottom' of the velocity
elif key == '0':
a = vector(0, 0, 0) # reset acceleration
# pre-programmed spaceship positions/scenarios:
elif key == '1': # Earth-Sun Lagrange point 3 (L3 - 'counter-Earth')
s = -earthpos
v0 = (planets[2][1][:, (int(-t + 1)) % n] - planets[2][1][:, (int(-t)) % n]) / (365.25 * 86400 / n)
v = vector(v0[0], v0[1], v0[2])
a = vector(0, 0, 0)
predraw = False
ship.trail.append(pos=s, retain=1)
elif key == '2': # polar orbit around the Sun
s = vector(3e+07, -2e+06, 2e+08)
v = vector(0, 24, 0)
a = vector(0, 0, 0)
predraw = False
ship.trail.append(pos=s, retain=1)
elif key == '3': # orbit of the probe Helios 2 (fastest man-made object to date - 0.02% speed of light)
s = vector(43e6, 0, 0) # perihelion
v = vector(0, 0, 70.22)
a = vector(0, 0, 0)
predraw = False
ship.trail.append(pos=s, retain=1)
elif key == '4': # Halley's comet (derived using specific orbital energy, 162.3 deg inclination)
s = vector(87813952, 0, 0) # perihelion
v = vector(0, 16.7, 52)
a = vector(0, 0, 0)
predraw = False
ship.trail.append(pos=s, retain=1)
return ship_mode, s, v, a, dt, sw_lbl, lbl_off, predraw, ship
def mouse_check(obj, sw_lbl, lbl_off, ship_mode):
if scene.mouse.clicked and not ship_mode: # check if there are any
clicks
in the queue
scene.mouse.getclick() # retrieve the click
obj_old = obj
obj = scene.mouse.pick # clicked object becomes main object
try:
r = obj.radius
except AttributeError:
obj = obj_old # if the clicked object is not a sphere (e.g. Saturn's rings), go back to old_obj
else:
if r > 30000000000: # if the clicked object is a very large sphere (celestial), go back to old_obj
obj = obj_old
if obj != obj_old and not lbl_off: # if different planet was clicked, switch planet label ON
sw_lbl = True
scene.center = obj.pos # center scene on the main object
return obj, sw_lbl`
Thanks in advance.
I would like to see on screen a sign, e.x might be (hash) '#'. Sign will have some starting position, let's say (0, 0). I would like to see sign moving right if I press right arrow, left if I press left arrow, etc.
So far my code looks like this, and it works for reading pos, but I want to add some kind of "animation" so I can see sign is moving on the screen:
!Update: Just to give u a clue, I created "icon" and now when u press right or left, icon moves in desired direction.
from msvcrt import getch
icon = chr(254)
pos = [0, 0]
t = []
def fright():
global pos
pos[0] += 1
print ' ' * pos[0],
print(icon)
def fleft():
global pos
pos[0] -= 1
print ' ' * pos[0],
print(icon)
def fup():
global pos
pos[1] += 1
def fdown():
global pos
pos[1] -= 1
def appendTab():
global pos, t
t.append(pos)
while True:
print'Distance from zero: ', pos
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
print('selected')
appendTab()
elif key == 32: #Space, just a small test - skip this line
print('jump')
print(t)
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
print('down')
fdown()
elif key == 72: #Up arrow
print('up')
fup()
elif key == 75: #Left arrow
print('left')
fleft()
elif key == 77: #Right arrow
print('right')
fright()
You could create a list of lists that serves as the map and set the cell of the player to '#'. Then just print the map and if the player moves, clear the command-line/terminal with os.system('cls' if os.name == 'nt' else 'clear') and print the updated map.
import os
from msvcrt import getch
pos = [0, 0]
# The map is a 2D list filled with '-'.
gamemap = [['-'] * 5 for _ in range(7)]
# Insert the player.
gamemap[pos[1]][pos[0]] = '#'
while True:
print('Distance from zero: ', pos )
key = ord(getch())
if key == 27: #ESC
break
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key in (80, 72, 75, 77):
# Clear previous tile if player moves.
gamemap[pos[1]][pos[0]] = '-'
if key == 80: #Down arrow
pos[1] += 1
elif key == 72: #Up arrow
pos[1] -= 1
elif key == 75: #Left arrow
pos[0] -= 1
elif key == 77: #Right arrow
pos[0] += 1
print('clear')
# Clear the command-line/terminal.
os.system('cls' if os.name == 'nt' else 'clear')
# Set the player to the new pos.
gamemap[pos[1]][pos[0]] = '#'
# Print the map.
for row in gamemap:
for tile in row:
print(tile, end='')
print()