pygame写游戏,常用代码记录

pygame写起游戏(页游等)来还是挺不错的,不过我也没用过别的什么东西写,所以也没什么发言权。
下面是一些常用的代码片段,记录下来,给别人看,也用来给我想不起来的时候看看。

pygame的常见开头

# 1 - Import library
import math
import random
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
pygame.mixer.init() # music initial
width, height = 640, 480
screen=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_x
bullrect.top=bullet_y

badrect = pygame.Rect(badguyimg.get_rect())
badrect.left = badguy_x
badrect.top = badguy_y
if 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().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)

你可能感兴趣的:(游戏开发)