我已经找到的所有教程都不适用于我。如果有人可以帮助,那就太好了。我的主要目标是制作类似《吃豆人》的游戏,但我无法摆脱冲突。我是pygame和python的新手。此刻,我只希望黄色圆圈不穿过蓝色矩形。如果您知道该怎么做,请告诉我!再说一次,我有点菜鸟,但找不到有效的例子。预先感谢!
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Pyman by Jonathan Curtis")
x = 50
y = 50
radius = 10
speed = 5
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
def mazeWall(startx, starty, endx, endy):
pygame.draw.line(win, BLUE, (startx, starty), (endx, endy), 10)
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_x]:
print(x)
if keys[pygame.K_y]:
print(y)
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
x -= speed
if keys[pygame.K_RIGHT] or keys[pygame.K_d] and not rightCollide:
x += speed
if keys[pygame.K_UP] or keys[pygame.K_w]:
y -= speed
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
y += speed
#Makes it impossible to go off the screen.
if x > 480:
x = 480
if x < 20:
x = 20
if y > 480:
y = 480
if y < 20:
y = 20
#Draws character
win.fill((0, 0, 0))
pygame.draw.circle(win, YELLOW, (x, y), radius)
#Draws the maze border
mazeWall(0, 1, 500, 1)
mazeWall(0, 1, 0, 500)
mazeWall(0, 499, 500, 499)
mazeWall(500, 0, 500, 500)
#Draws the rectangle
mazeWall(100, 50, 200, 50)
pygame.display.update()
pygame.quit()
答案 0 :(得分:2)
将迷宫墙转换为数据结构/类。甚至只是将它们保留为pygame.Rect的列表。还要在玩家对象周围保持Rect。
例如:
maze_walls = [ pygame.Rect(0, 1, 500, 1),
pygame.Rect(0, 1, 0, 500),
pygame.Rect(0, 499, 500, 499),
pygame.Rect(500, 0, 500, 500),
pygame.Rect(100, 50, 200, 50) ]
# this needs to have it's position updated when x & y change.
player_rect = pygame.Rect( x-radius, y-radius, 2*radius, 2*radius )
这将允许代码使用内置函数pygame.Rect.colliderect()和/或pygame.rect.collidelist()来检查冲突。
因此,这为以下墙壁提供了绘制循环:
#Draws character
win.fill((0, 0, 0))
pygame.draw.circle(win, YELLOW, (x, y), radius)
#Draws walls
for wall in maze_walls:
pygame.draw.rect( win, BLUE, wall )
pygame.display.update()
因此,要检查玩家和墙壁之间是否存在碰撞,请遍历墙壁检查每个墙壁都是不重要的:
# Did the player hit a wall
player_rect.center = (x, y)
for wall in maze_walls:
if ( player_rect.colliderect( wall ) ):
print( "Player hits wall: "+str( wall ) )
# TODO: stop movement, whatever
当然,使用PyGame Sprites可以有更好的方法,但是我试图使答案尽可能接近您的代码现在所做的,同时尽可能使答案保持简单。