少儿编程分享:手把手教你用Python编写圣诞大挑战(一)

更新时间:2023-07-18 19:00:01 阅读量: 实用文档 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

是时候再来一个小游戏制作啦~

游戏分享:手把手教你用Python 编写

圣诞大挑战(一)

2018.1.6

刚刚过去了圣诞节

是不是还意犹未尽?

不如我们一起来做一个圣诞小游戏吧!

是时候再来一个小游戏制作啦~

游戏介绍

圣诞大挑战中,玩家将亲手控制圣诞码趣把圣诞老人(也就是码趣君)扔的礼物全部接住,来比比谁接的礼物更多吧!

TIPS

码趣君在扔礼物的时候还会扔雪球噢,要是砸到了圣诞码趣的头上,那就直接晕倒

啦!准备工作

1.#!/usr/bin/env python

2.

3.import random,os.path

4.import pygame

5.from pygame.locals import *

6.

7.#测试是否能够读取扩展图片格式

8.if not pygame.image.get_extended():

9.raise SystemExit("Sorry,extended image module required")

10.

11.

12.#游戏参数

13.BOMB_ODDS =60

14.SCREENRECT =Rect(0,0,640,480)

15.SCORE =0

16.

17.#素材路径

18.main_dir =os.path.split(os.path.abspath(__file__))[0]

19.

20.def load_image(file):

21."预读取图片"

22.file =os.path.join(main_dir,'data',file)

是时候再来一个小游戏制作啦~

23.try:

24.surface =pygame.image.load(file)

25.except pygame.error:

26.raise SystemExit('Could not load image "%s"%s'%(file,

pygame.get_error()))

27.return surface.convert()

28.

29.def load_images(*files):

30.imgs =[]

31.for file in files:

32.imgs.append(load_image(file))

33.return imgs

34.

35.

36.class dummysound:

37.def play(self):pass

38.

39.def load_sound(file):

40.if not pygame.mixer:return dummysound()

41.file =os.path.join(main_dir,'data',file)

42.try:

43.sound =pygame.mixer.Sound(file)

44.return sound

45.except pygame.error:

46.print ('Warning,unable to load,%s'%file)

47.return dummysound()

#!/usr/bin/env python 目的是在运行python 脚本的时候告诉操作系统我们要用python 解释器去运行py 脚本。

所以我们在第一句往往会写如下两句中的其中一句:#!/usr/bin/python 或#!/usr/bin/env python。

就是说在没有在执行程序时指出用什么程序运行py 脚本时,系统会去调用python 程序来执行。

是时候再来一个小游戏制作啦~

在这里要注意os.path 模块的应用,这个模块会帮助我们更好地链接上我们使用的素材,不仅能减少报错,也能加快读取的速度。

而在之后的类里我们在之前的游戏中都有使用过,而在这里我们增加了except 和raise 使得当程序出问题时能准确汇报错误的部分,并且当有这一部分时,即使程

序出错也能顺利运行下去。

(未完待续)

本文来源:https://www.bwwdw.com/article/shp1.html

Top