1. 加载所有地鼠图片
mouseImgList = [chr(i)+'.png' for i in range(97, 123)]
2. 预设地洞位置
posList = [[100, 200], [240, 200], [380, 200],
[100, 350], [240, 350], [380, 350]]
3. 随机生成地鼠
mouseImg = random.choice(mouseImgList)
mouseImgObj = pygame.image.load('./images/' + mouseImg)
mouseRect = mouseImgObj.get_rect()
mouse = {
'img': mouseImgObj,
'x': 0,
'y': 0,
'width': mouseRect.width,
'height': mouseRect.height,
}
4. 随机位置出现地鼠
x, y = random.choice(posList)
mouse['x'] = x - mouse['width'] / 2
mouse['y'] = y - mouse['height'] / 2
screen.blit(mouse['img'], (mouse['x'], mouse['y']))
5.封装createMouse()函数
def createMouse():
mouseImg = random.choice(mouseImgList)
mouseImgObj = pygame.image.load('./images/' + mouseImg)
mouseRect = mouseImgObj.get_rect()
mouse = {
'img': mouseImgObj,
'x': 0,
'y': 0,
'width': mouseRect.width,
'height': mouseRect.height,
}
x, y = random.choice(posList)
mouse['x'] = x - mouse['width'] / 2
mouse['y'] = y - mouse['height'] / 2
return mouse
完整代码
import pygame
import sys
import random
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('打地鼠')
iconImg = pygame.image.load('./images/a.png')
pygame.display.set_icon(iconImg)
bgImg = pygame.image.load('./images/背景.png')
mouseImgList = []
letterList = [chr(i) for i in range(97, 123)]
for letter in letterList:
mouseImgList.append('%s.png' % letter)
posList = [[100, 200], [240, 200], [380, 200],
[100, 350], [240, 350], [380, 350]]
def createMouse():
mouseImg = random.choice(mouseImgList)
mouseImgObj = pygame.image.load('./images/' + mouseImg)
mouseRect = mouseImgObj.get_rect()
mouse = {
'img': mouseImgObj,
'x': 0,
'y': 0,
'width': mouseRect.width,
'height': mouseRect.height,
}
x, y = random.choice(posList)
mouse['x'] = x - mouse['width'] / 2
mouse['y'] = y - mouse['height'] / 2
return mouse
def draw():
screen.blit(bgImg, (0, 0))
screen.blit(mouse['img'], (mouse['x'], mouse['y']))
def eventListen():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
mouse = createMouse()
while True:
pygame.time.Clock().tick(60)
eventListen()
draw()
pygame.display.update()