1

I'm making a 2D game on replit and so far, I'm doing pretty well. My last question is about making the map.

Here's the code for the map:

import pygame, sys

BLUE = (0, 0, 255)
SAND = (194, 176, 128)
GRASS = (124, 252, 0)
FOREST = (0, 100, 0)

TileColor = {'W': BLUE, 'S': SAND, 'G': GRASS, 'F': FOREST}

map1 = ["WWWWWWWWWWWWWWWWWWWWWWW",
        "WWWWWWWWWGGGWWWWWWWWWWW",
        "WWWWWGGGGGGGGGGGWWWWWWW", 
        "WWWWGGGGGFFFGGGGGGWWWWW",
        "WWWGGGGGFFFFFFGGGGGWWWW", 
        "WWWGGGGGGFFFFFGGGGGGWWW",
        "WWGGGGGGGGGFFGGGGGGGWWW", 
        "WWGGGGGGGGGGGGGGGGGGGWW",
        "WWGGGGGGSSSSSSSGGGGGGGW", 
        "WWGGGGSSSSSSSSSSGGGGGGW",
        "WGGGGGGGSSGGGGGGGGGGGSW", 
        "WGGGGGGGGGGGGGGGGGGGSSW",
        "WSGGGGGGGGFFGGGGGGGGSSW", 
        "WSSGGGGGGFFFGGGGGFFGGSW",
        "WSSGGGGGFFFFFFGGFFFFFGW", 
        "WSGGGGFFFFFFFFFFFFFFGGW",
        "WWGGGGGFFFFFFFFFFFFGGWW", 
        "WWGGGGGGGFFFFFFFFGGGWWW",
        "WWWWGGGGGGGGFFGGGGGWWWW", 
        "WWWWWWSSSSSGGGGSSSWWWWW",
        "WWWWWWWWWSSSSSSSSWWWWWW", 
        "WWWWWWWWWWWWWWSWWWWWWWW",
        "WWWWWWWWWWWWWWWWWWWWWWW"
        ]

TILESIZE = 22
MAPWIDTH = 23
MAPHEIGHT = 23

pygame.init()
DISPLAY = pygame.display.set_mode((MAPWIDTH * TILESIZE, MAPHEIGHT * TILESIZE))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    for row in range(MAPHEIGHT):
        for col in range(MAPWIDTH):
            pygame.draw.rect(
                DISPLAY, TileColor[map1[row][col]],
                (col * TILESIZE, row * TILESIZE, TILESIZE, TILESIZE))

    pygame.display.update()

Which got me this:

My Map

Now I want to make a little person moving around when I press the arrow keys, and then I want to make it not be able to move onto to blue (water). Any suggestions on how I could do that?

roarg
  • 27
  • 5

3 Answers3

2

The character is represented by a row an column in the grid:

character = [5, 11]

Use the keyboard events to change the position of the character (see How to get keyboard input in pygame?). Skip character movement if new character position is not on grass (map1[c_row][c_col] == 'G'):

run = True
while run:
    c_col, c_row = character
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                c_col += 1  
            if event.key == pygame.K_LEFT:
                c_col -= 1
            if event.key == pygame.K_UP:
                c_row -= 1  
            if event.key == pygame.K_DOWN:
                c_row += 1   

    if 0 <= c_col < MAPWIDTH and 0 <= c_row < MAPHEIGHT:
        if map1[c_row][c_col] == 'G':
            character = [c_col, c_row]

Draw a rectangle at the character's position:

run = True
while run:
    # [...]

    pygame.draw.rect(
        DISPLAY, (255, 0, 0),
        (character[0] * TILESIZE, character[1] * TILESIZE, TILESIZE, TILESIZE))

Complete example:

import pygame, sys

BLUE = (0, 0, 255)
SAND = (194, 176, 128)
GRASS = (124, 252, 0)
FOREST = (0, 100, 0)

TileColor = {'W': BLUE, 'S': SAND, 'G': GRASS, 'F': FOREST}

map1 = ["WWWWWWWWWWWWWWWWWWWWWWW",
        "WWWWWWWWWGGGWWWWWWWWWWW",
        "WWWWWGGGGGGGGGGGWWWWWWW", 
        "WWWWGGGGGFFFGGGGGGWWWWW",
        "WWWGGGGGFFFFFFGGGGGWWWW", 
        "WWWGGGGGGFFFFFGGGGGGWWW",
        "WWGGGGGGGGGFFGGGGGGGWWW", 
        "WWGGGGGGGGGGGGGGGGGGGWW",
        "WWGGGGGGSSSSSSSGGGGGGGW", 
        "WWGGGGSSSSSSSSSSGGGGGGW",
        "WGGGGGGGSSGGGGGGGGGGGSW", 
        "WGGGGGGGGGGGGGGGGGGGSSW",
        "WSGGGGGGGGFFGGGGGGGGSSW", 
        "WSSGGGGGGFFFGGGGGFFGGSW",
        "WSSGGGGGFFFFFFGGFFFFFGW", 
        "WSGGGGFFFFFFFFFFFFFFGGW",
        "WWGGGGGFFFFFFFFFFFFGGWW", 
        "WWGGGGGGGFFFFFFFFGGGWWW",
        "WWWWGGGGGGGGFFGGGGGWWWW", 
        "WWWWWWSSSSSGGGGSSSWWWWW",
        "WWWWWWWWWSSSSSSSSWWWWWW", 
        "WWWWWWWWWWWWWWSWWWWWWWW",
        "WWWWWWWWWWWWWWWWWWWWWWW"
        ]

TILESIZE = 22
MAPWIDTH = 23
MAPHEIGHT = 23

pygame.init()
DISPLAY = pygame.display.set_mode((MAPWIDTH * TILESIZE, MAPHEIGHT * TILESIZE))
clock = pygame.time.Clock()

character = [5, 11]

run = True
while run:
    c_col, c_row = character
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                c_col += 1  
            if event.key == pygame.K_LEFT:
                c_col -= 1
            if event.key == pygame.K_UP:
                c_row -= 1  
            if event.key == pygame.K_DOWN:
                c_row += 1   

    if 0 <= c_col < MAPWIDTH and 0 <= c_row < MAPHEIGHT:
        if map1[c_row][c_col] == 'G':
            character = [c_col, c_row]            


    for row in range(MAPHEIGHT):
        for col in range(MAPWIDTH):
            pygame.draw.rect(
                DISPLAY, TileColor[map1[row][col]],
                (col * TILESIZE, row * TILESIZE, TILESIZE, TILESIZE))

    pygame.draw.rect(
        DISPLAY, (255, 0, 0),
        (character[0] * TILESIZE, character[1] * TILESIZE, TILESIZE, TILESIZE))

    pygame.display.update()
    clock.tick(100)

pygame.quit()
sys.exit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
1

Here is some nice starter code for PyGame

import pygame as pg, sys
mainClock = pg.time.Clock()
pg.init()
WINDOWWIDTH = 600
WINDOWHEIGHT = 400
screen = pg.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))


class Player:
    def __init__(self):
        self.rect = pg.Rect(200, 0, 10, 10)
        self.velocity = pg.Vector2(0, 0)
        print(self.rect)

    def draw(self, screen):
        pg.draw.rect(screen, (255, 0, 0), self.rect)


player = Player()
while True:

    # Input
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_LEFT:
                player.velocity.x = -5
            if event.key == pg.K_RIGHT:
                player.velocity.x = 5
            if event.key == pg.K_UP:
                player.velocity.y = -5
            if event.key == pg.K_DOWN:
                player.velocity.y = 5
        elif event.type == pg.KEYUP:
            if event.key == pg.K_LEFT:
                player.velocity.x = 0
            if event.key == pg.K_RIGHT:
                player.velocity.x = 0
            if event.key == pg.K_UP:
                player.velocity.y = 0
            if event.key == pg.K_DOWN:
                player.velocity.y = 0

    # Update
    player.rect.left += player.velocity.x
    player.rect.top += player.velocity.y

    # Draw
    screen.fill((0, 0, 0))
    player.draw(screen)

    pg.display.update()
    mainClock.tick(40)

Last I'd like to mention two things: I learned so much from this series by DaFluffyPotato. If you are coding a game for python, while PyGame has the largest community alternatives like rubato and pyglet are objectively much better.

Just to show, the same code above is achievable in way fewer lines in rubato:

import rubato as rb

rb.init()

main_scene = rb.Scene()

player = rb.GameObject(name="player", pos=rb.Display.center)
player.add(rb.Rectangle(color=rb.Color.red, width=100, height=100))
main_scene.add(player)

speed = 100


def main_update():
    if rb.Input.key_pressed("left"):
        player.pos.x -= speed * rb.Time.delta_time
    if rb.Input.key_pressed("right"):
        player.pos.x += speed * rb.Time.delta_time
    if rb.Input.key_pressed("up"):
        player.pos.y -= speed * rb.Time.delta_time
    if rb.Input.key_pressed("down"):
        player.pos.y += speed * rb.Time.delta_time


main_scene.update = main_update
rb.begin()

0

The first thing you have to do is create a new python file and name it player.py, the next thing you should do is import player.py to the main file.

Now make sure you have imported Pygame to the player.py file

import pygame

Now lets create a class called "Player"(make SURE it has a CAPITAL "P") and inside of this class create the function init

def __init__(self,ai_game):
        self.screen=ai_game.screen

        #this is the position of the player
        self.posX=0
        self.posY=0

The next thing you have to do is create a function that draws the player on the screen(after all what's the fun of a game without the player)

def blitme(self):
        self.screen.blit(self.image,self.rect)
        # change the color to anything you want
        color = (255,0,0)

        #⚠️WARNING⚠️ self.posX and self.posY are JUST to make the player SEEM like it's moving but later if you want to add collisions then make SURE you create a RECT variable
 
        self.draw.rect(self.screen, color, pygame.Rect(30, 30, self.posX, self.posY))

The next thing to do is go back to your main python file and create a new function named check

now make sure in your main file to write this line of code:

player=Player()

now go back to your for event in pygame...... and write all of this:

                       if event.type==pygame.KEYDOWN:
                              if event.key==pygame.K_RIGHT:
                                    player.posX+=1
                              elif event.key==pygame.K_LEFT:
                                    player.posX-=1
                              elif event.key==pygame.K_UP:
                                    player.posY-=1
                              elif event.key==pygame.K_DOWN:
                                    player.posY+=1

if you recieve any errors please give me the repl link and I will try to fix it!