Pygame欢乐打地鼠游戏_unit02 随机生成地鼠

14 篇文章 1 订阅
14 篇文章 0 订阅

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()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值