點擊藍字 關注我們
Python是一門非常簡單的語言,快速入門之后可以做很多事情!比如爬蟲啊,數(shù)據(jù)分析啊,自動化運維啊,機器學習,量化分析等等!但是入門到進階的過程有時會非常痛苦,如果有一些好玩有趣的例子就好了。
比如通過游戲來學編程是一個非常好的途徑,今天強哥就來寫一個非常好玩的打飛機游戲,大概就1000多行,非常不錯!
1、打飛機的游戲
打飛機的游戲估計很多人都玩過,雷霆戰(zhàn)機相信很多80后的小伙伴都玩過!
Python是一門非常簡單的語言,快速入門之后可以做很多事情!比如爬蟲啊,數(shù)據(jù)分析啊,自動化運維啊,機器學習,量化分析等等!
但是入門到進階的過程有時會非常痛苦,如果有一些好玩有趣的例子就好了。比如通過游戲來學編程是一個非常好的途徑
2、代碼講解
1.代碼的結構
2.游戲的角色文件
gameRole 整個游戲分三個角色,下面我一一來解釋一下,思路其實非常清晰的。
1)一個是子彈
初始化子彈的圖片,然后得到它在畫布上的坐標,并控制它的移動速度
2)敵機
會隨機出一堆敵人的飛機,直管往前沖,從屏幕的上方往下方蜂擁而至,不需要考慮其他的行為!
敵機有幾個重要的屬性,比如它的飛行圖片和擊落的圖片,然后獲取的屏幕上的坐標。敵機的行為就一個飛,而且是只會往前飛。
3)我方戰(zhàn)機
玩家類class Player(pygame.sprite.Sprite):` `def __init__(self, plane_img, player_rect, init_pos):` `pygame.sprite.Sprite.__init__(self)` `self.image = [] # 用來存儲玩家對象精靈圖片的列表` `for i in range(len(player_rect)):` `self.image.append(plane_img.subsurface(player_rect[i]).convert_alpha())` `self.rect = player_rect[0] # 初始化圖片所在的矩形` `self.rect.topleft = init_pos # 初始化矩形的左上角坐標` `self.speed = 8 # 初始化玩家速度,這里是一個確定的值` `self.bullets = pygame.sprite.Group() # 玩家飛機所發(fā)射的子彈的集合` `self.img_index = 0 # 玩家精靈圖片索引` `self.is_hit = False # 玩家是否被擊中 def shoot(self, bullet_img): bullet = Bullet(bullet_img, self.rect.midtop) self.bullets.add(bullet) ` `def moveUp(self):` `if self.rect.top <= 0:` `self.rect.top = 0` `else:` `self.rect.top -= self.speed def moveDown(self): if self.rect.top >= SCREEN_HEIGHT - self.rect.height: self.rect.top = SCREEN_HEIGHT - self.rect.height else: self.rect.top += self.speed ` `def moveLeft(self):` `if self.rect.left <= 0:` `self.rect.left = 0` `else:` `self.rect.left -= self.speed def moveRight(self): if self.rect.left >= SCREEN_WIDTH - self.rect.width: self.rect.left = SCREEN_WIDTH - self.rect.width else: self.rect.left += self.speed
我方的戰(zhàn)機稍微復雜一點,它有這么幾個主要的屬性,飛行的圖片,被擊落的圖片,屏幕坐標,它的子彈等等!然后我們需要控制它的飛機方向,向上,向下,左邊和右邊,發(fā)射子彈。
完整代碼請?zhí)砑有≈肢@取哦,有什么不懂的問題也可以隨時咨詢~
請長按掃碼添加小助手
3.主游戲部分文件mainGame
1)先是初始化游戲的界面大小,字體等等,讀取聲音和圖片和基本配置:
class HeroPlane(BasePlane):
global supply_size ` `def __init__(self, screen_temp):` `BasePlane.__init__(self, 3, screen_temp, 210, 728, "./feiji/hero1.png", 4, HP_list[3]) # super().__init__()` `BasePlane.crate_images(self, "hero_blowup_n")` `self.key_down_list = [] # 用來存儲鍵盤上下左右移動鍵` `self.space_key_list = [] # 保存space鍵` `self.is_three_bullet = False` `self.barrel_2 = [] # 2號炮管(左)` `self.barrel_3 = [] # 3號炮管(右)` `self.three_bullet_stock = 50 # 三管齊發(fā)子彈初始值為50
# 單鍵移動方向
def move_left(self):
self.x -= 7 ` `def move_right(self):` `self.x += 7
def move_up(self):
self.y -= 6 ` `def move_down(self):` `self.y += 6
# 雙鍵移動方向
def move_left_and_up(self):
self.x -= 5
self.y -= 6 ` `def move_right_and_up(self):` `self.x += 5` `self.y -= 6
def move_lef_and_down(self):
self.x -= 5
self.y += 6 ` `def move_right_and_down(self):` `self.x += 5` `self.y += 6
# 控制飛機左右移動范圍s
def move_limit(self):
if self.x < 0:
self.x = -2
elif self.x + 100 > 480:
self.x = 380
if self.y > 728:
self.y = 728
elif self.y < 350:
self.y += 6 ` `# 鍵盤按下向列表添加按鍵` `def key_down(self, key):` `self.key_down_list.append(key)
# 鍵盤松開向列表刪除按鍵
def key_up(self, key):
if len(self.key_down_list) != 0: # 判斷是否為空
try:
self.key_down_list.remove(key)
except Exception:
pass ` `# 控制hero的持續(xù)移動` `def press_move(self):` `if len(self.key_down_list) != 0:` `if len(self.key_down_list) == 2: # 兩個鍵` `if (self.key_down_list[0] == K_LEFT and self.key_down_list[1] == K_UP) or (` `self.key_down_list[1] == K_LEFT and self.key_down_list[` `0] == K_UP): # key_down_list列表存在按鍵為left,up 或 up,left時調用move_left_and_up()方法` `self.move_left_and_up()` `elif (self.key_down_list[0] == K_RIGHT and self.key_down_list[1] == K_UP) or (` `self.key_down_list[1] == K_RIGHT and self.key_down_list[0] == K_UP):` `self.move_right_and_up()` `elif (self.key_down_list[0] == K_LEFT and self.key_down_list[1] == K_DOWN) or (` `self.key_down_list[1] == K_LEFT and self.key_down_list[0] == K_DOWN):` `self.move_lef_and_down()` `elif (self.key_down_list[0] == K_RIGHT and self.key_down_list[1] == K_DOWN) or (` `self.key_down_list[1] == K_RIGHT and self.key_down_list[0] == K_DOWN):` `self.move_right_and_down()` `else: # 一個鍵` `if self.key_down_list[0] == K_LEFT:` `self.move_left()` `elif self.key_down_list[0] == K_RIGHT:` `self.move_right()` `elif self.key_down_list[0] == K_UP:` `self.move_up()` `elif self.key_down_list[0] == K_DOWN:` `self.move_down()
# 自爆
def bomb(self):
self.hitted = True
self.HP = 0 ` `# 鍵盤按下向列表添加space` `def space_key_down(self, key):` `self.space_key_list.append(key)
# 鍵盤松開向列表刪除space
def space_key_up(self, key):
if len(self.space_key_list) != 0: # 判斷是否為空
try:
self.space_key_list.pop(0)
except Exception:
raise ` `# 按鍵space不放,持續(xù)開火` `def press_fire(self):` `if len(self.bullet_list) == 0 and len(self.space_key_list):` `self.fire()` `else:` `if len(self.space_key_list) != 0:` `if self.bullet_list[len(self.bullet_list) - 1].y < self.y - 14 - 60:` `self.fire()
# 開火
def fire(self):
global plane_maximum_bullet
hero_fire_music.play()
if not self.is_three_bullet:
if len(self.bullet_list) < plane_maximum_bullet[self.plane_type]: # 單發(fā)炮臺子彈限制為8
self.bullet_list.append(Bullet(self.screen, self.x + 40, self.y - 14, self))
else: # 沒有子彈限制
# 主炮管
self.bullet_list.append(Bullet(self.screen, self.x + 40, self.y - 14, self))
# 創(chuàng)建2,3號炮管子彈
self.barrel_2.append(Bullet(self.screen, self.x + 5, self.y + 20, self))
self.barrel_3.append(Bullet(self.screen, self.x + 75, self.y + 20, self))
self.three_bullet_stock -= 1 # 三管炮彈彈藥余量-1
if not self.three_bullet_stock: # 三管齊發(fā)彈藥用完
self.is_three_bullet = False``
# 是否吃到補給
def supply_hitted(self, supply_temp, width, height): # widht和height表示范圍
if supply_temp and self.HP:
# 更加精確的判斷是否吃到補給
supply_temp_left_x = supply_temp.x + supply_size[supply_temp.supply_type][“width”] * 0.15
supply_temp_right_x = supply_temp.x + supply_size[supply_temp.supply_type][“width”] * 0.85
supply_temp_top_y = supply_temp.y + supply_size[supply_temp.supply_type][“height”] * 0.4
supply_temp_bottom_y = supply_temp.y + supply_size[supply_temp.supply_type][“height”] * 0.9
if supply_temp_left_x > self.x + 0.05 * width and supply_temp_right_x < self.x + 0.95 * width and supply_temp_top_y < self.y + 0.95 * height and supply_temp_bottom_y > self.y + 0.1 * height:
if supply_temp.supply_type == 0: # 0為血量補給,吃到血量補給
self.HP -= supply_temp.supply_HP # 血量-(-3)
if self.HP > 41: # 血量最大值為41
self.HP = 41
show_score_HP()
else: # 吃到彈藥補給
self.is_three_bullet = True
self.three_bullet_stock += 20 # 三管炮彈余量+20
del_supply(supply_temp)
?
2)游戲的邏輯部分
函數(shù)def del_outWindow_bullet(plane):` `"""刪除plane的越界子彈"""` `bullet_list_out = [] # 越界子彈` `for bullet in plane.bullet_list:` `bullet.display()` `bullet.move()` `if bullet.judge(): # 判斷子彈是否越界` `bullet_list_out.append(bullet)` `# 刪除越界子彈` `if bullet_list_out:` `for bullet in bullet_list_out:` `plane.bullet_list.remove(bullet)` `# 如果為hero并且為三管齊發(fā)則判斷炮管23的子彈是否越界` `if plane.plane_type == 3 and (plane.barrel_2 or plane.barrel_3):` `barrel2_bullet_out = [] # 越界子彈` `barrel3_bullet_out = [] # 越界子彈` `# 判斷炮管2` `for bullet in plane.barrel_2:` `bullet.display()` `bullet.move()` `if bullet.judge(): # 判斷子彈是否越界` `barrel2_bullet_out.append(bullet)` `# 刪除越界子彈` `if barrel2_bullet_out:` `for bullet in barrel2_bullet_out:` `plane.barrel_2.remove(bullet)` `# 判斷炮管3` `for bullet in plane.barrel_3:` `bullet.display()` `bullet.move()` `if bullet.judge(): # 判斷子彈是否越界` `barrel3_bullet_out.append(bullet)` `# 刪除越界子彈` `if barrel3_bullet_out:` `for bullet in barrel3_bullet_out:` `plane.barrel_3.remove(bullet)` `def del_plane(plane):` `"""回收被擊中的敵機的對象"""` `global hero` `global hit_score` `global enemy0_list` `global enemy1_list` `global enemy2_list` `if plane in enemy0_list: # 回收對象為enemy0` `enemy0_list.remove(plane)` `elif plane in enemy1_list:` `enemy1_list.remove(plane)` `elif plane in enemy2_list:` `enemy2_list.remove(plane)` `elif plane == hero: # 回收對象為hero` `hit_score = 0` `show_score_HP()` `hero = None` `def del_supply(supply):` `"""回收補給"""` `global blood_supply` `global bullet_supply` `if supply == blood_supply: # 回收對象為血量補給` `blood_supply = None` `elif supply == bullet_supply:` `bullet_supply = None` `def reborn():` `"""Hero重生"""` `global hero` `global window_screen` `global hit_score` `hero = HeroPlane(window_screen)` `show_score_HP()` `hit_score = 0` `# 將最高分寫入到文件def max_score_2_file(): global hit_score file = None try: file = open(“./飛機大戰(zhàn)得分榜.txt”, ‘r+’) except Exception: file = open(“./飛機大戰(zhàn)得分榜.txt”, ‘w+’) finally: if file.read(): # 判斷文件是否為空 file.seek(0, 0) # 定位到文件開頭 file_score = eval(file.read()) if hit_score > file_score: file.seek(0, 0) # 定位到文件開頭 file.truncate() # 清空文件內容 file.write(str(hit_score)) else: file.write(str(hit_score)) file.close() def create_enemy_plane(): “”“生成敵機”“” global window_screen global hit_score global enemy0_list global enemy0_maximum global enemy1_list global enemy1_maximum global enemy2_list global enemy2_maximum global HP_list if hit_score < 40: random_num = random.randint(1, 70) HP_list = [1, 20, 100, 20] elif hit_score < 450: random_num = random.randint(1, 60) HP_list = [1, 20, 120, 20] elif hit_score < 650: random_num = random.randint(1, 60) HP_list = [1, 30, 140, 20] elif hit_score < 850: random_num = random.randint(1, 55) HP_list = [2, 36, 160, 20] else: random_num = random.randint(1, 50) HP_list = [2, 40, 180, 20] random_appear_boss1 = random.randint(18, 28) random_appear_boss2 = random.randint(80, 100) # enemy0 if (random_num == 20 or random == 40) and len(enemy0_list) < enemy0_maximum: enemy0_list.append(Enemy0Plane(window_screen)) # enemy1 if (hit_score >= random_appear_boss1 and (hit_score % random_appear_boss1) == 0) and len( enemy1_list) < enemy1_maximum: enemy1_list.append(Enemy1Plane(window_screen)) # enemy2 if (hit_score >= random_appear_boss2 and (hit_score % random_appear_boss2) == 0) and len( enemy2_list) < enemy2_maximum: enemy2_list.append(Enemy2Plane(window_screen))
` `
上面這一堆代碼其實就是干下面幾個事情:
-
先繪制出背景幕布
-
再繪制出玩家的戰(zhàn)機,敵機
-
綁定戰(zhàn)機和敵機的鼠標和鍵盤響應事件
-
發(fā)射子彈,通過坐標來判斷子彈和敵機的碰撞,以及敵機和玩家戰(zhàn)機的碰撞
-
最后還要計算得分
點擊下方安全鏈接前往獲取
CSDN大禮包:《Python入門&進階學習資源包》免費分享文章來源:http://www.zghlxwxcb.cn/news/detail-851354.html
??Python實戰(zhàn)案例??
光學理論是沒用的,要學會跟著一起敲,要動手實操,才能將自己的所學運用到實際當中去,這時候可以搞點實戰(zhàn)案例來學習。
??Python書籍和視頻合集??
觀看零基礎學習視頻,看視頻學習是最快捷也是最有效果的方式,跟著視頻中老師的思路,從基礎到深入,還是很容易入門的。
??Python副業(yè)創(chuàng)收路線??
這些資料都是非常不錯的,朋友們如果有需要《Python學習路線&學習資料》,點擊下方安全鏈接前往獲取
CSDN大禮包:《Python入門&進階學習資源包》免費分享
本文轉自網(wǎng)絡,如有侵權,請聯(lián)系刪除。文章來源地址http://www.zghlxwxcb.cn/news/detail-851354.html
到了這里,關于用Python開發(fā)一個飛機大戰(zhàn)游戲(附源碼教程)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!