Pygame:创建边框

时间:2016-10-07 19:45:36

标签: python python-2.7 pygame

我一直在研究我的学校项目,这是一个带有可移动玩家的2D游戏。我希望在屏幕边缘创建一个边框。我已经阅读了其他几篇文章,但似乎无法解读它。如果有人可以帮助我会很棒。这是我的程序

import pygame
import os

black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)


class Player(object):  
    def __init__(self):
        self.image = pygame.image.load("player1.png")
        self.image2 = pygame.transform.flip(self.image, True, False) 
        self.coffee = pygame.image.load("coffee.png")
        self.computer = pygame.image.load("computer.png")
        self.background = pygame.image.load("background.png")
        self.flipped = False
        self.x = 0
        self.y = 0


    def handle_keys(self):
        """ Movement keys """
        key = pygame.key.get_pressed()
        dist = 5
        if key[pygame.K_DOWN]: 
            self.y += dist 
        elif key[pygame.K_UP]: 
            self.y -= dist 
        if key[pygame.K_RIGHT]: 
            self.x += dist
            self.flipped = False
        elif key[pygame.K_LEFT]:
            self.x -= dist
            self.flipped = True

    def draw(self, surface):
        if self.flipped:
            image = self.image2
        else:
            image = self.image
        surface.blit(self.background,(0,0))
        surface.blit(self.coffee, (725,500))
        surface.blit(self.computer,(15,500))
        surface.blit(image, (self.x, self.y))


pygame.init()

screen = pygame.display.set_mode((800, 600))    #creates the screen

player = Player() 
clock = pygame.time.Clock()

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()      # quit the screen
            running = False

    player.handle_keys()       # movement keys
    screen.fill((255,255,255)) # fill the screen with white
    player.draw(screen)        # draw the player to the screen
    pygame.display.update()    # update the screen

    clock.tick(60)             # Limits Frames Per Second to 60 or less

2 个答案:

答案 0 :(得分:1)

你可以做的是你可以为每个宽度和高度添加20个像素,并在周围绘制一系列正方形。

screen = pygame.display.set_mode((800 + 20, 600 + 20))


for x in range(0, 810, 10)
    pygame.draw.rect(surface, BLACK, [x, 0, 10, 10])
    pygame.draw.rect(surface, BLACK, [x, 610, 10, 10])

for x in range(0, 610, 10)
    pygame.draw.rect(screen, BLACK, [0, x, 10, 10])
    pygame.draw.rect(screen, BLACK, [810, x, 10, 10])

答案 1 :(得分:0)

尝试在player.draw(screen)之前将其添加到主要部分:

pygame.init()

line_width = 10
width = 800
height = 600
#creates the screen
screen = pygame.display.set_mode((width+line_width, height+line_width),0,32)    

screen.fill(white) # fill the screen with white
# top line
pygame.draw.rect(screen, black, [0,0,width,line_width])
# bottom line
pygame.draw.rect(screen, black, [0,height,width,line_width])
# left line
pygame.draw.rect(screen, black, [0,0,line_width, height])
# right line
pygame.draw.rect(screen, black, [width,0,line_width, height+line_width])