用pygame学习初级python(二) 15.5.11

  闲得无聊,对第一版的东西做了一些修改,让它更像一个游戏,也具有一些可玩性。

项目的github地址: https://github.com/lfkdsk/BrainHole_pygame

1.人物类进行了一些修改,添加了怪物类的生成机制:

  1 __author__ = ‘Administrator‘
  2 import pygame
  3
  4 Window_width = 1365
  5 Window_height = 768
  6 screen = pygame.display.set_mode((Window_width, Window_height))
  7 first_location = [screen.get_width() / 2, screen.get_height() / 2]
  8 Player_image_up = [‘resources/image/up-1.png‘, ‘resources/image/up-2.png‘, ‘resources/image/up-3.png‘,
  9                    ‘resources/image/up-4.png‘]
 10 Player_image_down = [‘resources/image/down-1.png‘, ‘resources/image/down-2.png‘, ‘resources/image/down-3.png‘,
 11                      ‘resources/image/down-4.png‘]
 12 Player_image_left = [‘resources/image/left-1.png‘, ‘resources/image/left-2.png‘, ‘resources/image/left-3.png‘,
 13                      ‘resources/image/left-4.png‘]
 14 Player_image_right = [‘resources/image/right-1.png‘, ‘resources/image/right-2.png‘, ‘resources/image/right-3.png‘,
 15                       ‘resources/image/right-4.png‘]
 16 Enemy_image = ["resources/image/zm-1.png", "resources/image/zm-2.png"]
 17 Bullets = []
 18
 19
 20 class Enemy(pygame.sprite.Sprite):
 21     def __init__(self, init_pos):
 22         pygame.sprite.Sprite.__init__(self)
 23         self.image = pygame.image.load("resources/image/zm-2.png")
 24         self.rect = self.image.get_rect()
 25         self.rect.topleft = init_pos
 26         self.speed = 2
 27         self.down_index = 0
 28         self.walk = 0
 29
 30     def move(self):
 31         topleft = self.rect.topleft
 32         if self.walk > 40:
 33             self.walk = 0
 34             self.image = pygame.image.load("resources/image/zm-2.png")
 35         if self.walk == 20:
 36             self.image = pygame.image.load("resources/image/zm-1.png")
 37         self.rect = self.image.get_rect()
 38         self.rect.topleft = topleft
 39         self.walk += 1
 40         self.rect.centerx -= self.speed
 41
 42
 43 class Bullet(pygame.sprite.Sprite):
 44     def __init__(self, init_pos):
 45         pygame.sprite.Sprite.__init__(self)
 46         self.image = pygame.image.load(‘resources/image/bullet.png‘)
 47         self.rect = self.image.get_rect()
 48         self.rect.midtop = init_pos
 49         self.speed = 10
 50         self.walk = 0
 51
 52     def move(self, button_flag):
 53         if button_flag == 1:
 54             self.rect.centerx -= self.speed
 55         elif button_flag == 0:
 56             self.rect.centerx += self.speed
 57         elif button_flag == 2:
 58             self.rect.centery += self.speed
 59         elif button_flag == 3:
 60             self.rect.centery -= self.speed
 61             # self.rect.centery += self.speed
 62             # screen.blit(self.image,self.rect)
 63             # pygame.display.update()
 64
 65
 66 class Player(pygame.sprite.Sprite):
 67     def __init__(self):
 68         pygame.sprite.Sprite.__init__(self)
 69         self.image = pygame.image.load(‘resources/image/down-1.png‘)
 70         self.rect = self.image.get_rect()
 71         self.rect.center = first_location
 72         self.is_hit = False
 73         self.speed = 15
 74         self.down = 0
 75         self.left = 0
 76         self.right = 0
 77         self.up = 0
 78         # print self.rect.center
 79
 80     def turn(self, distance):
 81         center = self.rect.center
 82         if distance == 2:
 83             if self.down > 3:
 84                 self.down = 0
 85             self.image = pygame.image.load(Player_image_down[self.down])
 86             self.rect = self.image.get_rect()
 87             self.rect.center = center
 88             self.down += 1
 89             # screen.blit(player.image, player.rect)
 90         elif distance == 0:
 91             if self.left > 3:
 92                 self.left = 0
 93             self.image = pygame.image.load(Player_image_left[self.left])
 94             self.rect = self.image.get_rect()
 95             self.rect.center = center
 96             self.left += 1
 97         elif distance == 3:
 98             if self.up > 3:
 99                 self.up = 0
100             self.image = pygame.image.load(Player_image_up[self.up])
101             self.rect = self.image.get_rect()
102             self.rect.center = center
103             self.up += 1
104         elif distance == 1:
105             if self.right > 3:
106                 self.right = 0
107             self.image = pygame.image.load(Player_image_right[self.right])
108             self.rect = self.image.get_rect()
109             self.rect.center = center
110             self.right += 1
111
112     def move(self, temper):
113         temper = int(temper)
114         if temper == 0:
115             for temp in range(1, 10):
116                 self.rect.centerx -= 3
117             print self.rect.centerx, self.rect.centery
118         if temper == 1:
119             self.rect.centerx += self.speed
120             print self.rect.centery
121         if temper == 2:
122             self.rect.centery -= self.speed
123             print self.rect.centerx, self.rect.centery
124         if temper == 3:
125             self.rect.centery += self.speed
126         if 0 > self.rect.centerx or self.rect.centerx > screen.get_width():
127             self.rect.centerx = -self.rect.centerx
128         if 0 > self.rect.centery or self.rect.centery > screen.get_height():
129             self.rect.centery = -self.rect.centery
130
131     def shoot(self):
132         bullet = Bullet(self.rect.midtop)
133         Bullets.append(bullet)

 1 __author__ = ‘Administrator‘
 2 import pygame
 3
 4 Window_width = 1365
 5 Window_height = 768
 6 screen = pygame.display.set_mode((Window_width, Window_height))
 7 first_location = [screen.get_width() / 2, screen.get_height() / 2]
 8 Player_image_up = [‘resources/image/up-1.png‘, ‘resources/image/up-2.png‘, ‘resources/image/up-3.png‘,
 9                    ‘resources/image/up-4.png‘]
10 Player_image_down = [‘resources/image/down-1.png‘, ‘resources/image/down-2.png‘, ‘resources/image/down-3.png‘,
11                      ‘resources/image/down-4.png‘]
12 Player_image_left = [‘resources/image/left-1.png‘, ‘resources/image/left-2.png‘, ‘resources/image/left-3.png‘,
13                      ‘resources/image/left-4.png‘]
14 Player_image_right = [‘resources/image/right-1.png‘, ‘resources/image/right-2.png‘, ‘resources/image/right-3.png‘,
15                       ‘resources/image/right-4.png‘]
16 Enemy_image = ["resources/image/zm-1.png", "resources/image/zm-2.png"]
17 Bullets = []

首先,初始化了屏幕的大小,并且设置了图片资源。

 1 class Enemy(pygame.sprite.Sprite):
 2     def __init__(self, init_pos):
 3         pygame.sprite.Sprite.__init__(self)
 4         self.image = pygame.image.load("resources/image/zm-2.png")
 5         self.rect = self.image.get_rect()
 6         self.rect.topleft = init_pos
 7         self.speed = 2
 8         self.down_index = 0
 9         self.walk = 0
10
11     def move(self):
12         topleft = self.rect.topleft
13         if self.walk > 40:
14             self.walk = 0
15             self.image = pygame.image.load("resources/image/zm-2.png")
16         if self.walk == 20:
17             self.image = pygame.image.load("resources/image/zm-1.png")
18         self.rect = self.image.get_rect()
19         self.rect.topleft = topleft
20         self.walk += 1
21         self.rect.centerx -= self.speed

怪物类设置了一个move函数,在初始化里设定了一个walk的值,能让在自增的过程中,不断的切换图片。

就是这样的两张图片。

 1 class Bullet(pygame.sprite.Sprite):
 2     def __init__(self, init_pos):
 3         pygame.sprite.Sprite.__init__(self)
 4         self.image = pygame.image.load(‘resources/image/bullet.png‘)
 5         self.rect = self.image.get_rect()
 6         self.rect.midtop = init_pos
 7         self.speed = 10
 8         self.walk = 0
 9
10     def move(self, button_flag):
11         if button_flag == 1:
12             self.rect.centerx -= self.speed
13         elif button_flag == 0:
14             self.rect.centerx += self.speed
15         elif button_flag == 2:
16             self.rect.centery += self.speed
17         elif button_flag == 3:
18             self.rect.centery -= self.speed

子弹类添加了在不同移动方向上的不同移动方法,可以向左右两个方向发射。

(发射飞剑!)

 1 class Player(pygame.sprite.Sprite):
 2     def __init__(self):
 3         pygame.sprite.Sprite.__init__(self)
 4         self.image = pygame.image.load(‘resources/image/down-1.png‘)
 5         self.rect = self.image.get_rect()
 6         self.rect.center = first_location
 7         self.is_hit = False
 8         self.speed = 15
 9         self.down = 0
10         self.left = 0
11         self.right = 0
12         self.up = 0
13         # print self.rect.center
14
15     def turn(self, distance):
16         center = self.rect.center
17         if distance == 2:
18             if self.down > 3:
19                 self.down = 0
20             self.image = pygame.image.load(Player_image_down[self.down])
21             self.rect = self.image.get_rect()
22             self.rect.center = center
23             self.down += 1
24             # screen.blit(player.image, player.rect)
25         elif distance == 0:
26             if self.left > 3:
27                 self.left = 0
28             self.image = pygame.image.load(Player_image_left[self.left])
29             self.rect = self.image.get_rect()
30             self.rect.center = center
31             self.left += 1
32         elif distance == 3:
33             if self.up > 3:
34                 self.up = 0
35             self.image = pygame.image.load(Player_image_up[self.up])
36             self.rect = self.image.get_rect()
37             self.rect.center = center
38             self.up += 1
39         elif distance == 1:
40             if self.right > 3:
41                 self.right = 0
42             self.image = pygame.image.load(Player_image_right[self.right])
43             self.rect = self.image.get_rect()
44             self.rect.center = center
45             self.right += 1
46
47     def move(self, temper):
48         temper = int(temper)
49         if temper == 0:
50             for temp in range(1, 10):
51                 self.rect.centerx -= 3
52             print self.rect.centerx, self.rect.centery
53         if temper == 1:
54             self.rect.centerx += self.speed
55             print self.rect.centery
56         if temper == 2:
57             self.rect.centery -= self.speed
58             print self.rect.centerx, self.rect.centery
59         if temper == 3:
60             self.rect.centery += self.speed
61         if 0 > self.rect.centerx or self.rect.centerx > screen.get_width():
62             self.rect.centerx = -self.rect.centerx
63         if 0 > self.rect.centery or self.rect.centery > screen.get_height():
64             self.rect.centery = -self.rect.centery
65
66     def shoot(self):
67         bullet = Bullet(self.rect.midtop)
68         Bullets.append(bullet)

修改了turn函数让图片不断切换的,在字符数组里不断的进行切换图片,做出人物(李逍遥)走路的样子。

(利用图片的反复切换)

2.主函数体的修改:

  1 import random
  2
  3 __author__ = ‘Administrator‘
  4
  5 from pygame.locals import *
  6 from Class import *
  7 from sys import exit
  8
  9
 10 background_image_filename = ‘resources/image/gamestart.png‘
 11 start_image = ‘resources/image/bg2.png‘
 12 dead_image = ‘resources/image/dead.png‘
 13
 14 Score = 0
 15 x = 0
 16 y = 0
 17 pygame.init()
 18 pygame.mixer.init()
 19 background = pygame.image.load(background_image_filename).convert()
 20 pygame.key.set_repeat(100, 100)
 21 clock = pygame.time.Clock()
 22
 23 pygame.mixer.music.load("resources/music/butterflylove.mp3")# 初始化背景音乐
 24 pygame.mixer.music.set_volume(0.3)
 25 pygame.mixer.music.play(-1)
 26
 27 button_music = pygame.mixer.Sound("resources/music/bullet.wav")# 初始化发射音乐
 28 button_music.set_volume(10)
 29 # music
 30
 31 def Waitkey():
 32     while True:
 33         for event in pygame.event.get():
 34             if event.type == QUIT:
 35                 exit()
 36             if event.type == KEYDOWN:
 37                 if event.key == K_ESCAPE:  # pressing escape quits
 38                     exit()
 39                 if event.key == K_RETURN:
 40                     return
 41 # font
 42 flag = 0
 43 button_flag = 0
 44 enemies = []
 45 enemies_down = []
 46 enemy_frequency = 0
 47 running = True
 48 while running:
 49     clock.tick(60)    # 强置设定为不超过60帧每秒
 50     if enemy_frequency % 50 == 0:
 51         enemy1_pos = [screen.get_width(), random.randint(0, screen.get_height())]# 在屏幕的右侧随机生成怪物
 52         enemy1 = Enemy(enemy1_pos)
 53         enemies.append(enemy1)                
 54     enemy_frequency += 1
 55     if enemy_frequency >= 100:
 56         enemy_frequency = 0
 57     for event in pygame.event.get():
 58         if event.type == QUIT:
 59             exit()
 60         if event.type == KEYDOWN:
 61             if flag == 0:
 62                 if event.key == pygame.K_1:
 63                     background = pygame.image.load(start_image).convert()
 64                     player = Player()
 65                     print screen.get_width()
 66                     print screen.get_height()
 67                     flag = 1
 68             elif event.key == pygame.K_4:
 69                 exit()
 70             elif event.key == pygame.K_RIGHT:            # 分别有不同的移动方向
 71                 if flag == 1:
 72                     player.turn(1)
 73                     player.move(1)
 74                     button_flag = 0
 75                     # flag == 1
 76                     print "buttonflag" and button_flag
 77             elif event.key == pygame.K_LEFT:
 78                 if flag == 1:
 79                     player.turn(0)
 80                     player.move(0)
 81                     button_flag = 1
 82                     print "buttonflag" and button_flag
 83             elif event.key == pygame.K_UP:
 84                 if flag == 1:
 85                     player.turn(3)
 86                     player.move(2)
 87                     button_flag = 3
 88                     # flag == 1
 89             elif event.key == pygame.K_DOWN:
 90                 if flag == 1:
 91                     player.turn(2)
 92                     player.move(3)
 93                     button_flag = 2
 94             elif event.key == pygame.K_x:
 95                 if flag == 1:
 96                     player.shoot()
 97                     button_music.play()
 98                     print("shoot")
 99     screen.blit(background, (x, y))
100     if flag == 1:
101         score_font = pygame.font.Font(None, 50)                  # 初始化在左上角的score分数
102         score_surf = score_font.render("Score: " + str(Score), 1, (0, 0, 0))
103         screen.blit(score_surf, [10, 10])
104         screen.blit(player.image, player.rect)
105         for enemy in enemies:
106             enemy.move()
107             screen.blit(enemy.image, enemy.rect)
108             if enemy.rect.left < 0:
109                 enemies.remove(enemy)
110                 break
111             if pygame.sprite.collide_circle(enemy, player):
112                 enemies_down.append(enemy)
113                 enemies.remove(enemy)
114                 # player.is_hit = True
115                 Score -= 1                      # 每次人物和怪物碰撞的时候分数就会-1
116                 # Game_Over()
117                 break
118         for bullet in Bullets:
119             bullet.move(button_flag)
120             screen.blit(bullet.image, bullet.rect)
121             for enemy in enemies:
122                 if pygame.sprite.collide_circle(bullet, enemy):
123                     enemies_down.append(enemy)
124                     enemies.remove(enemy)
125                     Bullets.remove(bullet)
126                     Score += 1                      # 然后只要子弹和怪物碰撞子弹会消失然后怪物消失,分数+1
127                     break
128             if bullet is not None:
129                 if bullet.rect.bottom < 0 or bullet.rect.centerx > screen.get_width() or bullet.rect.centerx < 0:
130                     Bullets.remove(bullet)
131         if Score < -10:
132             background_dead = pygame.image.load(dead_image).convert()    # -10分以下就会播放失败图片然后退出
133             screen.blit(background_dead, (x, y))
134     pygame.display.update()
135     if flag == 0:
136         pygame.display.update()

(死亡的界面)

注释里写的很详细了哦,这次改完之后会出现可随按键移动的子弹类似飞剑的效果哦!

好了第二篇就是这样,喜欢就点赞吧,=-=!

项目的github地址: https://github.com/lfkdsk/BrainHole_pygame
时间: 2024-11-08 04:11:29

用pygame学习初级python(二) 15.5.11的相关文章

Python学习笔记(二)——高级特性

知识点 切片 切片 取一个list或tuple的部分元素. 原理:调用__getitem__,__setitem__,__delitem__和slice函数. 根据官方的帮助文档(https://docs.python.org/2/library/operator.html)可知,_getitem_返回元素的下标,_setitem_设置元素的值,_remove_删除元素的值. 而slice函数实现最重要的切片功能.            x=a[1:5] --> x._getitem_(slic

Python 数据分析(二 本实验将学习利用 Python 数据聚合与分组运算,时间序列,金融与经济数据应用等相关知识

Python 数据分析(二) 本实验将学习利用 Python 数据聚合与分组运算,时间序列,金融与经济数据应用等相关知识 第1节 groupby 技术 第2节 数据聚合 第3节 分组级运算和转换 第4节 透视表和交叉表 第5节 时间序列 第6节 日期的规范.频率以及移动 第7节 时区处理 第8节 时期及算术运算 第9节 重采样及频率转换 第10节 时间序列绘图 groupby 技术 一.实验简介 Python 数据分析(二)需要同学们先行学完 Python 数据分析(一)的课程. 对数据集进行分

Tornado/Python 学习笔记(二)

部分ssrpc.py代码分析 -- 服务端: 1 #!/usr/bin/python3 2 3 from xmlrpc.client import Fault, dumps, loads 4 import sys 5 from socketserver import ForkingMixIn 6 from xmlrpc.server import SimpleXMLRPCServer 7 8 class VerboseFaultXMLRPCServer(SimpleXMLRPCServer):

python 学习笔记 (二)

逻辑运算符 python不用&& || !表示与或非,用and or not,优先级是not > and > or. bool类型:True 和 False 条件语句 if expression1: ; elif expression2: ; else: ; 字符串函数 word = raw_input("Enter a word: ") # 读入字符串给word isalpha()  # 返回False如果字符串里含有非字母字符 word = word[n

python学习[第十二篇] 数据类型之 集合

python学习[第十二篇] 数据类型之 集合 集合概念 python中集合是一组无序排列的哈希值.集合分为两种可变集合(set)和不可变集合(frozenset) 对可变集合可以修改和删除元素,对于不可变集合不允许.可变集合是不可以哈希的,因此既不能用作字典的键,也不能做其他集合的元素. 集合的增删改查 集合的创建于赋值 集合与列表([]) 和字典({})不同,集合没有特别的语法格式.列表和字典可以通过他们自己的工厂方法创建,这也是集合的唯一的创建方式.set()和frozenset() #创

Numpy学习笔记(二)

最近一直在学HTML5和CSS3,Numpy的东西都有些生疏,那本书是已经看完了的,紧跟着相关的代码也都敲了一遍,还是发现了一些问题,因为这样的学习方式,总感觉太被动,紧紧跟着示例代码,缺少了整体观,即使你现在问我Numpy可以处理什么问题,我还是回答不出.所以,有必要回头重来一遍,再一次审视代码背后的意义,写博客真的是一个很不错的方式,毕竟,如果你不懂,写出来的文字必然也是混乱的. 那,下面记录一下Numpy学习笔记(二) Example1 文件读写:数据不应该仅仅存在内存里,应该及时保存在硬

学习资源(二)

最近在微博中发现MOOC上有了Python的教程,出于兴趣就打算简单的听一听了解一下,今天听了第一期的讲座,老师讲的非常形象,大家有兴趣可以去看一看 https://class.coursera.org/pythonlearn-002/lecture 课程是全英文的,但是有英文字幕,在学习的同时可以学习英语^-^ (手机上有Coursera的客户端可以同步学习纪录,还可以离线下载视频教程) 网易云课堂上的MOOC也会在6月10日发布哈工大的Python教程 Codecademy上边也有类似与Co

JavaWeb学习总结(三)——Tomcat服务器学习和使用(二) 包含https 非对称秘钥 NB

JavaWeb学习总结(三)--Tomcat服务器学习和使用(二) 一.打包JavaWeb应用 在Java中,使用"jar"命令来对将JavaWeb应用打包成一个War包,jar命令的用法如下: 范例:将JavaWebDemoProject这个JavaWeb应用打包成war包 执行完之后,就可以得到一个文件,平时开发完JavaWeb应用后,一般都会将JavaWeb应用打包成一个war包,然后将这个war包放到Tomcat服务器的webapps目录下,当Tomcat服务器启动时,就会自动

Android Web Service学习总结(二)

上篇文章做好了准备工作,现在就实践(android平台调用web service实现号码归属地查询) 1.    Ksoap2-android简介 在Android平台调用web service需要依赖于第三方类库ksoap2,它是一个SOAP Web service客户端开发包,主要用于资源受限制的Java环境如Applets或J2ME应用程序(CLDC/ CDC/MIDP).在Android平台中我们并不会直接使用ksoap2,而是使用ksoap2 android.KSoap2 Androi