写起游戏来还是挺不错的,不过我也没用过别的什么东西写,所以也没什么发言权。 些游戏我是从这篇文章开始入门的
下面是一些常用的代码片段,记录下来,给别人看,也用来给我想不起来的时候看看。
pygame的常见开头
# 1 - Import libraryimport mathimport randomimport pygamefrom pygame.locals import * # 2 - Initialize the gamepygame.init()pygame.mixer.init() # music initialwidth, height = 640, 480screen=pygame.display.set_mode((width, height))
加载图片和声音
player = pygame.image.load("resources/images/dude.png")screen.blit(player, (100, 100))hit = pygame.mixer.Sound("resources/audio/explode.wav")hit.set_volume(0.05)
碰撞检测
bullrect=pygame.Rect(arrow.get_rect())bullrect.left=bullet_xbullrect.top=bullet_ybadrect = pygame.Rect(badguyimg.get_rect())badrect.left = badguy_xbadrect.top = badguy_yif badrect.colliderect(bullrect): print 'Shooted'
常见事件循环
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) if event.type == pygame.KEYDOWN: if event.key == K_q: pygame.quit() exit(0) # refresh screen pygame.display.flip()
显示文字
pygame.font.init()font = pygame.font.Font(None, 24)text = font.render("Good job", True, (255,0,0))textRect = text.get_rect()textRect.centerx = screen.get_rect().centerxtextRect.centery = screen.get_rect().centery+24screen.blit(gameover, (0,0))screen.blit(text, textRect)