如何制作角色并与碰撞一起移动?

发布于 2025-02-08 04:13:29 字数 1782 浏览 4 评论 0 原文

我正在进行2D款游戏,到目前为止,我做得很好。我的最后一个问题是制作地图。

这是地图的代码:

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()

让我得到了:

​(水)。关于我该怎么做的任何建议?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别闹i 2025-02-15 04:13:30

字符由网格中的一排列表示:

character = [5, 11]

使用键盘事件更改字符的位置(请参见如何在pygame中获取键盘输入?)。跳过字符运动如果新角色位置不在草地上( 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]

在角色的位置绘制矩形:

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

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

完整示例:

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()

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()
墨小墨 2025-02-15 04:13:30

这是

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)

最后一个我想提到的pygame的不错的入门代码:
我从这个系列中学到了很多, rubato pyglet 客观上好得多。

只是为了显示,上面的相同代码在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()

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()

睡美人的小仙女 2025-02-15 04:13:30

您要做的第一件事是创建一个新的python文件,并将其命名 player.py ,您应该做的下一件事就是将player.py import.py import.py import.py。

现在,请确保您已将pygame导入 player.py 文件

import pygame

现在让我们创建一个名为“ player”的类(确保其具有资本“ P”)
在此类中,创建函数 init

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

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

您要做的接下来要做的就是创建一个函数,该函数在屏幕上绘制播放器(毕竟没有玩家的游戏的乐趣)

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))

下一件事要做的是返回到您的主python文件,并创建一个名为Check的新功能

,请确保在主文件中编写此代码行:

player=Player()

现在返回您的pygame中的以获取事件.................................... /strong>并写下所有这些:

                       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

如果您收到任何错误,请给我repl链接,我会尝试修复它!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文