I am an amateur programmer and very new at Pygame. This is my program written in Pygame, something akin to Minecraft. For the past hour, I've been trying to set up a code that would make my player move to a random tile on pressing X key. I've exhausted most if not all web sites and search engines looking. I have manages to accomplish half of my task; when X key is pressed, the avatar moves to a random tile but it moves out of the window/display. Please, could you take a look at my code and see what I can do to improve it?
import pygame, sys, random
from pygame.locals import *
LTBLUE = (125, 221, 255)
GREEN = (42, 106, 24)
YELLOW = (247, 243, 59)
GREY = (150, 150, 150)
WHITE = (255, 255, 255)
PINK = (251, 175, 224)
WATER = 0
SEAWEED = 1
SAND = 2
ROCKS = 3
PEARL = 4
CORAL = 5
PLAYER = pygame.image.load("mermaid.gif")
playerPos=[0,0]
#colors = {SAND: YELLOW, SEAWEED: GREEN, WATER: LTBLUE, PEARL: WHITE, ROCKS: GREY, CORAL: PINK}
textures = { WATER: pygame.image.load("water.png"),
SEAWEED: pygame.image.load("seaweed.png"),
SAND: pygame.image.load("sand.png"),
ROCKS: pygame.image.load("rocks.png"),
PEARL: pygame.image.load("pearl.png"),
CORAL: pygame.image.load("coral3.png")
TILESIZE = 40
MAPWIDTH = 15
MAPHEIGHT = 15
resources = [SAND, WATER, SEAWEED, PEARL, ROCKS, CORAL]
tilemap=[]
for h in range(MAPHEIGHT):
myrow=[]
for w in range(MAPWIDTH):
if(h==0 or h==14 or w==0 or w==14):
myrow.append(CORAL);
else:
randomindex = random.randint(0,5)
myrow.append(randomindex);
tilemap.append(myrow)
print(tilemap)
pygame.init()
DISPLAYSURF = pygame.display.set_mode((MAPWIDTH*TILESIZE, MAPHEIGHT*TILESIZE))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
#rmove = random.randint(0,15)
if event.key == K_RIGHT:
playerPos[0]+=1
elif event.key == K_LEFT:
playerPos[0]-=1
elif event.key == K_UP:
playerPos[1]-=1
elif event.key == K_DOWN:
playerPos[1]+=1
elif event.key == K_x:
if(movex<14 and movey<14):
playerPos[0]-=movex
playerPos[0]+=movex
playerPos[1]-=movey
playerPos[1]+=movey
for row in range(MAPHEIGHT):
for column in range(MAPWIDTH):
DISPLAYSURF.blit(textures[tilemap[row][column]],(column*TILESIZE, row*TILESIZE))
DISPLAYSURF.blit(PLAYER, (playerPos[0]*TILESIZE, playerPos[1]*TILESIZE))`
pygame.display.update()
ifto check new position before you move player. - furas