import pygame
from pygame.locals import (K_SPACE, KEYDOWN, QUIT)
class Obj:
def __init__(self):
self.x = 400
self.y = 300
self.dir = 0
def update(self): # 更新位置
if self.dir == 0:
self.up()
elif self.dir == 1:
self.right()
elif self.dir == 2:
self.down()
else:
self.left()
def up(self): # 上
self.y -= 1
if self.y <= 10:
self.dir = 1
def right(self): # 右
self.x += 1
if self.x >= 790:
self.dir = 2
def down(self): # 下
self.y += 1
if self.y >= 590:
self.dir = 3
def left(self): # 左
self.x -= 1
if self.x <= 10:
self.dir = 0
class App:
def __init__(self, WIDTH, HEIGHT,TEXT_HEIGHT):
pygame.init()
self.WIDTH = WIDTH
self.HEIGHT = HEIGHT
self.TEXT_HEIGHT = TEXT_HEIGHT
self.screen = pygame.display.set_mode((WIDTH, HEIGHT+TEXT_HEIGHT))
self.WHITE = (255, 255, 255)
self.BLACK = (0, 0, 0)
self.BLUE = (0, 0, 200)
def pause(self): # 暂停
self.showtext("press space to play")
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE: # 按空格恢复
return True
elif event.type == pygame.QUIT: # 退出
return False
def init(self): # 初始场景
self.screen.fill(self.WHITE)
def showtext(self,text): # 显示提示文字
bar = pygame.Surface((self.WIDTH, self.TEXT_HEIGHT)) # 字的背景条的大小
bar.fill(self.BLUE) # 颜色
rect = bar.get_rect()
self.screen.blit(bar, (0, self.HEIGHT)) # 显示位置
font = pygame.font.Font('freesansbold.ttf',self.TEXT_HEIGHT) # 字体和大小
TextSurface = font.render(text, True, self.BLACK) # 要显示的字和颜色
TextRect = TextSurface.get_rect()
TextRect.center = ((self.WIDTH/2),(self.HEIGHT+self.TEXT_HEIGHT/2)) # 显示位置
self.screen.blit(TextSurface, TextRect)
def run(self):
obj = Obj()
self.init() # 初始场景
running = self.pause() # 刚开始先暂停
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE: # 按空格暂停
running = self.pause()
elif event.type == pygame.QUIT: # 退出
running = False
self.screen.fill(self.WHITE) # 背景
self.showtext("press space to pause")
# --------------
surf = pygame.Surface((50, 50))
surf.fill((0, 0, 0))
rect = surf.get_rect()
self.screen.blit(surf, (obj.x, obj.y))
# --------------
pygame.display.flip() # 画
obj.update() # 更新
pygame.quit() # 退出循环后,结束
if __name__=='__main__':
WIDTH = 800
HEIGHT = 600
TEXT_HEIGHT = 60
App(WIDTH, HEIGHT, TEXT_HEIGHT).run()