当前位置:   article > 正文

8个Python小游戏,可以上班摸鱼玩一天

python小游戏

1、吃金币

源码分享:

  1. import os
  2. import cfg
  3. import sys
  4. import pygame
  5. import random
  6. from modules import *
  7.  
  8.  
  9. '''游戏初始化'''
  10. def initGame():
  11.     # 初始化pygame, 设置展示窗口
  12.     pygame.init()
  13.     screen = pygame.display.set_mode(cfg.SCREENSIZE)
  14.     pygame.display.set_caption('catch coins —— 九歌')
  15.     # 加载必要的游戏素材
  16.     game_images = {}
  17.     for keyvalue in cfg.IMAGE_PATHS.items():
  18.         if isinstance(value, list):
  19.             images = []
  20.             for item in value: images.append(pygame.image.load(item))
  21.             game_images[key= images
  22.         else:
  23.             game_images[key= pygame.image.load(value)
  24.     game_sounds = {}
  25.     for keyvalue in cfg.AUDIO_PATHS.items():
  26.         if key == 'bgm'continue
  27.         game_sounds[key= pygame.mixer.Sound(value)
  28.     # 返回初始化数据
  29.     return screen, game_images, game_sounds
  30.  
  31.  
  32. '''主函数'''
  33. def main():
  34.     # 初始化
  35.     screen, game_images, game_sounds = initGame()
  36.     # 播放背景音乐
  37.     pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
  38.     pygame.mixer.music.play(-10.0)
  39.     # 字体加载
  40.     font = pygame.font.Font(cfg.FONT_PATH, 40)
  41.     # 定义hero
  42.     hero = Hero(game_images['hero'], position=(375520))
  43.     # 定义食物组
  44.     food_sprites_group = pygame.sprite.Group()
  45.     generate_food_freq = random.randint(1020)
  46.     generate_food_count = 0
  47.     # 当前分数/历史最高分
  48.     score = 0
  49.     highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
  50.     # 游戏主循环
  51.     clock = pygame.time.Clock()
  52.     while True:
  53.         # --填充背景
  54.         screen.fill(0)
  55.         screen.blit(game_images['background'], (00))
  56.         # --倒计时信息
  57.         countdown_text = 'Count down: ' + str((90000 - pygame.time.get_ticks()) // 60000+ ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)
  58.         countdown_text = font.render(countdown_text, True, (000))
  59.         countdown_rect = countdown_text.get_rect()
  60.         countdown_rect.topright = [cfg.SCREENSIZE[0]-305]
  61.         screen.blit(countdown_text, countdown_rect)
  62.         # --按键检测
  63.         for event in pygame.event.get():
  64.             if event.type == pygame.QUIT:
  65.                 pygame.quit()
  66.                 sys.exit()
  67.         key_pressed = pygame.key.get_pressed()
  68.         if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
  69.             hero.move(cfg.SCREENSIZE, 'left')
  70.         if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
  71.             hero.move(cfg.SCREENSIZE, 'right')
  72.         # --随机生成食物
  73.         generate_food_count += 1
  74.         if generate_food_count > generate_food_freq:
  75.             generate_food_freq = random.randint(1020)
  76.             generate_food_count = 0
  77.             food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)
  78.             food_sprites_group.add(food)
  79.         # --更新食物
  80.         for food in food_sprites_group:
  81.             if food.update(): food_sprites_group.remove(food)
  82.         # --碰撞检测
  83.         for food in food_sprites_group:
  84.             if pygame.sprite.collide_mask(food, hero):
  85.                 game_sounds['get'].play()
  86.                 food_sprites_group.remove(food)
  87.                 score += food.score
  88.                 if score > highest_score: highest_score = score
  89.         # --画hero
  90.         hero.draw(screen)
  91.         # --画食物
  92.         food_sprites_group.draw(screen)
  93.         # --显示得分
  94.         score_text = f'Score: {score}, Highest: {highest_score}'
  95.         score_text = font.render(score_text, True, (000))
  96.         score_rect = score_text.get_rect()
  97.         score_rect.topleft = [55]
  98.         screen.blit(score_text, score_rect)
  99.         # --判断游戏是否结束
  100.         if pygame.time.get_ticks() >= 90000:
  101.             break
  102.         # --更新屏幕
  103.         pygame.display.flip()
  104.         clock.tick(cfg.FPS)
  105.     # 游戏结束, 记录最高分并显示游戏结束画面
  106.     fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
  107.     fp.write(str(highest_score))
  108.     fp.close()
  109.     return showEndGameInterface(screen, cfg, score, highest_score)
  110.  
  111.  
  112. '''run'''
  113. if __name__ == '__main__':
  114.     while main():
  115.         pass

2、打乒乓

源码分享:

  1.  
  2. import sys
  3. import cfg
  4. import pygame
  5. from modules import *
  6.  
  7.  
  8. '''定义按钮'''
  9. def Button(screen, position, text, button_size=(20050)):
  10.     lefttop = position
  11.     bwidth, bheight = button_size
  12.     pygame.draw.line(screen, (150150150), (lefttop), (left+bwidth, top), 5)
  13.     pygame.draw.line(screen, (150150150), (lefttop-2), (lefttop+bheight), 5)
  14.     pygame.draw.line(screen, (505050), (lefttop+bheight), (left+bwidth, top+bheight), 5)
  15.     pygame.draw.line(screen, (505050), (left+bwidth, top+bheight), (left+bwidth, top), 5)
  16.     pygame.draw.rect(screen, (100100100), (lefttop, bwidth, bheight))
  17.     font = pygame.font.Font(cfg.FONTPATH, 30)
  18.     text_render = font.render(text, 1, (255235205))
  19.     return screen.blit(text_render, (left+50top+10))
  20.  
  21.  
  22. '''
  23. Function:
  24.     开始界面
  25. Input:
  26.     --screen: 游戏界面
  27. Return:
  28.     --game_mode: 1(单人模式)/2(双人模式)
  29. '''
  30. def startInterface(screen):
  31.     clock = pygame.time.Clock()
  32.     while True:
  33.         screen.fill((413633))
  34.         button_1 = Button(screen, (150175), '1 Player')
  35.         button_2 = Button(screen, (150275), '2 Player')
  36.         for event in pygame.event.get():
  37.             if event.type == pygame.QUIT:
  38.                 pygame.quit()
  39.                 sys.exit()
  40.             if event.type == pygame.MOUSEBUTTONDOWN:
  41.                 if button_1.collidepoint(pygame.mouse.get_pos()):
  42.                     return 1
  43.                 elif button_2.collidepoint(pygame.mouse.get_pos()):
  44.                     return 2
  45.         clock.tick(10)
  46.         pygame.display.update()
  47.  
  48.  
  49. '''结束界面'''
  50. def endInterface(screen, score_left, score_right):
  51.     clock = pygame.time.Clock()
  52.     font1 = pygame.font.Font(cfg.FONTPATH, 30)
  53.     font2 = pygame.font.Font(cfg.FONTPATH, 20)
  54.     msg = 'Player on left won!' if score_left > score_right else 'Player on right won!'
  55.     texts = [font1.render(msg, True, cfg.WHITE),
  56.             font2.render('Press ESCAPE to quit.'True, cfg.WHITE),
  57.             font2.render('Press ENTER to continue or play again.'True, cfg.WHITE)]
  58.     positions = [[120200], [155270], [80300]]
  59.     while True:
  60.         screen.fill((413633))
  61.         for event in pygame.event.get():
  62.             if event.type == pygame.QUIT:
  63.                 pygame.quit()
  64.                 sys.exit()
  65.             if event.type == pygame.KEYDOWN:
  66.                 if event.key == pygame.K_RETURN:
  67.                     return
  68.                 elif event.key == pygame.K_ESCAPE:
  69.                     sys.exit()
  70.                     pygame.quit()
  71.         for text, pos in zip(texts, positions):
  72.             screen.blit(text, pos)
  73.         clock.tick(10)
  74.         pygame.display.update()
  75.  
  76.  
  77. '''运行游戏Demo'''
  78. def runDemo(screen):
  79.     # 加载游戏素材
  80.     hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
  81.     goal_sound = pygame.mixer.Sound(cfg.GOALSOUNDPATH)
  82.     pygame.mixer.music.load(cfg.BGMPATH)
  83.     pygame.mixer.music.play(-10.0)
  84.     font = pygame.font.Font(cfg.FONTPATH, 50)
  85.     # 开始界面
  86.     game_mode = startInterface(screen)
  87.     # 游戏主循环
  88.     # --左边球拍(ws控制, 仅双人模式时可控制)
  89.     score_left = 0
  90.     racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)
  91.     # --右边球拍(↑↓控制)
  92.     score_right = 0
  93.     racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)
  94.     # --球
  95.     ball = Ball(cfg.BALLPICPATH, cfg)
  96.     clock = pygame.time.Clock()
  97.     while True:
  98.         for event in pygame.event.get():
  99.             if event.type == pygame.QUIT:
  100.                 pygame.quit()
  101.                 sys.exit(-1)
  102.         screen.fill((413633))
  103.         # 玩家操作
  104.         pressed_keys = pygame.key.get_pressed()
  105.         if pressed_keys[pygame.K_UP]:
  106.             racket_right.move('UP')
  107.         elif pressed_keys[pygame.K_DOWN]:
  108.             racket_right.move('DOWN')
  109.         if game_mode == 2:
  110.             if pressed_keys[pygame.K_w]:
  111.                 racket_left.move('UP')
  112.             elif pressed_keys[pygame.K_s]:
  113.                 racket_left.move('DOWN')
  114.         else:
  115.             racket_left.automove(ball)
  116.         # 球运动
  117.         scores = ball.move(ball, racket_left, racket_right, hit_sound, goal_sound)
  118.         score_left += scores[0]
  119.         score_right += scores[1]
  120.         # 显示
  121.         # --分隔线
  122.         pygame.draw.rect(screen, cfg.WHITE, (24706500))
  123.         # --球
  124.         ball.draw(screen)
  125.         # --拍
  126.         racket_left.draw(screen)
  127.         racket_right.draw(screen)
  128.         # --得分
  129.         screen.blit(font.render(str(score_left), False, cfg.WHITE), (15010))
  130.         screen.blit(font.render(str(score_right), False, cfg.WHITE), (30010))
  131.         if score_left == 11 or score_right == 11:
  132.             return score_left, score_right
  133.         clock.tick(100)
  134.         pygame.display.update()
  135.  
  136.  
  137. '''主函数'''
  138. def main():
  139.     # 初始化
  140.     pygame.init()
  141.     pygame.mixer.init()
  142.     screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
  143.     pygame.display.set_caption('pingpong —— 九歌')
  144.     # 开始游戏
  145.     while True:
  146.         score_left, score_right = runDemo(screen)
  147.         endInterface(screen, score_left, score_right)
  148.  
  149.  
  150. '''run'''
  151. if __name__ == '__main__':
  152.     main()

3、滑雪

源码分享: 

  1.  
  2. import sys
  3. import cfg
  4. import pygame
  5. import random
  6.  
  7.  
  8. '''滑雪者类'''
  9. class SkierClass(pygame.sprite.Sprite):
  10.     def __init__(self):
  11.         pygame.sprite.Sprite.__init__(self)
  12.         # 滑雪者的朝向(-22)
  13.         self.direction = 0
  14.         self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]
  15.         self.image = pygame.image.load(self.imagepaths[self.direction])
  16.         self.rect = self.image.get_rect()
  17.         self.rect.center = [320100]
  18.         self.speed = [self.direction, 6-abs(self.direction)*2]
  19.     '''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''
  20.     def turn(self, num):
  21.         self.direction += num
  22.         self.direction = max(-2self.direction)
  23.         self.direction = min(2self.direction)
  24.         center = self.rect.center
  25.         self.image = pygame.image.load(self.imagepaths[self.direction])
  26.         self.rect = self.image.get_rect()
  27.         self.rect.center = center
  28.         self.speed = [self.direction, 6-abs(self.direction)*2]
  29.         return self.speed
  30.     '''移动滑雪者'''
  31.     def move(self):
  32.         self.rect.centerx += self.speed[0]
  33.         self.rect.centerx = max(20self.rect.centerx)
  34.         self.rect.centerx = min(620self.rect.centerx)
  35.     '''设置为摔倒状态'''
  36.     def setFall(self):
  37.         self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
  38.     '''设置为站立状态'''
  39.     def setForward(self):
  40.         self.direction = 0
  41.         self.image = pygame.image.load(self.imagepaths[self.direction])
  42.  
  43.  
  44. '''
  45. Function:
  46.     障碍物类
  47. Input:
  48.     img_path: 障碍物图片路径
  49.     location: 障碍物位置
  50.     attribute: 障碍物类别属性
  51. '''
  52. class ObstacleClass(pygame.sprite.Sprite):
  53.     def __init__(self, img_path, location, attribute):
  54.         pygame.sprite.Sprite.__init__(self)
  55.         self.img_path = img_path
  56.         self.image = pygame.image.load(self.img_path)
  57.         self.location = location
  58.         self.rect = self.image.get_rect()
  59.         self.rect.center = self.location
  60.         self.attribute = attribute
  61.         self.passed = False
  62.     '''移动'''
  63.     def move(self, num):
  64.         self.rect.centery = self.location[1] - num
  65.  
  66.  
  67. '''创建障碍物'''
  68. def createObstacles(s, e, num=10):
  69.     obstacles = pygame.sprite.Group()
  70.     locations = []
  71.     for i in range(num):
  72.         row = random.randint(s, e)
  73.         col = random.randint(09)
  74.         location  = [col*64+20, row*64+20]
  75.         if location not in locations:
  76.             locations.append(location)
  77.             attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))
  78.             img_path = cfg.OBSTACLE_PATHS[attribute]
  79.             obstacle = ObstacleClass(img_path, location, attribute)
  80.             obstacles.add(obstacle)
  81.     return obstacles
  82.  
  83.  
  84. '''合并障碍物'''
  85. def AddObstacles(obstacles0, obstacles1):
  86.     obstacles = pygame.sprite.Group()
  87.     for obstacle in obstacles0:
  88.         obstacles.add(obstacle)
  89.     for obstacle in obstacles1:
  90.         obstacles.add(obstacle)
  91.     return obstacles
  92.  
  93.  
  94. '''显示游戏开始界面'''
  95. def ShowStartInterface(screen, screensize):
  96.     screen.fill((255255255))
  97.     tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)
  98.     cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)
  99.     title = tfont.render(u'滑雪游戏'True, (25500))
  100.     content = cfont.render(u'按任意键开始游戏'True, (00255))
  101.     trect = title.get_rect()
  102.     trect.midtop = (screensize[0]/2, screensize[1]/5)
  103.     crect = content.get_rect()
  104.     crect.midtop = (screensize[0]/2, screensize[1]/2)
  105.     screen.blit(title, trect)
  106.     screen.blit(content, crect)
  107.     while True:
  108.         for event in pygame.event.get():
  109.             if event.type == pygame.QUIT:
  110.                 pygame.quit()
  111.                 sys.exit()
  112.             elif event.type == pygame.KEYDOWN:
  113.                 return
  114.         pygame.display.update()
  115.  
  116.  
  117. '''显示分数'''
  118. def showScore(screen, score, pos=(1010)):
  119.     font = pygame.font.Font(cfg.FONTPATH, 30)
  120.     score_text = font.render("Score: %s" % score, True, (000))
  121.     screen.blit(score_text, pos)
  122.  
  123.  
  124. '''更新当前帧的游戏画面'''
  125. def updateFrame(screen, obstacles, skier, score):
  126.     screen.fill((255255255))
  127.     obstacles.draw(screen)
  128.     screen.blit(skier.image, skier.rect)
  129.     showScore(screen, score)
  130.     pygame.display.update()
  131.  
  132.  
  133. '''主程序'''
  134. def main():
  135.     # 游戏初始化
  136.     pygame.init()
  137.     pygame.mixer.init()
  138.     pygame.mixer.music.load(cfg.BGMPATH)
  139.     pygame.mixer.music.set_volume(0.4)
  140.     pygame.mixer.music.play(-1)
  141.     # 设置屏幕
  142.     screen = pygame.display.set_mode(cfg.SCREENSIZE)
  143.     pygame.display.set_caption('滑雪游戏 —— 九歌')
  144.     # 游戏开始界面
  145.     ShowStartInterface(screen, cfg.SCREENSIZE)
  146.     # 实例化游戏精灵
  147.     # --滑雪者
  148.     skier = SkierClass()
  149.     # --创建障碍物
  150.     obstacles0 = createObstacles(2029)
  151.     obstacles1 = createObstacles(1019)
  152.     obstaclesflag = 0
  153.     obstacles = AddObstacles(obstacles0, obstacles1)
  154.     # 游戏clock
  155.     clock = pygame.time.Clock()
  156.     # 记录滑雪的距离
  157.     distance = 0
  158.     # 记录当前的分数
  159.     score = 0
  160.     # 记录当前的速度
  161.     speed = [06]
  162.     # 游戏主循环
  163.     while True:
  164.         # --事件捕获
  165.         for event in pygame.event.get():
  166.             if event.type == pygame.QUIT:
  167.                 pygame.quit()
  168.                 sys.exit()
  169.             if event.type == pygame.KEYDOWN:
  170.                 if event.key == pygame.K_LEFT or event.key == pygame.K_a:
  171.                     speed = skier.turn(-1)
  172.                 elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
  173.                     speed = skier.turn(1)
  174.         # --更新当前游戏帧的数据
  175.         skier.move()
  176.         distance += speed[1]
  177.         if distance >= 640 and obstaclesflag == 0:
  178.             obstaclesflag = 1
  179.             obstacles0 = createObstacles(2029)
  180.             obstacles = AddObstacles(obstacles0, obstacles1)
  181.         if distance >= 1280 and obstaclesflag == 1:
  182.             obstaclesflag = 0
  183.             distance -= 1280
  184.             for obstacle in obstacles0:
  185.                 obstacle.location[1= obstacle.location[1] - 1280
  186.             obstacles1 = createObstacles(1019)
  187.             obstacles = AddObstacles(obstacles0, obstacles1)
  188.         for obstacle in obstacles:
  189.             obstacle.move(distance)
  190.         # --碰撞检测
  191.         hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)
  192.         if hitted_obstacles:
  193.             if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:
  194.                 score -= 50
  195.                 skier.setFall()
  196.                 updateFrame(screen, obstacles, skier, score)
  197.                 pygame.time.delay(1000)
  198.                 skier.setForward()
  199.                 speed = [06]
  200.                 hitted_obstacles[0].passed = True
  201.             elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:
  202.                 score += 10
  203.                 obstacles.remove(hitted_obstacles[0])
  204.         # --更新屏幕
  205.         updateFrame(screen, obstacles, skier, score)
  206.         clock.tick(cfg.FPS)
  207.  
  208.  
  209. '''run'''
  210. if __name__ == '__main__':
  211.     main();

4、并夕夕版飞机大战

源码分享:

  1.  
  2. import sys
  3. import cfg
  4. import pygame
  5. from modules import *
  6.  
  7.  
  8. '''游戏界面'''
  9. def GamingInterface(num_player, screen):
  10.     # 初始化
  11.     pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])
  12.     pygame.mixer.music.set_volume(0.4)
  13.     pygame.mixer.music.play(-1)
  14.     explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
  15.     fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
  16.     font = pygame.font.Font(cfg.FONTPATH, 20)
  17.     # 游戏背景图
  18.     bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']]
  19.     bg_move_dis = 0
  20.     bg_1 = pygame.image.load(bg_imgs[0]).convert()
  21.     bg_2 = pygame.image.load(bg_imgs[1]).convert()
  22.     bg_3 = pygame.image.load(bg_imgs[2]).convert()
  23.     # 玩家, 子弹和小行星精灵组
  24.     player_group = pygame.sprite.Group()
  25.     bullet_group = pygame.sprite.Group()
  26.     asteroid_group = pygame.sprite.Group()
  27.     # 产生小行星的时间间隔
  28.     asteroid_ticks = 90
  29.     for i in range(num_player):
  30.         player_group.add(Ship(i+1, cfg))
  31.     clock = pygame.time.Clock()
  32.     # 分数
  33.     score_1, score_2 = 00
  34.     # 游戏主循环
  35.     while True:
  36.         for event in pygame.event.get():
  37.             if event.type == pygame.QUIT:
  38.                 pygame.quit()
  39.                 sys.exit()
  40.         # --玩家一: ↑↓←→控制, j射击; 玩家二: wsad控制, 空格射击
  41.         pressed_keys = pygame.key.get_pressed()
  42.         for idx, player in enumerate(player_group):
  43.             direction = None
  44.             if idx == 0:
  45.                 if pressed_keys[pygame.K_UP]:
  46.                     direction = 'up'
  47.                 elif pressed_keys[pygame.K_DOWN]:
  48.                     direction = 'down'
  49.                 elif pressed_keys[pygame.K_LEFT]:
  50.                     direction = 'left'
  51.                 elif pressed_keys[pygame.K_RIGHT]:
  52.                     direction = 'right'
  53.                 if direction:
  54.                     player.move(direction)
  55.                 if pressed_keys[pygame.K_j]:
  56.                     if player.cooling_time == 0:
  57.                         fire_sound.play()
  58.                         bullet_group.add(player.shot())
  59.                         player.cooling_time = 20
  60.             elif idx == 1:
  61.                 if pressed_keys[pygame.K_w]:
  62.                     direction = 'up'
  63.                 elif pressed_keys[pygame.K_s]:
  64.                     direction = 'down'
  65.                 elif pressed_keys[pygame.K_a]:
  66.                     direction = 'left'
  67.                 elif pressed_keys[pygame.K_d]:
  68.                     direction = 'right'
  69.                 if direction:
  70.                     player.move(direction)
  71.                 if pressed_keys[pygame.K_SPACE]:
  72.                     if player.cooling_time == 0:
  73.                         fire_sound.play()
  74.                         bullet_group.add(player.shot())
  75.                         player.cooling_time = 20
  76.             if player.cooling_time > 0:
  77.                 player.cooling_time -= 1
  78.         if (score_1 + score_2< 500:
  79.             background = bg_1
  80.         elif (score_1 + score_2< 1500:
  81.             background = bg_2
  82.         else:
  83.             background = bg_3
  84.         # --向下移动背景图实现飞船向上移动的效果
  85.         screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
  86.         screen.blit(background, (0, bg_move_dis))
  87.         bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
  88.         # --生成小行星
  89.         if asteroid_ticks == 0:
  90.             asteroid_ticks = 90
  91.             asteroid_group.add(Asteroid(cfg))
  92.         else:
  93.             asteroid_ticks -= 1
  94.         # --画飞船
  95.         for player in player_group:
  96.             if pygame.sprite.spritecollide(player, asteroid_groupTrue, None):
  97.                 player.explode_step = 1
  98.                 explosion_sound.play()
  99.             elif player.explode_step > 0:
  100.                 if player.explode_step > 3:
  101.                     player_group.remove(player)
  102.                     if len(player_group== 0:
  103.                         return
  104.                 else:
  105.                     player.explode(screen)
  106.             else:
  107.                 player.draw(screen)
  108.         # --画子弹
  109.         for bullet in bullet_group:
  110.             bullet.move()
  111.             if pygame.sprite.spritecollide(bullet, asteroid_groupTrue, None):
  112.                 bullet_group.remove(bullet)
  113.                 if bullet.player_idx == 1:
  114.                     score_1 += 1
  115.                 else:
  116.                     score_2 += 1
  117.             else:
  118.                 bullet.draw(screen)
  119.         # --画小行星
  120.         for asteroid in asteroid_group:
  121.             asteroid.move()
  122.             asteroid.rotate()
  123.             asteroid.draw(screen)
  124.         # --显示分数
  125.         score_1_text = '玩家一得分: %s' % score_1
  126.         score_2_text = '玩家二得分: %s' % score_2
  127.         text_1 = font.render(score_1_text, True, (00255))
  128.         text_2 = font.render(score_2_text, True, (25500))
  129.         screen.blit(text_1, (25))
  130.         screen.blit(text_2, (235))
  131.         # --屏幕刷新
  132.         pygame.display.update()
  133.         clock.tick(60)
  134.  
  135.  
  136. '''主函数'''
  137. def main():
  138.     pygame.init()
  139.     pygame.font.init()
  140.     pygame.mixer.init()
  141.     screen = pygame.display.set_mode(cfg.SCREENSIZE)
  142.     pygame.display.set_caption('飞机大战 —— 九歌')
  143.     num_player = StartInterface(screen, cfg)
  144.     if num_player == 1:
  145.         while True:
  146.             GamingInterface(num_player=1screen=screen)
  147.             EndInterface(screen, cfg)
  148.     else:
  149.         while True:
  150.             GamingInterface(num_player=2screen=screen)
  151.             EndInterface(screen, cfg)
  152.  
  153.  
  154. '''run'''
  155. if __name__ == '__main__':
  156.     main()

5、消消乐

玩法:三个相连就能消除

源码分享:

  1.  
  2. import os
  3. import sys
  4. import cfg
  5. import pygame
  6. from modules import *
  7.  
  8.  
  9. '''游戏主程序'''
  10. def main():
  11.     pygame.init()
  12.     screen = pygame.display.set_mode(cfg.SCREENSIZE)
  13.     pygame.display.set_caption('Gemgem —— 九歌')
  14.     # 加载背景音乐
  15.     pygame.mixer.init()
  16.     pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))
  17.     pygame.mixer.music.set_volume(0.6)
  18.     pygame.mixer.music.play(-1)
  19.     # 加载音效
  20.     sounds = {}
  21.     sounds['mismatch'= pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))
  22.     sounds['match'= []
  23.     for i in range(6):
  24.         sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))
  25.     # 加载字体
  26.     font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)
  27.     # 图片加载
  28.     gem_imgs = []
  29.     for i in range(18):
  30.         gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))
  31.     # 主循环
  32.     game = gemGame(screen, sounds, font, gem_imgs, cfg)
  33.     while True:
  34.         score = game.start()
  35.         flag = False
  36.         # 一轮游戏结束后玩家选择重玩或者退出
  37.         while True:
  38.             for event in pygame.event.get():
  39.                 if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
  40.                     pygame.quit()
  41.                     sys.exit()
  42.                 elif event.type == pygame.KEYUP and event.key == pygame.K_r:
  43.                     flag = True
  44.             if flag:
  45.                 break
  46.             screen.fill((135206235))
  47.             text0 = 'Final score: %s' % score
  48.             text1 = 'Press <R> to restart the game.'
  49.             text2 = 'Press <Esc> to quit the game.'
  50.             y = 150
  51.             for idx, text in enumerate([text0, text1, text2]):
  52.                 text_render = font.render(text, 1, (85650))
  53.                 rect = text_render.get_rect()
  54.                 if idx == 0:
  55.                     rect.left, rect.top = (212, y)
  56.                 elif idx == 1:
  57.                     rect.left, rect.top = (122.5, y)
  58.                 else:
  59.                     rect.left, rect.top = (126.5, y)
  60.                 y += 100
  61.                 screen.blit(text_render, rect)
  62.             pygame.display.update()
  63.         game.reset()
  64.  
  65.  
  66. '''run'''
  67. if __name__ == '__main__':
  68.     main()

6、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的。

源码分享:

  1.  
  2. import os
  3. import sys
  4. import random
  5. from modules import *
  6. from PyQt5.QtGui import *
  7. from PyQt5.QtCore import *
  8. from PyQt5.QtWidgets import *
  9.  
  10.  
  11. '''定义俄罗斯方块游戏类'''
  12. class TetrisGame(QMainWindow):
  13.     def __init__(self, parent=None):
  14.         super(TetrisGame, self).__init__(parent)
  15.         # 是否暂停ing
  16.         self.is_paused = False
  17.         # 是否开始ing
  18.         self.is_started = False
  19.         self.initUI()
  20.     '''界面初始化'''
  21.     def initUI(self):
  22.         # icon
  23.         self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg')))
  24.         # 块大小
  25.         self.grid_size = 22
  26.         # 游戏帧率
  27.         self.fps = 200
  28.         self.timer = QBasicTimer()
  29.         # 焦点
  30.         self.setFocusPolicy(Qt.StrongFocus)
  31.         # 水平布局
  32.         layout_horizontal = QHBoxLayout()
  33.         self.inner_board = InnerBoard()
  34.         self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)
  35.         layout_horizontal.addWidget(self.external_board)
  36.         self.side_panel = SidePanel(self, self.grid_size, self.inner_board)
  37.         layout_horizontal.addWidget(self.side_panel)
  38.         self.status_bar = self.statusBar()
  39.         self.external_board.score_signal[str].connect(self.status_bar.showMessage)
  40.         self.start()
  41.         self.center()
  42.         self.setWindowTitle('Tetris —— 九歌')
  43.         self.show()
  44.         self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())
  45.     '''游戏界面移动到屏幕中间'''
  46.     def center(self):
  47.         screen = QDesktopWidget().screenGeometry()
  48.         size = self.geometry()
  49.         self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
  50.     '''更新界面'''
  51.     def updateWindow(self):
  52.         self.external_board.updateData()
  53.         self.side_panel.updateData()
  54.         self.update()
  55.     '''开始'''
  56.     def start(self):
  57.         if self.is_started:
  58.             return
  59.         self.is_started = True
  60.         self.inner_board.createNewTetris()
  61.         self.timer.start(self.fps, self)
  62.     '''暂停/不暂停'''
  63.     def pause(self):
  64.         if not self.is_started:
  65.             return
  66.         self.is_paused = not self.is_paused
  67.         if self.is_paused:
  68.             self.timer.stop()
  69.             self.external_board.score_signal.emit('Paused')
  70.         else:
  71.             self.timer.start(self.fps, self)
  72.         self.updateWindow()
  73.     '''计时器事件'''
  74.     def timerEvent(self, event):
  75.         if event.timerId() == self.timer.timerId():
  76.             removed_lines = self.inner_board.moveDown()
  77.             self.external_board.score += removed_lines
  78.             self.updateWindow()
  79.         else:
  80.             super(TetrisGame, self).timerEvent(event)
  81.     '''按键事件'''
  82.     def keyPressEvent(self, event):
  83.         if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:
  84.             super(TetrisGame, self).keyPressEvent(event)
  85.             return
  86.         key = event.key()
  87.         # P键暂停
  88.         if key == Qt.Key_P:
  89.             self.pause()
  90.             return
  91.         if self.is_paused:
  92.             return
  93.         # 向左
  94.         elif key == Qt.Key_Left:
  95.             self.inner_board.moveLeft()
  96.         # 向右
  97.         elif key == Qt.Key_Right:
  98.             self.inner_board.moveRight()
  99.         # 旋转
  100.         elif key == Qt.Key_Up:
  101.             self.inner_board.rotateAnticlockwise()
  102.         # 快速坠落
  103.         elif key == Qt.Key_Space:
  104.             self.external_board.score += self.inner_board.dropDown()
  105.         else:
  106.             super(TetrisGame, self).keyPressEvent(event)
  107.         self.updateWindow()
  108.  
  109.  
  110. '''run'''
  111. if __name__ == '__main__':
  112.     app = QApplication([])
  113.     tetris = TetrisGame()
  114.     sys.exit(app.exec_())

7、24点小游戏

玩法:通过加减乘除操作,小学生都没问题的。

源码分享:

  1.  
  2. import os
  3. import sys
  4. import pygame
  5. from cfg import *
  6. from modules import *
  7. from fractions import Fraction
  8.  
  9.  
  10. '''检查控件是否被点击'''
  11. def checkClicked(group, mouse_pos, group_type='NUMBER'):
  12.     selected = []
  13.     # 数字卡片/运算符卡片
  14.     if group_type == GROUPTYPES[0or group_type == GROUPTYPES[1]:
  15.         max_selected = 2 if group_type == GROUPTYPES[0else 1
  16.         num_selected = 0
  17.         for each in group:
  18.             num_selected += int(each.is_selected)
  19.         for each in group:
  20.             if each.rect.collidepoint(mouse_pos):
  21.                 if each.is_selected:
  22.                     each.is_selected = not each.is_selected
  23.                     num_selected -= 1
  24.                     each.select_order = None
  25.                 else:
  26.                     if num_selected < max_selected:
  27.                         each.is_selected = not each.is_selected
  28.                         num_selected += 1
  29.                         each.select_order = str(num_selected)
  30.             if each.is_selected:
  31.                 selected.append(each.attribute)
  32.     # 按钮卡片
  33.     elif group_type == GROUPTYPES[2]:
  34.         for each in group:
  35.             if each.rect.collidepoint(mouse_pos):
  36.                 each.is_selected = True
  37.                 selected.append(each.attribute)
  38.     # 抛出异常
  39.     else:
  40.         raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type*GROUPTYPES))
  41.     return selected
  42.  
  43.  
  44. '''获取数字精灵组'''
  45. def getNumberSpritesGroup(numbers):
  46.     number_sprites_group = pygame.sprite.Group()
  47.     for idx, number in enumerate(numbers):
  48.         args = (*NUMBERCARD_POSITIONS[idx], str(number), NUMBERFONT, NUMBERFONT_COLORS, NUMBERCARD_COLORS, str(number))
  49.         number_sprites_group.add(Card(*args))
  50.     return number_sprites_group
  51.  
  52.  
  53. '''获取运算符精灵组'''
  54. def getOperatorSpritesGroup(operators):
  55.     operator_sprites_group = pygame.sprite.Group()
  56.     for idx, operator in enumerate(operators):
  57.         args = (*OPERATORCARD_POSITIONS[idx], str(operator), OPERATORFONT, OPREATORFONT_COLORS, OPERATORCARD_COLORS, str(operator))
  58.         operator_sprites_group.add(Card(*args))
  59.     return operator_sprites_group
  60.  
  61.  
  62. '''获取按钮精灵组'''
  63. def getButtonSpritesGroup(buttons):
  64.     button_sprites_group = pygame.sprite.Group()
  65.     for idx, button in enumerate(buttons):
  66.         args = (*BUTTONCARD_POSITIONS[idx], str(button), BUTTONFONT, BUTTONFONT_COLORS, BUTTONCARD_COLORS, str(button))
  67.         button_sprites_group.add(Button(*args))
  68.     return button_sprites_group
  69.  
  70.  
  71. '''计算'''
  72. def calculate(number1number2, operator):
  73.     operator_map = {'+''+''-''-''×''*''÷''/'}
  74.     try:
  75.         result = str(eval(number1+operator_map[operator]+number2))
  76.         return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))
  77.     except:
  78.         return None
  79.  
  80.  
  81. '''在屏幕上显示信息'''
  82. def showInfo(text, screen):
  83.     rect = pygame.Rect(200180400200)
  84.     pygame.draw.rect(screen, PAPAYAWHIP, rect)
  85.     font = pygame.font.Font(FONTPATH, 40)
  86.     text_render = font.render(text, True, BLACK)
  87.     font_size = font.size(text)
  88.     screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2))
  89.  
  90.  
  91. '''主函数'''
  92. def main():
  93.     # 初始化, 导入必要的游戏素材
  94.     pygame.init()
  95.     pygame.mixer.init()
  96.     screen = pygame.display.set_mode(SCREENSIZE)
  97.     pygame.display.set_caption('24 point —— 九歌')
  98.     win_sound = pygame.mixer.Sound(AUDIOWINPATH)
  99.     lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
  100.     warn_sound = pygame.mixer.Sound(AUDIOWARNPATH)
  101.     pygame.mixer.music.load(BGMPATH)
  102.     pygame.mixer.music.play(-10.0)
  103.     # 24点游戏生成器
  104.     game24_gen = game24Generator()
  105.     game24_gen.generate()
  106.     # 精灵组
  107.     # --数字
  108.     number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
  109.     # --运算符
  110.     operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
  111.     # --按钮
  112.     button_sprites_group = getButtonSpritesGroup(BUTTONS)
  113.     # 游戏主循环
  114.     clock = pygame.time.Clock()
  115.     selected_numbers = []
  116.     selected_operators = []
  117.     selected_buttons = []
  118.     is_win = False
  119.     while True:
  120.         for event in pygame.event.get():
  121.             if event.type == pygame.QUIT:
  122.                 pygame.quit()
  123.                 sys.exit(-1)
  124.             elif event.type == pygame.MOUSEBUTTONUP:
  125.                 mouse_pos = pygame.mouse.get_pos()
  126.                 selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER')
  127.                 selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR')
  128.                 selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON')
  129.         screen.fill(AZURE)
  130.         # 更新数字
  131.         if len(selected_numbers) == 2 and len(selected_operators) == 1:
  132.             noselected_numbers = []
  133.             for each in number_sprites_group:
  134.                 if each.is_selected:
  135.                     if each.select_order == '1':
  136.                         selected_number1 = each.attribute
  137.                     elif each.select_order == '2':
  138.                         selected_number2 = each.attribute
  139.                     else:
  140.                         raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order)
  141.                 else:
  142.                     noselected_numbers.append(each.attribute)
  143.                 each.is_selected = False
  144.             for each in operator_sprites_group:
  145.                 each.is_selected = False
  146.             result = calculate(selected_number1, selected_number2*selected_operators)
  147.             if result is not None:
  148.                 game24_gen.numbers_now = noselected_numbers + [result]
  149.                 is_win = game24_gen.check()
  150.                 if is_win:
  151.                     win_sound.play()
  152.                 if not is_win and len(game24_gen.numbers_now) == 1:
  153.                     lose_sound.play()
  154.             else:
  155.                 warn_sound.play()
  156.             selected_numbers = []
  157.             selected_operators = []
  158.             number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
  159.         # 精灵都画到screen
  160.         for each in number_sprites_group:
  161.             each.draw(screen, pygame.mouse.get_pos())
  162.         for each in operator_sprites_group:
  163.             each.draw(screen, pygame.mouse.get_pos())
  164.         for each in button_sprites_group:
  165.             if selected_buttons and selected_buttons[0in ['RESET''NEXT']:
  166.                 is_win = False
  167.             if selected_buttons and each.attribute == selected_buttons[0]:
  168.                 each.is_selected = False
  169.                 number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group)
  170.                 selected_buttons = []
  171.             each.draw(screen, pygame.mouse.get_pos())
  172.         # 游戏胜利
  173.         if is_win:
  174.             showInfo('Congratulations'screen)
  175.         # 游戏失败
  176.         if not is_win and len(game24_gen.numbers_now) == 1:
  177.             showInfo('Game Over'screen)
  178.         pygame.display.flip()
  179.         clock.tick(30)
  180.  
  181.  
  182. '''run'''
  183. if __name__ == '__main__':
  184.     main()

8、外星人入侵

玩法:这让我想起了魂斗罗那第几关的boss,有点类似,不过魂斗罗那个难度肯定高点。

源码分享:

  1.  
  2. import os
  3. import sys
  4. import cfg
  5. import random
  6. import pygame
  7. from modules import *
  8.  
  9.  
  10. '''开始游戏'''
  11. def startGame(screen):
  12.     clock = pygame.time.Clock()
  13.     # 加载字体
  14.     font = pygame.font.SysFont('arial'18)
  15.     if not os.path.isfile('score'):
  16.         f = open('score''w')
  17.         f.write('0')
  18.         f.close()
  19.     with open('score''r'as f:
  20.         highest_score = int(f.read().strip())
  21.     # 敌方
  22.     enemies_group = pygame.sprite.Group()
  23.     for i in range(55):
  24.         if i < 11:
  25.             enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)
  26.         elif i < 33:
  27.             enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)
  28.         else:
  29.             enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)
  30.         enemy.rect.x = 85 + (i % 11* 50
  31.         enemy.rect.y = 120 + (i // 11* 45
  32.         enemies_group.add(enemy)
  33.     boomed_enemies_group = pygame.sprite.Group()
  34.     en_bullets_group = pygame.sprite.Group()
  35.     ufo = ufoSprite(color=cfg.RED)
  36.     # 我方
  37.     myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)
  38.     my_bullets_group = pygame.sprite.Group()
  39.     # 用于控制敌方位置更新
  40.     # --移动一行
  41.     enemy_move_count = 24
  42.     enemy_move_interval = 24
  43.     enemy_move_flag = False
  44.     # --改变移动方向(改变方向的同时集体下降一次)
  45.     enemy_change_direction_count = 0
  46.     enemy_change_direction_interval = 60
  47.     enemy_need_down = False
  48.     enemy_move_right = True
  49.     enemy_need_move_row = 6
  50.     enemy_max_row = 5
  51.     # 用于控制敌方发射子弹
  52.     enemy_shot_interval = 100
  53.     enemy_shot_count = 0
  54.     enemy_shot_flag = False
  55.     # 游戏进行中
  56.     running = True
  57.     is_win = False
  58.     # 主循环
  59.     while running:
  60.         screen.fill(cfg.BLACK)
  61.         for event in pygame.event.get():
  62.             # --点右上角的X或者按Esc键退出游戏
  63.             if event.type == pygame.QUIT:
  64.                 pygame.quit()
  65.                 sys.exit()
  66.             if event.type == pygame.KEYDOWN:
  67.                 if event.key == pygame.K_ESCAPE:
  68.                     pygame.quit()
  69.                     sys.exit()
  70.             # --射击
  71.             if event.type == pygame.MOUSEBUTTONDOWN:
  72.                 my_bullet = myaircraft.shot()
  73.                 if my_bullet:
  74.                     my_bullets_group.add(my_bullet)
  75.         # --我方子弹与敌方/UFO碰撞检测
  76.         for enemy in enemies_group:
  77.             if pygame.sprite.spritecollide(enemy, my_bullets_groupTrue, None):
  78.                 boomed_enemies_group.add(enemy)
  79.                 enemies_group.remove(enemy)
  80.                 myaircraft.score += enemy.reward
  81.         if pygame.sprite.spritecollide(ufo, my_bullets_groupTrue, None):
  82.             ufo.is_dead = True
  83.             myaircraft.score += ufo.reward
  84.         # --更新并画敌方
  85.         # ----敌方子弹
  86.         enemy_shot_count += 1
  87.         if enemy_shot_count > enemy_shot_interval:
  88.             enemy_shot_flag = True
  89.             enemies_survive_list = [enemy.number for enemy in enemies_group]
  90.             shot_number = random.choice(enemies_survive_list)
  91.             enemy_shot_count = 0
  92.         # ----敌方移动
  93.         enemy_move_count += 1
  94.         if enemy_move_count > enemy_move_interval:
  95.             enemy_move_count = 0
  96.             enemy_move_flag = True
  97.             enemy_need_move_row -= 1
  98.             if enemy_need_move_row == 0:
  99.                 enemy_need_move_row = enemy_max_row
  100.             enemy_change_direction_count += 1
  101.             if enemy_change_direction_count > enemy_change_direction_interval:
  102.                 enemy_change_direction_count = 1
  103.                 enemy_move_right = not enemy_move_right
  104.                 enemy_need_down = True
  105.                 # ----每次下降提高移动和射击速度
  106.                 enemy_move_interval = max(15, enemy_move_interval-3)
  107.                 enemy_shot_interval = max(50, enemy_move_interval-10)
  108.         # ----遍历更新
  109.         for enemy in enemies_group:
  110.             if enemy_shot_flag:
  111.                 if enemy.number == shot_number:
  112.                     en_bullet = enemy.shot()
  113.                     en_bullets_group.add(en_bullet)
  114.             if enemy_move_flag:
  115.                 if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):
  116.                     if enemy_move_right:
  117.                         enemy.update('right', cfg.SCREENSIZE[1])
  118.                     else:
  119.                         enemy.update('left', cfg.SCREENSIZE[1])
  120.             else:
  121.                 enemy.update(None, cfg.SCREENSIZE[1])
  122.             if enemy_need_down:
  123.                 if enemy.update('down', cfg.SCREENSIZE[1]):
  124.                     running = False
  125.                     is_win = False
  126.                 enemy.change_count -= 1
  127.             enemy.draw(screen)
  128.         enemy_move_flag = False
  129.         enemy_need_down = False
  130.         enemy_shot_flag = False
  131.         # ----敌方爆炸特效
  132.         for boomed_enemy in boomed_enemies_group:
  133.             if boomed_enemy.boom(screen):
  134.                 boomed_enemies_group.remove(boomed_enemy)
  135.                 del boomed_enemy
  136.         # --敌方子弹与我方飞船碰撞检测
  137.         if not myaircraft.one_dead:
  138.             if pygame.sprite.spritecollide(myaircraft, en_bullets_groupTrue, None):
  139.                 myaircraft.one_dead = True
  140.         if myaircraft.one_dead:
  141.             if myaircraft.boom(screen):
  142.                 myaircraft.resetBoom()
  143.                 myaircraft.num_life -= 1
  144.                 if myaircraft.num_life < 1:
  145.                     running = False
  146.                     is_win = False
  147.         else:
  148.             # ----更新飞船
  149.             myaircraft.update(cfg.SCREENSIZE[0])
  150.             # ----画飞船
  151.             myaircraft.draw(screen)
  152.         if (not ufo.has_boomed) and (ufo.is_dead):
  153.             if ufo.boom(screen):
  154.                 ufo.has_boomed = True
  155.         else:
  156.             # ----更新UFO
  157.             ufo.update(cfg.SCREENSIZE[0])
  158.             # ----画UFO
  159.             ufo.draw(screen)
  160.         # --画我方飞船子弹
  161.         for bullet in my_bullets_group:
  162.             if bullet.update():
  163.                 my_bullets_group.remove(bullet)
  164.                 del bullet
  165.             else:
  166.                 bullet.draw(screen)
  167.         # --画敌方子弹
  168.         for bullet in en_bullets_group:
  169.             if bullet.update(cfg.SCREENSIZE[1]):
  170.                 en_bullets_group.remove(bullet)
  171.                 del bullet
  172.             else:
  173.                 bullet.draw(screen)
  174.         if myaircraft.score > highest_score:
  175.             highest_score = myaircraft.score
  176.         # --得分每增加2000我方飞船增加一条生命
  177.         if (myaircraft.score % 2000 == 0and (myaircraft.score > 0and (myaircraft.score != myaircraft.old_score):
  178.             myaircraft.old_score = myaircraft.score
  179.             myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)
  180.         # --敌人都死光了的话就胜利了
  181.         if len(enemies_group< 1:
  182.             is_win = True
  183.             running = False
  184.         # --显示文字
  185.         # ----当前得分
  186.         showText(screen'SCORE: ', cfg.WHITE, font, 2008)
  187.         showText(screen, str(myaircraft.score), cfg.WHITE, font, 20024)
  188.         # ----敌人数量
  189.         showText(screen'ENEMY: ', cfg.WHITE, font, 3708)
  190.         showText(screen, str(len(enemies_group)), cfg.WHITE, font, 37024)
  191.         # ----历史最高分
  192.         showText(screen'HIGHEST: ', cfg.WHITE, font, 5408)
  193.         showText(screen, str(highest_score), cfg.WHITE, font, 54024)
  194.         # ----FPS
  195.         showText(screen'FPS: ' + str(int(clock.get_fps())), cfg.RED, font, 88)
  196.         # --显示剩余生命值
  197.         showLife(screen, myaircraft.num_life, cfg.GREEN)
  198.         pygame.display.update()
  199.         clock.tick(cfg.FPS)
  200.     with open('score''w'as f:
  201.         f.write(str(highest_score))
  202.     return is_win
  203.  
  204.  
  205. '''主函数'''
  206. def main():
  207.     # 初始化
  208.     pygame.init()
  209.     pygame.display.set_caption('外星人入侵 —— 九歌')
  210.     screen = pygame.display.set_mode(cfg.SCREENSIZE)
  211.     pygame.mixer.init()
  212.     pygame.mixer.music.load(cfg.BGMPATH)
  213.     pygame.mixer.music.set_volume(0.4)
  214.     pygame.mixer.music.play(-1)
  215.     while True:
  216.         is_win = startGame(screen)
  217.         endInterface(screen, cfg.BLACK, is_win)
  218.  
  219.  
  220. '''run'''
  221. if __name__ == '__main__':
  222.     main()

【python学习】
学Python的伙伴,欢迎加入新的交流【君羊】:1020465983
一起探讨编程知识,成为大神,群里还有软件安装包,实战案例、学习资料 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/92057
推荐阅读
相关标签
  

闽ICP备14008679号