我一直在尝试学习PyGame的基础知识,所以我一直在尝试制作一个非常基础的游戏。游戏(应该)由一个红色方块组成,该方块会四处移动,如果碰到从天上掉落的蓝色方块之一,则会丢失。一切正常,除了碰撞检测器不检测任何东西。谁能帮我?这是代码:
import pygame as pg
import sys
import random as rd
pg.init()
winWidth = 850
winHeight = 600
red = (255, 0, 0)
blue = (0, 0, 255)
speed = 10
player_pos = [int(winWidth/2-25), winHeight-100]
enemyList = []
clock = pg.time.Clock()
win = pg.display.set_mode((winWidth, winHeight))
pg.display.set_caption('Game')
# creates the position of the enemy and returns it
def createEnemy():
enemy = [rd.randrange(0, winWidth-50, 50), 0]
return enemy
# draws an enemy in the position received
def drawEnemy(enemy_pos):
pg.draw.rect(win, blue, (enemy_pos[0], enemy_pos[1], 50, 50))
# if the enemy is inside the screen, it is moved downwards.
# else, it is deleted from the list.
def updateEnemy(enemy_pos):
if 0 <= enemy_pos[1] < winHeight:
enemy_pos[1] += speed
else:
enemyList.remove(enemy_pos)
# detects collisions
def collisionDetector(enemy):
if enemy[0] == player_pos[0] and enemy[1] >= player_pos[1] + 50 >= enemy[1] + 50:
return True
elif enemy[0] == player_pos[0] and enemy[1] >= player_pos[1] >= enemy[1] + 50:
return True
return False
while True:
# keeps 10 enemies on screen always
while len(enemyList) < 11:
enemyList.append(createEnemy())
# moves the player
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_LEFT:
player_pos[0] -= 50
elif event.key == pg.K_RIGHT:
player_pos[0] += 50
for enemy_pos in enemyList:
updateEnemy(enemy_pos)
for enemy in enemyList:
if collisionDetector(enemy):
sys.exit()
win.fill((0, 0, 0))
pg.draw.rect(win, red, (player_pos[0], player_pos[1], 50, 50))
for enemy_pos in enemyList:
drawEnemy(enemy_pos)
clock.tick(30)
pg.display.update()
答案 0 :(得分:1)
重新检查碰撞检测条件。这行得通,但需要进行微调。
if enemy[0] == player_pos[0] and enemy[1] <= player_pos[1] + 50 <= enemy[1] + 50:
return True
elif enemy[0] == player_pos[0] and enemy[1] <= player_pos[1] <= enemy[1] + 50:
return True
return False
答案 1 :(得分:1)
我建议使用pygame.Rect
对象和.colliderect()
检查矩形的碰撞:
# detects collisions
def collisionDetector(enemy):
playerRect = pg.Rect(*player_pos, 50, 50)
enemyRect = pg.Rect(*enemy, 50, 50)
return playerRect.colliderect(enemyRect)