创新的外星人突击游戏
最编程
2024-07-29 08:56:59
...
import sys
from time import sleep
import pygame
from settings import Settings
from game_starts import GameStats
from scoreboard import Scoreboard
from button import Button
from ship import Ship
from bullet import Bullet
from aileen import Aileen
class AileenInvasion:
"""Overall class to manage game assets and behavior.整体类来管理游戏资产和行为"""
def __init__(self):#初始化
"""Initialize the game, and create game resources."""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height
# self.screen = pygame.display.set_mode(
# (self.settings.screen_width,self.settings.screen_height))
#类中变量前有self,说明该变量绑定在当前实例化本身
pygame.display.set_caption("Aileen Invasion")
# Creation an instance to store game statistics.
self.stats = GameStats(self)
# Create an instance to store game statics,
# and create a scoreboard.
self.sb = Scoreboard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()#Group可以批量使用的函数
self.aileens = pygame.sprite.Group()
self._create_fleet()
#Make the play button.
self.play_button = Button(self,"Play")
self.bg_color =(0,0,225) #代表红 绿 蓝 三颜色
# def _create_fleet(self):
# """Create the fleet of aileens."""
# #Make a aileen
# aileen = Aileen(self)
# self.aileens.add(aileen)
# #set the background color.
def run_game(self): #功能:1监听事件,2处理事件,3更新屏幕事件
"""Start the main loop for the game."""
while True:
# 1监听事件函数--监听和处理用户的行为
self._check_events()#将监听事件(封装)外包给这个函数,减轻run_game的工作量---这个过程叫重构(refactory)
if self.stats.game_active:
# 2处理事件函数
self.ship.update()
#更新子弹
self._update_bullets()
self._update_aileens()
# 3 屏幕更新函数
self._update_screen()
def _update_bullets(self):
self.bullets.update()
if not self.aileens:
# Destory existing bullets and create new fleet
self.bullets.empty()
self._create_fleet()
# Get rid of the bullets that have disappeared.
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_aileen_collisions()
def _check_bullet_aileen_collisions(self):
"""Respond to bullet-aileen collisions."""
""" Remove any bullets and aileens that have collided """
#????
collisions = pygame.sprite.groupcollide(
self.bullets, self.aileens,True,True)
if collisions: #collision是字典类型变量
# for aileens in collisions.values():
self.stats.score += self.settings.aileen_points #* len(aileens)
for aileens in collisions.values():
self.stats.score += self.settings.aileen_points * len(aileens)
self.sb.prep_score()
self.sb.check_high_score()
self.sb.prep_high_score()
if not self.aileens:
# Destory existing bullets and create new fleet.
self.bullets.empty()
self._create_fleet()
self.settings.increase_speed()
# Increase level
self.stats.level += 1
self.sb.prep_level()
# print(len(self.bullets))
# Watch for keyboard and mouse events. 监听用户在做什么操作--这里设置游戏菜单栏
def _check_events(self): #
#--snip--
"""Respond to keypress and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
self._check_play_button(mouse_pos)
def _check_play_button(self,mouse_pos):
"""Start a new game when the player clicks Play."""
button_clicked = self.play_button.rect.collidepoint(mouse_pos)
if button_clicked and not self.stats.game_active:
# Hide the mouse cursor.
pygame.mouse.set_visible(False)
# Reset the game statistics.
self.stats.reset_stats()
self.stats.game_active = True
# 确保分数清0
self.sb.prep_score()
self.sb.prep_level()
self.sb.prep_ships()
# Get rid of any remaining aileens and bullets.
self.aileens.empty()
self.bullets.empty()
#Create A new fleet and center the ship.
self._create_fleet()
self.ship.center_ship()
#Reset the game settings.
self.settings.initialize_dynamic_settings()
pygame.mixer.init()
pygame.mixer.music.load("music/香香 - 猪之歌.mp3")
# pygame.mixer.music.set_volume(2)
pygame.mixer.music.play()
def _check_keydown_events(self,event):
"""Respond to keypress"""
#判断右键
if event.key == pygame.K_RIGHT:
#处理右键
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_UP:
self.ship.moving_up = True
elif event.key == pygame.K_DOWN:
self.ship.moving_down = True
elif event.key == pygame.K_q:#按q键退出游戏
sys.exit()
elif event.key == pygame.K_SPACE:
self._fire_bullet()
def _check_keyup_events(self,event):
"""Respond to key release."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
# Move the ship to the right.
self.ship.rect.x += 1
elif event.key == pygame.K_m:
self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
self.settings.screen_width =self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height
self.ship = Ship(self)
self.aliens = pygame.sprite.Group()
self._create_fleet()
elif event.key == pygame.K_n:
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
self.ship = Ship(self)
self.aliens = pygame.sprite.Group()
self._create_fleet()
elif event.key == pygame.K_UP:
self.ship.moving_up = False
elif event.key == pygame.K_DOWN:
self.ship.moving_down = False
def _fire_bullet(self):
"""create a new bullet and add it to the bullets group."""
if len(self.bullets) < self.settings.bullets_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _create_fleet(self):#self传的也是ai
"""Create the fleet of aileens."""
#Create an aileen and find the number of aileens in a row
#Spacing between each aileen is equal to one aileen width.
aileen = Aileen(self)
aileen_width, aileen_height = aileen.rect.size
available_space_x = self.settings.screen_width - (2 * aileen_width)
print(available_space_x)
print(self.settings.screen_width)
print(2 * aileen_width)
number_aileen_x = available_space_x // (2 * aileen_width)
# Determine the number of rows of aileens that fit on the screen.
ship_height =self.ship.rect.height
available_space_y = (self.settings.screen_height -
(3 * aileen_height) - ship_height)
number_rows = available_space_y // (2 * aileen_height)
#Create the first row of aileens.
for row_number in range(number_rows):
for aileen_number in range(number_aileen_x):
self._create_aileen(aileen_number, row_number)
def _create_aileen(self,aileen_number, row_number):
# Create an aileen and place it in row.
# Make a aileen
aileen = Aileen(self)
aileen_width, aileen_height =aileen.rect.size
aileen.x = aileen_width + 2 * aileen_width * aileen_number
aileen.rect.x = aileen.x
aileen.rect.y = aileen.rect.height + 2 * aileen.rect.height * row_number
self.aileens.add(aileen)
def _check_aileens_bottom(self):
"""Check if any aileens have reached the bottom of the screen."""
screen_rect = self.screen.get_rect()
for aileen in self.aileens.sprites():
if aileen.rect.bottom >= screen_rect.bottom:
#Treat this the same as if the ship got hit.
self._ship_hit()
break
# Redraw the screen during each pass through the loop. 更新画布颜色
def _update_aileens(self):
"""
Check if the fleet is at an edge,
then update the positions of all aliens in the fleet.
"""
self._check_fleet_edges()
"""Update the positions of all aileens in the fleet."""
self.aileens.update()
# Look for aileen-ship collisions.
if pygame.sprite.spritecollideany(self.ship, self.aileens):
self._ship_hit()
print("Ship hit!!!")
# Look for aileens hitting the bottom of the screen
self._check_aileens_bottom()
def _check_fleet_edges(self):
"""Respond appropriately if any aileens have reached an edge."""
for aileen in self.aileens.sprites():
if aileen.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
"""Drop the entire fleet and change the fleet's direction."""
for aileen in self.aileens.sprites():
aileen.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_direction *= -1
def _ship_hit(self):
"""Respond to the ship being hit by an allien"""
if self.stats.ships_left > 0:
# Decrement ships_left.and update scoreboard
self.stats.ships_left -= 1
self.sb.prep_ships()
# Get rid of any remaining aileens and bullets.
self.aileens.empty()
self.bullets.empty()
# Create a new fleet and center the ship.
self._create_fleet()
self.ship.center_ship()
# Pause
sleep(0.5)
else:
self.stats.game_active = False
pygame.mouse.set_visible(True)
def _update_screen(self):
"""Update images on the screen , and flip to the new screen"""
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aileens.draw(self.screen)
#Draw the score information.
self.sb.show_score()
# Draw the play button if the games is inactive.
if not self.stats.game_active:
self.play_button.draw_button()
self.bullets.draw(self.screen)
pygame.display.flip()
def check_high_score(self):
"""Check to see if there's a new high score."""
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
if __name__ == '__main__':
# Make a game instance , and run the game.
ai = AileenInvasion()#游戏本身的实例化,ai就是那个AileenInvasion
ai.run_game()
上一篇: 国内常用镜像资源仓库网址集锦
下一篇: 《皇室战争》体验报告:游戏时长被无限拉长
推荐阅读
-
创新玩法,体验不一样的24点游戏
-
创新的外星人突击游戏
-
FIFA 20》传承版:需要微创新的三幻神级游戏
-
技术峰会|58同城陆盛华、黄硕凯受邀参加WOT全球技术创新大会--个人介绍: 现任58集团汽车事业群技术总监,人人车技术负责人,58集团技术委员会委员。拥有多年研发、架构和管理经验,曾从事大型办公软件、游戏、二手车交易平台等研发和管理工作。2016年加入人人车,推动了人人车业务架构和基础设施的演进和发展,实现了人人车平台化服务、自研中间件、容器化平台等从0到1的建设。
-
深入分析:Freedroid RPG 游戏引擎的技术创新与应用场景
-
快速了解《卡拉特协议》:旨在好莱坞,开创游戏、娱乐和人工智能创新的新时代
-
玩出新花样!结合吃豆人与切水果的创新小游戏,用Pygame实现,超神奇,源代码奉上
-
创建一个创新的网络游戏平台,整合音乐搜索与视频在线观看功能
-
常征老师的畅销书《火药改变世界》(简称‘火药说’)解析科技迷思,寻找游戏界的合作伙伴" 常征老师在《火药说》中深入探讨了"李约瑟之谜",即为何中国未能引领工业和科学革命。实际上,这本书透过讲述欧美七百年的科技创新历程,为中华文明的原创力量提供了科技实证和哲学启示,其视角超越纯粹的科技史范畴。 常征提到,《文明》这款广受欢迎的游戏以其宏大的综合性历史叙事为特色,兼具高雅性、启发性和教育性,远离低俗。同样,《火药说》也为读者呈现了一个包含丰富细节的综合性大历史线索,内容高尚且富有启发,适宜寻求游戏制作公司的合作,共同打造高质量的文化产品。 在近期的交流中,我们有幸采访到《火药改变世界》的作者常征老师,他的深度提问精神和对第一性原理的推崇,如混沌大学李善友、张首晟以及特斯拉的马斯克所倡导的,无疑将对我们产生深远影响。持续这样的思维训练,必能带来巨大的成长和收益。 CIDA编辑按此分享。
-
玩转《我的世界》,轻松收获大学文凭:游戏与学术的创新结合