本博客使用了Pygame庫(kù)來(lái)創(chuàng)建游戲窗口和處理游戲邏輯。
目錄
一、代碼的詳細(xì)解釋:
創(chuàng)建游戲窗口:
蜜蜂的定義與循環(huán)出現(xiàn):
顯示蜜蜂和處理碰撞:
定義射擊器:
子彈的定義與處理碰撞:
計(jì)算兩點(diǎn)間距離的函數(shù):
播放背景音樂(lè):
主游戲循環(huán):
二、完整代碼展示:
三、視頻演示:
四、Gitee倉(cāng)庫(kù)地址
一、代碼的詳細(xì)解釋: ?
創(chuàng)建游戲窗口:
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bee")
創(chuàng)建了一個(gè)名為"Bee"的游戲窗口,窗口的大小由WIDTH
和HEIGHT
變量決定。
蜜蜂的定義與循環(huán)出現(xiàn):
class Enemy():
# 構(gòu)造函數(shù)
def __init__(self):
self.img = pygame.image.load('bee.png')
self.x = random.randint(200, 600)
self.y = random.randint(50, 250)
self.step = random.randint(2, 6)
# 重置蜜蜂位置
def reset(self):
self.x = random.randint(200, 600)
self.y = random.randint(50, 200)
enemies = []
for i in range(number_of_bee):
enemies.append(Enemy())
定義了一個(gè)名為Enemy
的類,每個(gè)蜜蜂對(duì)象有圖像、x坐標(biāo)、y坐標(biāo)和步長(zhǎng)。蜜蜂的循環(huán)出現(xiàn)在enemies
列表中,初始位置隨機(jī)。
顯示蜜蜂和處理碰撞:
def show_bee():
for e in enemies:
screen.blit(e.img, (e.x, e.y))
e.x += e.step
if e.x > 736 or e.x < 0:
e.step *= -1
e.y += 40
if e.y >= 450:
over, over_rect = init_item('game over.jpg', 0, 0)
txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32)
screen.blit(over, over_rect) ##顯示gameover圖片
screen.blit(txt_restart, txt_restart_rect)
quit()
這個(gè)函數(shù)用于顯示蜜蜂,并在蜜蜂到達(dá)窗口邊緣時(shí),讓其改變方向并向下移動(dòng)。如果蜜蜂的y坐標(biāo)超過(guò)了450,則游戲結(jié)束,顯示"game over"圖片和"Restart"文字,然后退出游戲。
定義射擊器:
play_x = 400
play_y = 500
shoot, shoot_rect = init_item('fighter.png', play_x, play_y)
playerstep = 0
定義了射擊器的初始位置,并加載了射擊器的圖像。
子彈的定義與處理碰撞:
class bullet():
def __init__(self):
self.img = pygame.image.load('bullet1.png')
self.x = play_x
self.y = play_y + 10
self.step = 10 # 子彈移動(dòng)的速度
def hit(self):
for e in enemies:
if distance(self.x, self.y, e.x, e.y) < 30:
bullets.remove(self)
e.reset()
bullets = []
def show_bullets():
for b in bullets:
screen.blit(b.img, (b.x, b.y))
b.hit()
b.y -= b.step
if b.y < 0:
bullets.remove(b)
這段代碼定義了bullet
類,每個(gè)子彈對(duì)象有圖像、x坐標(biāo)、y坐標(biāo)和速度。在子彈的hit()
方法中,檢查子彈與蜜蜂是否碰撞,若是,則移除該子彈并重新生成蜜蜂。show_bullets()
函數(shù)用于顯示子彈,并在子彈超出窗口時(shí)移除它們。
計(jì)算兩點(diǎn)間距離的函數(shù):
def distance(bx, by, ex, ey):
a = bx - ex
b = by - ey
return math.sqrt(a * a + b * b)
這個(gè)函數(shù)用于計(jì)算兩點(diǎn)之間的距離,其中bx
和by
表示子彈的坐標(biāo),ex
和ey
表示蜜蜂的坐標(biāo)。
播放背景音樂(lè):
pygame.mixer.music.load('背景音樂(lè).mp3') # 導(dǎo)入音樂(lè)
pygame.mixer.music.play(loops=-1) # 循環(huán)播放
這段代碼加載名為"背景音樂(lè).mp3"的音樂(lè),并設(shè)置為循環(huán)播放。
主游戲循環(huán):
clock = pygame.time.Clock() ##用來(lái)設(shè)定窗口的刷新頻率
while True:
clock.tick(60) ##每秒執(zhí)行60次
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
playerstep = 5
elif event.key == pygame.K_LEFT:
playerstep = -5
elif event.key == pygame.K_SPACE:
bullets.append(bullet())
if event.type == pygame.KEYUP:
playerstep = 0
screen.blit(shoot, (play_x, play_y))
play_x += playerstep
if play_x > 736:
play_x = 736
if play_x < 0:
play_x = 0
show_bee()
show_bullets()
pygame.display.flip()
這是游戲的主循環(huán),游戲會(huì)在每次循環(huán)中執(zhí)行以下步驟:
最后,游戲會(huì)在主循環(huán)中不斷重復(fù)執(zhí)行以上步驟,實(shí)現(xiàn)了蜜蜂的循環(huán)出現(xiàn)、射擊器的控制以及子彈和蜜蜂之間的碰撞檢測(cè)。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-719301.html
- 設(shè)置窗口刷新頻率為60幀。
- 填充窗口背景為黑色。
- 處理事件,包括按鍵事件和退出事件。
- 根據(jù)按鍵事件移動(dòng)射擊器的位置,如果按下空格鍵,則添加一個(gè)新的子彈對(duì)象到
bullets
列表。 - 顯示射擊器的圖像,根據(jù)按鍵事件移動(dòng)射擊器的位置,使其在窗口內(nèi)左右移動(dòng),并限制其不超出窗口邊界。
- 調(diào)用
show_bee()
函數(shù),顯示蜜蜂,并處理蜜蜂與窗口邊界的碰撞,以及蜜蜂與子彈的碰撞。 - 調(diào)用
show_bullets()
函數(shù),顯示子彈,并處理子彈與窗口邊界的碰撞,以及子彈與蜜蜂的碰撞。 - 使用
pygame.display.flip()
方法更新整個(gè)游戲窗口。
二、完整代碼展示:
import pygame import sys import random import math WIDTH = 800 HEIGHT = 600 def pygame_1(): global event, e pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Bee") ##蜜蜂: number_of_bee = 6 ##顯示分?jǐn)?shù) txt_score, txt_score_rect = show_text("Score:0", 40, 20, 20) score = 0 ##蜜蜂的循環(huán)出現(xiàn) class Enemy(): def __init__(self): self.img = pygame.image.load('bee.png') self.x = random.randint(200, 600) self.y = random.randint(50, 250) self.step = random.randint(2, 6) def reset(self): self.x = random.randint(200, 600) self.y = random.randint(50, 200) enemies = [] for i in range(number_of_bee): enemies.append(Enemy()) def show_bee(): for e in enemies: screen.blit(e.img, (e.x, e.y)) e.x += e.step if e.x > 736 or e.x < 0: e.step *= -1 e.y += 40 if e.y >= 450: over, over_rect = init_item('game over.jpg', 0, 0) txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32) screen.blit(over, over_rect) ##顯示gameover圖片 screen.blit(txt_restart, txt_restart_rect) quit() ##射擊器 play_x = 400 play_y = 500 shoot, shoot_rect = init_item('fighter.png', play_x, play_y) playerstep = 0 ##子彈 class bullet(): def __init__(self): self.img = pygame.image.load('bullet1.png') self.x = play_x self.y = play_y + 10 self.step = 10 # 子彈移動(dòng)的速度 def hit(self): for e in enemies: if distance(self.x, self.y, e.x, e.y) < 30: bullets.remove(self) e.reset() bullets = [] def show_bullets(): for b in bullets: screen.blit(b.img, (b.x, b.y)) b.hit() b.y -= b.step if b.y < 0: bullets.remove(b) def distance(bx, by, ex, ey): a = bx - ex b = by - ey return math.sqrt(a * a + b * b) pygame.mixer.music.load('背景音樂(lè).mp3') # 導(dǎo)入音樂(lè) pygame.mixer.music.play(loops=-1) # 循環(huán)播放 clock = pygame.time.Clock() ##用來(lái)設(shè)定窗口的刷新頻率 while True: clock.tick(60) ##每秒執(zhí)行60次 screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: playerstep = 5 elif event.key == pygame.K_LEFT: playerstep = -5 elif event.key == pygame.K_SPACE: bullets.append(bullet()) if event.type == pygame.KEYUP: playerstep = 0 screen.blit(shoot, (play_x, play_y)) play_x += playerstep if play_x > 736: play_x = 736 if play_x < 0: play_x = 0 show_bee() show_bullets() pygame.display.flip() def init_item(img_path, pos_x, pos_y): ##顯示圖片 item = pygame.image.load(img_path) item_rect = pygame.Rect((pos_x, pos_y, 0, 0)) item_rect.size = item.get_size() return item, item_rect def show_text(txt, pos_x, pos_y, fontsize=12): ##設(shè)定顯示文本信息 font = pygame.font.Font(None, fontsize) text = font.render(txt, True, (255, 0, 0)) text_rect = text.get_rect() text_rect.centerx = pos_x text_rect.centery = pos_y return text, text_rect if __name__ == "__main__": pygame_1()
三、視頻演示: ?
用python做小游戲——以射擊游戲?yàn)槔?span toymoban-style="hidden">文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-719301.html
四、Gitee倉(cāng)庫(kù)地址
- Jiamei Fu/PythonWork - 碼云 - 開源中國(guó) (gitee.com)
到了這里,關(guān)于用python做小游戲——以射擊游戲?yàn)槔奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!