Pygame屏幕碰撞故障,播放器移动屏幕

时间:2015-03-04 01:04:09

标签: python pygame screen collision

我已经看了很多代码来实现屏幕冲突,但我找不到任何我知道如何适应我自己的代码,所以我只需要一些帮助来弄清楚如何制作我的播放器不要通过屏幕。

import pygame
import random
pygame.init()

display_width = 800
display_height = 600



gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('proto')

black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
divider = pygame.image.load('divider.png')
spikeImg = pygame.image.load('spikey.png')
player = pygame.image.load('player.png')
bg = pygame.image.load('Backgroundlvl1.png')
attack = ['player.png', 'playerattack.png']
dead = False
images = ['player.png', 'playerwalk.png']
cat = pygame.image.load('catenemy.png')
playerX = 158
playerY = 400
walk1 = ['playerwalkright.png', 'faceright.png'] 
attack1 = ['playerattack1.png', 'faceright.png']
divider = pygame.image.load('divider.png')
YBuffer = 600 - 16

counter = 0


while not dead:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            dead = True

    ############################
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
        player = pygame.image.load(images[counter])
        counter = (counter + 1) % len(images)
        playerX = playerX + -5
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
        player = pygame.image.load(walk1[counter])
        counter = (counter + 9) % len(walk1)
        playerX = playerX + 5
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
        player = pygame.image.load(images[counter])
        counter = (counter + 1) % len(images)
        playerY = playerY + -25
if event.type == pygame.KEYUP and event.key == pygame.K_UP:
        player = pygame.image.load(images[counter])
        counter = (counter + 1) % len(images)
        playerY = playerY + 25
if event.type == pygame.KEYDOWN and event.key == pygame.K_z:
        player = pygame.image.load(attack[counter])
        counter = (counter + 1) % len(attack)

if event.type == pygame.KEYDOWN and event.key == pygame.K_x:
        player = pygame.image.load(attack1[counter])
        counter = (counter + 1) % len(attack1)            

##

gameDisplay.fill(black)
gameDisplay.blit(bg, (0,0))
gameDisplay.blit(player, (playerX, playerY))
gameDisplay.blit(cat, (636, 450))






pygame.display.flip()
clock.tick(60)

pygame.quit()
quit()

1 个答案:

答案 0 :(得分:0)

if playerX > display_width:
    playerX = display_width
elif playerX < 0:
    playerX = 0

这样可以防止玩家左右离开屏幕。