【发布时间】:2020-08-08 02:31:21
【问题描述】:
我对编码和 pygame 还很陌生,我正在尝试制作一个简单的迷宫游戏,您可以在其中拖动角色穿过迷宫而不撞到边(有点像棋盘游戏“操作”)。
大部分都在工作,但我不知道当它撞到迷宫的墙壁时让它停止移动的命令。我已经想出了如何让它寻找碰撞:
if player.colliderect(mazewall):
??????
但我不确定如何让“玩家”不通过“迷宫墙”。我正在寻找像这样工作的东西:
if player.bottom >= 390:
player.bottom = 390
因此,您可以随意拖动播放器,但仍无法将其拉到迷宫墙的上方或下方。 到目前为止,这是我的完整代码:
#Import stuff
import pygame as pg
from pygame import Surface
import time
#Initialize
pg.init()
#Some colours
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
blue = (0,0,255)
green = (0, 255, 0)
walls = (146, 200, 203)
background = (253, 208, 236)
#Make the size of the panel
screen_width = 700
screen_height = 430
screen = pg.display.set_mode([screen_width, screen_height])
pg.display.set_caption("Runner")
#x, y, How big)
player = pg.rect.Rect(50, 350, 17, 17)
player_dragging = False
#Make the maze
mazewall = pg.rect.Rect(20, 390, 200, 20)
Run = True
while Run:
for event in pg.event.get():
#If the player clicks the close button
if event.type == pg.QUIT:
Run = False
elif event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
Run = False
#All the player dragging stuff
elif event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
if player.collidepoint(event.pos):
player_dragging = True
mouse_x, mouse_y = event.pos
offset_x = player.x - mouse_x
offset_y = player.y - mouse_y
elif event.type == pg.MOUSEBUTTONUP:
if event.button == 1:
player_dragging = False
elif event.type == pg.MOUSEMOTION:
if player_dragging:
mouse_x, mouse_y = event.pos
player.x = mouse_x + offset_x
player.y = mouse_y + offset_y
#This is the bit I'm not sure about, I want it to work like this (Run the program)
if player.bottom >= 390:
player.bottom = 390
#But with this instead
#player.colliderect(mazewall)
#Set the background
screen.fill(background)
#Draw the player
pg.draw.rect(screen, black, player)
#Draw the maze
pg.draw.rect(screen, walls, mazewall)
pg.display.flip()
pg.quit()
【问题讨论】:
标签: python pygame collision-detection collision maze