Pygame 迷宫

0 投票
1 回答
1276 浏览
提问于 2025-04-17 21:31

我最近发现了一个用pygame做的小迷宫,心里有个想法:我想把那些难看的矩形换成:

  • 一张背景图片
  • 一个玩家的角色图
  • 一个墙壁的角色图

我已经尝试过几次,但每次都出错(我不能在这里发代码,因为上传时出现了bug,系统提示我没有放4个缩进,但我确实放了……)

有没有人能给我指个方向? 这是原游戏的链接:

http://www.pygame.org/project-Rect+Collision+Response-1061-.html

import pygame
import random
from pygame.locals import *

玩家类 / player Class

class Joueur(object):

def _init_(self):
    self.rect = pygame.image.load("perso.png").convert_alpha()

def mvmt(self, dx, dy):
    #déplacement sur un axe a la fois avec detection de collision / Move each axis separately. Note that this checks for collisions both times.
    if dx !=0:
        self.mvmt_axe(dx, 0)
    if dy !=0:
        self.mvmt_axe(0, dy)

def mvmt_axe(self, dx, dy):

    self.rect.x +=dx
    self.rect.y +=dy
    # Action en cas de collision /  If you collide with a wall, move out based on velocity
    for mur in murs :
        if self.rect.colliderect(mur.rect):
            if dx > 0 :
                self.rect.right = mur.rect.left
            if dx < 0 :
                self.rect.left = mur.rect.right
            if dy > 0 :
                self.rect.bottom = mur.rect.top
            if dy < 0 :
                self.rect.top = mur.rect.bottom 

1 个回答

1

下拉框里显示了一个叫 Mur 的类,但你提问中的代码里没有。我是根据你评论中显示的错误和我在下拉框看到的代码来回答的。看起来问题出在 self.rect 的定义上。

不过,请你再检查一下你执行的代码。错误信息显示:

追踪记录(最近的调用在最后):文件 "C:\Users\Maxime\ISN 2014\Dropbox\Deadalus\Partie Maxime\proto collision.py",第 74 行,在 Mur((x, y)) TypeError: object() 不接受参数

这似乎意味着你在第 40 行定义 self.rect 时做的更改,已经改变了定义,使得 Mur 不再接受这种调用。请确认一下原始代码是否能正常工作。同时也检查一下下拉框中的第 74 行是否是你正在运行的代码。

Mur(x, y)

以及

Mur((x, y))

之间的差异足以导致失败。

在你的代码中,你有

#Classe mur / Class for the wall ( it will be represented by a small .png 

class Mur(object):
  def _init_(self, pos): 
    murs.append(self) 
    # Put in a print statement here
    self.rect = pygame.image.load("mur.png").convert_alpha() # line 40

第 74 行是

#Création du niveau après 'lecture' des murs / Parse the level string above. M = wall, S = exit  line 69
x = y = 0                 # This is line 70
for rangée in niveau:     # This is line 71
  for colonne in rangée:  # This is line 72
    if colonne == "M":    # This is line 73
        Mur((x, y))       # This is line 74 and is the error
    if colonnne == "S": 
        end_rect = pygame.Rect(x, y, 30, 30) 
    x += 30
  y += 30
  x = 0

我把下拉框的内容和原始代码进行了比较。

一个很好的类来表示墙的矩形

类 Wall(object):

def __init__(self, pos):
    walls.append(self)
    self.rect = pygame.Rect(pos[0], pos[1], 16, 16)

# Parse the level string above. W = wall, E = exit
x = y = 0
for row in level:
  for col in row:
    if col == "W":
        Wall((x, y))
    if col == "E":
        end_rect = pygame.Rect(x, y, 16, 16)
    x += 16
  y += 16
  x = 0

撰写回答