当前位置:   article > 正文

python编写小游戏的代码,python游戏编程代码大全_python编写小游戏代码

python编写小游戏代码

大家好,小编为大家解答python游戏编程入门游戏代码的问题。很多人还不知道python编写小游戏的代码,现在让我们一起来看看吧!

大家好,小编来为大家解答以下问题,如何用python编写一个简单的小游戏,用python语言编简单游戏,今天让我们一起来看看吧!

今天给大家分享13个游戏源码,可以自己复现玩玩,研究下里面的编程逻辑,对学习编程(特别是初学者)应该会有很大帮助。

1、吃金币

源码分享:

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

2、打乒乓

源码分享:

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

3、滑雪

源码分享:

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

4、并夕夕版飞机大战

源码分享:

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

5、打地鼠

源码分享:

  1. import cfg
  2. import sys
  3. import pygame
  4. import random
  5. from modules import *
  6. '''游戏初始化'''
  7. def initGame():
  8. pygame.init()
  9. pygame.mixer.init()
  10. screen = pygame.display.set_mode(cfg.SCREENSIZE)
  11. pygame.display.set_caption('打地鼠 —— 九歌')
  12. return screen
  13. '''主函数'''
  14. def main():
  15. # 初始化
  16. screen = initGame()
  17. # 加载背景音乐和其他音效
  18. pygame.mixer.music.load(cfg.BGM_PATH)
  19. pygame.mixer.music.play(-1)
  20. audios = {
  21. 'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
  22. 'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
  23. }
  24. # 加载字体
  25. font = pygame.font.Font(cfg.FONT_PATH, 40)
  26. # 加载背景图片
  27. bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
  28. # 开始界面
  29. startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
  30. # 地鼠改变位置的计时
  31. hole_pos = random.choice(cfg.HOLE_POSITIONS)
  32. change_hole_event = pygame.USEREVENT
  33. pygame.time.set_timer(change_hole_event, 800)
  34. # 地鼠
  35. mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
  36. # 锤子
  37. hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
  38. # 时钟
  39. clock = pygame.time.Clock()
  40. # 分数
  41. your_score = 0
  42. flag = False
  43. # 初始时间
  44. init_time = pygame.time.get_ticks()
  45. # 游戏主循环
  46. while True:
  47. # --游戏时间为60s
  48. time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
  49. # --游戏时间减少, 地鼠变位置速度变快
  50. if time_remain == 40 and not flag:
  51. hole_pos = random.choice(cfg.HOLE_POSITIONS)
  52. mole.reset()
  53. mole.setPosition(hole_pos)
  54. pygame.time.set_timer(change_hole_event, 650)
  55. flag = True
  56. elif time_remain == 20 and flag:
  57. hole_pos = random.choice(cfg.HOLE_POSITIONS)
  58. mole.reset()
  59. mole.setPosition(hole_pos)
  60. pygame.time.set_timer(change_hole_event, 500)
  61. flag = False
  62. # --倒计时音效
  63. if time_remain == 10:
  64. audios['count_down'].play()
  65. # --游戏结束
  66. if time_remain < 0: break
  67. count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
  68. # --按键检测
  69. for event in pygame.event.get():
  70. if event.type == pygame.QUIT:
  71. pygame.quit()
  72. sys.exit()
  73. elif event.type == pygame.MOUSEMOTION:
  74. hammer.setPosition(pygame.mouse.get_pos())
  75. elif event.type == pygame.MOUSEBUTTONDOWN:
  76. if event.button == 1:
  77. hammer.setHammering()
  78. elif event.type == change_hole_event:
  79. hole_pos = random.choice(cfg.HOLE_POSITIONS)
  80. mole.reset()
  81. mole.setPosition(hole_pos)
  82. # --碰撞检测
  83. if hammer.is_hammering and not mole.is_hammer:
  84. is_hammer = pygame.sprite.collide_mask(hammer, mole)
  85. if is_hammer:
  86. audios['hammering'].play()
  87. mole.setBeHammered()
  88. your_score += 10
  89. # --分数
  90. your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
  91. # --绑定必要的游戏元素到屏幕(注意顺序)
  92. screen.blit(bg_img, (0, 0))
  93. screen.blit(count_down_text, (875, 8))
  94. screen.blit(your_score_text, (800, 430))
  95. mole.draw(screen)
  96. hammer.draw(screen)
  97. # --更新
  98. pygame.display.flip()
  99. clock.tick(60)
  100. # 读取最佳分数(try块避免第一次游戏无.rec文件)
  101. try:
  102. best_score = int(open(cfg.RECORD_PATH).read())
  103. except:
  104. best_score = 0
  105. # 若当前分数大于最佳分数则更新最佳分数
  106. if your_score > best_score:
  107. f = open(cfg.RECORD_PATH, 'w')
  108. f.write(str(your_score))
  109. f.close()
  110. # 结束界面
  111. score_info = {'your_score': your_score, 'best_score': best_score}
  112. is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
  113. return is_restart
  114. '''run'''
  115. if __name__ == '__main__':
  116. while True:
  117. is_restart = main()
  118. if not is_restart:
  119. break

6、小恐龙

玩法:上下控制起跳躲避

源码分享:

  1. import cfg
  2. import sys
  3. import random
  4. import pygame
  5. from modules import *
  6. '''main'''
  7. def main(highest_score):
  8. # 游戏初始化
  9. pygame.init()
  10. screen = pygame.display.set_mode(cfg.SCREENSIZE)
  11. pygame.display.set_caption('九歌')
  12. # 导入所有声音文件
  13. sounds = {}
  14. for key, value in cfg.AUDIO_PATHS.items():
  15. sounds[key] = pygame.mixer.Sound(value)
  16. # 游戏开始界面
  17. GameStartInterface(screen, sounds, cfg)
  18. # 定义一些游戏中必要的元素和变量
  19. score = 0
  20. score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR)
  21. highest_score = highest_score
  22. highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True)
  23. dino = Dinosaur(cfg.IMAGE_PATHS['dino'])
  24. ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1]))
  25. cloud_sprites_group = pygame.sprite.Group()
  26. cactus_sprites_group = pygame.sprite.Group()
  27. ptera_sprites_group = pygame.sprite.Group()
  28. add_obstacle_timer = 0
  29. score_timer = 0
  30. # 游戏主循环
  31. clock = pygame.time.Clock()
  32. while True:
  33. for event in pygame.event.get():
  34. if event.type == pygame.QUIT:
  35. pygame.quit()
  36. sys.exit()
  37. elif event.type == pygame.KEYDOWN:
  38. if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
  39. dino.jump(sounds)
  40. elif event.key == pygame.K_DOWN:
  41. dino.duck()
  42. elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
  43. dino.unduck()
  44. screen.fill(cfg.BACKGROUND_COLOR)
  45. # --随机添加云
  46. if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10:
  47. cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75))))
  48. # --随机添加仙人掌/飞龙
  49. add_obstacle_timer += 1
  50. if add_obstacle_timer > random.randrange(50, 150):
  51. add_obstacle_timer = 0
  52. random_value = random.randrange(0, 10)
  53. if random_value >= 5 and random_value <= 7:
  54. cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti']))
  55. else:
  56. position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20]
  57. ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys))))
  58. # --更新游戏元素
  59. dino.update()
  60. ground.update()
  61. cloud_sprites_group.update()
  62. cactus_sprites_group.update()
  63. ptera_sprites_group.update()
  64. score_timer += 1
  65. if score_timer > (cfg.FPS//12):
  66. score_timer = 0
  67. score += 1
  68. score = min(score, 99999)
  69. if score > highest_score:
  70. highest_score = score
  71. if score % 100 == 0:
  72. sounds['point'].play()
  73. if score % 1000 == 0:
  74. ground.speed -= 1
  75. for item in cloud_sprites_group:
  76. item.speed -= 1
  77. for item in cactus_sprites_group:
  78. item.speed -= 1
  79. for item in ptera_sprites_group:
  80. item.speed -= 1
  81. # --碰撞检测
  82. for item in cactus_sprites_group:
  83. if pygame.sprite.collide_mask(dino, item):
  84. dino.die(sounds)
  85. for item in ptera_sprites_group:
  86. if pygame.sprite.collide_mask(dino, item):
  87. dino.die(sounds)
  88. # --将游戏元素画到屏幕上
  89. dino.draw(screen)
  90. ground.draw(screen)
  91. cloud_sprites_group.draw(screen)
  92. cactus_sprites_group.draw(screen)
  93. ptera_sprites_group.draw(screen)
  94. score_board.set(score)
  95. highest_score_board.set(highest_score)
  96. score_board.draw(screen)
  97. highest_score_board.draw(screen)
  98. # --更新屏幕
  99. pygame.display.update()
  100. clock.tick(cfg.FPS)
  101. # --游戏是否结束
  102. if dino.is_dead:
  103. break
  104. # 游戏结束界面
  105. return GameEndInterface(screen, cfg), highest_score
  106. '''run'''
  107. if __name__ == '__main__':
  108. highest_score = 0
  109. while True:
  110. flag, highest_score = main(highest_score)
  111. if not flag: break

7、消消乐

玩法:三个相连就能消除

源码分享:

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

8、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的小发猫伪原创API调用说明python实现猴子跳台阶

源码分享:

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

9、贪吃蛇

玩法:童年经典,普通魔术也没啥意思,小时候玩的也是加速的。

源码分享:

  1. import cfg
  2. import sys
  3. import pygame
  4. from modules import *
  5. '''主函数'''
  6. def main(cfg):
  7. # 游戏初始化
  8. pygame.init()
  9. screen = pygame.display.set_mode(cfg.SCREENSIZE)
  10. pygame.display.set_caption('Greedy Snake —— 九歌')
  11. clock = pygame.time.Clock()
  12. # 播放背景音乐
  13. pygame.mixer.music.load(cfg.BGMPATH)
  14. pygame.mixer.music.play(-1)
  15. # 游戏主循环
  16. snake = Snake(cfg)
  17. apple = Apple(cfg, snake.coords)
  18. score = 0
  19. while True:
  20. screen.fill(cfg.BLACK)
  21. # --按键检测
  22. for event in pygame.event.get():
  23. if event.type == pygame.QUIT:
  24. pygame.quit()
  25. sys.exit()
  26. elif event.type == pygame.KEYDOWN:
  27. if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
  28. snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])
  29. # --更新贪吃蛇和食物
  30. if snake.update(apple):
  31. apple = Apple(cfg, snake.coords)
  32. score += 1
  33. # --判断游戏是否结束
  34. if snake.isgameover: break
  35. # --显示游戏里必要的元素
  36. drawGameGrid(cfg, screen)
  37. snake.draw(screen)
  38. apple.draw(screen)
  39. showScore(cfg, score, screen)
  40. # --屏幕更新
  41. pygame.display.update()
  42. clock.tick(cfg.FPS)
  43. return endInterface(screen, cfg)
  44. '''run'''
  45. if __name__ == '__main__':
  46. while True:
  47. if not main(cfg):
  48. break

10、24点小游戏

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

源码分享:

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

11、平衡木

玩法:也是小时候的经典游戏,控制左右就行,到后面才有一点点难度。

源码分享:

  1. import cfg
  2. from modules import breakoutClone
  3. '''主函数'''
  4. def main():
  5. game = breakoutClone(cfg)
  6. game.run()
  7. '''run'''
  8. if __name__ == '__main__':
  9. main()

12、外星人入侵

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

源码分享:

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

13、井字棋888

玩法:我打赌大家在课堂上肯定玩过这个,想想当年和同桌玩这个废了好几本本子。

源码分享:

  1. from tkinter import *
  2. import tkinter.messagebox as msg
  3. root = Tk()
  4. root.title('TIC-TAC-TOE---Project Gurukul')
  5. # labels
  6. Label(root, text="player1 : X", font="times 15").grid(row=0, column=1)
  7. Label(root, text="player2 : O", font="times 15").grid(row=0, column=2)
  8. digits = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  9. # for player1 sign = X and for player2 sign= Y
  10. mark = ''
  11. # counting the no. of click
  12. count = 0
  13. panels = ["panel"] * 10
  14. def win(panels, sign):
  15. return ((panels[1] == panels[2] == panels[3] == sign)
  16. or (panels[1] == panels[4] == panels[7] == sign)
  17. or (panels[1] == panels[5] == panels[9] == sign)
  18. or (panels[2] == panels[5] == panels[8] == sign)
  19. or (panels[3] == panels[6] == panels[9] == sign)
  20. or (panels[3] == panels[5] == panels[7] == sign)
  21. or (panels[4] == panels[5] == panels[6] == sign)
  22. or (panels[7] == panels[8] == panels[9] == sign))
  23. def checker(digit):
  24. global count, mark, digits
  25. # Check which button clicked
  26. if digit == 1 and digit in digits:
  27. digits.remove(digit)
  28. ##player1 will play if the value of count is even and for odd player2 will play
  29. if count % 2 == 0:
  30. mark = 'X'
  31. panels[digit] = mark
  32. elif count % 2 != 0:
  33. mark = 'O'
  34. panels[digit] = mark
  35. button1.config(text=mark)
  36. count = count + 1
  37. sign = mark
  38. if (win(panels, sign) and sign == 'X'):
  39. msg.showinfo("Result", "Player1 wins")
  40. root.destroy()
  41. elif (win(panels, sign) and sign == 'O'):
  42. msg.showinfo("Result", "Player2 wins")
  43. root.destroy()
  44. if digit == 2 and digit in digits:
  45. digits.remove(digit)
  46. if count % 2 == 0:
  47. mark = 'X'
  48. panels[digit] = mark
  49. elif count % 2 != 0:
  50. mark = 'O'
  51. panels[digit] = mark
  52. button2.config(text=mark)
  53. count = count + 1
  54. sign = mark
  55. if (win(panels, sign) and sign == 'X'):
  56. msg.showinfo("Result", "Player1 wins")
  57. root.destroy()
  58. elif (win(panels, sign) and sign == 'O'):
  59. msg.showinfo("Result", "Player2 wins")
  60. root.destroy()
  61. if digit == 3 and digit in digits:
  62. digits.remove(digit)
  63. if count % 2 == 0:
  64. mark = 'X'
  65. panels[digit] = mark
  66. elif count % 2 != 0:
  67. mark = 'O'
  68. panels[digit] = mark
  69. button3.config(text=mark)
  70. count = count + 1
  71. sign = mark
  72. if (win(panels, sign) and sign == 'X'):
  73. msg.showinfo("Result", "Player1 wins")
  74. root.destroy()
  75. elif (win(panels, sign) and sign == 'O'):
  76. msg.showinfo("Result", "Player2 wins")
  77. root.destroy()
  78. if digit == 4 and digit in digits:
  79. digits.remove(digit)
  80. if count % 2 == 0:
  81. mark = 'X'
  82. panels[digit] = mark
  83. elif count % 2 != 0:
  84. mark = 'O'
  85. panels[digit] = mark
  86. button4.config(text=mark)
  87. count = count + 1
  88. sign = mark
  89. if (win(panels, sign) and sign == 'X'):
  90. msg.showinfo("Result", "Player1 wins")
  91. root.destroy()
  92. elif (win(panels, sign) and sign == 'O'):
  93. msg.showinfo("Result", "Player2 wins")
  94. root.destroy()
  95. if digit == 5 and digit in digits:
  96. digits.remove(digit)
  97. if count % 2 == 0:
  98. mark = 'X'
  99. panels[digit] = mark
  100. elif count % 2 != 0:
  101. mark = 'O'
  102. panels[digit] = mark
  103. button5.config(text=mark)
  104. count = count + 1
  105. sign = mark
  106. if (win(panels, sign) and sign == 'X'):
  107. msg.showinfo("Result", "Player1 wins")
  108. root.destroy()
  109. elif (win(panels, sign) and sign == 'O'):
  110. msg.showinfo("Result", "Player2 wins")
  111. root.destroy()
  112. if digit == 6 and digit in digits:
  113. digits.remove(digit)
  114. if count % 2 == 0:
  115. mark = 'X'
  116. panels[digit] = mark
  117. elif count % 2 != 0:
  118. mark = 'O'
  119. panels[digit] = mark
  120. button6.config(text=mark)
  121. count = count + 1
  122. sign = mark
  123. if (win(panels, sign) and sign == 'X'):
  124. msg.showinfo("Result", "Player1 wins")
  125. root.destroy()
  126. elif (win(panels, sign) and sign == 'O'):
  127. msg.showinfo("Result", "Player2 wins")
  128. root.destroy()
  129. if digit == 7 and digit in digits:
  130. digits.remove(digit)
  131. if count % 2 == 0:
  132. mark = 'X'
  133. panels[digit] = mark
  134. elif count % 2 != 0:
  135. mark = 'O'
  136. panels[digit] = mark
  137. button7.config(text=mark)
  138. count = count + 1
  139. sign = mark
  140. if (win(panels, sign) and sign == 'X'):
  141. msg.showinfo("Result", "Player1 wins")
  142. root.destroy()
  143. elif (win(panels, sign) and sign == 'O'):
  144. msg.showinfo("Result", "Player2 wins")
  145. root.destroy()
  146. if digit == 8 and digit in digits:
  147. digits.remove(digit)
  148. if count % 2 == 0:
  149. mark = 'X'
  150. panels[digit] = mark
  151. elif count % 2 != 0:
  152. mark = 'O'
  153. panels[digit] = mark
  154. button8.config(text=mark)
  155. count = count + 1
  156. sign = mark
  157. if (win(panels, sign) and sign == 'X'):
  158. msg.showinfo("Result", "Player1 wins")
  159. root.destroy()
  160. elif (win(panels, sign) and sign == 'O'):
  161. msg.showinfo("Result", "Player2 wins")
  162. root.destroy()
  163. if digit == 9 and digit in digits:
  164. digits.remove(digit)
  165. if count % 2 == 0:
  166. mark = 'X'
  167. panels[digit] = mark
  168. elif count % 2 != 0:
  169. mark = 'O'
  170. panels[digit] = mark
  171. button9.config(text=mark)
  172. count = count + 1
  173. sign = mark
  174. if (win(panels, sign) and sign == 'X'):
  175. msg.showinfo("Result", "Player1 wins")
  176. root.destroy()
  177. elif (win(panels, sign) and sign == 'O'):
  178. msg.showinfo("Result", "Player2 wins")
  179. root.destroy()
  180. ###if count is greater then 8 then the match has been tied
  181. if (count > 8 and win(panels, 'X') == False and win(panels, 'O') == False):
  182. msg.showinfo("Result", "Match Tied")
  183. root.destroy()
  184. ####define buttons
  185. button1 = Button(root, width=15, font=('Times 16 bold'), height=7, command=lambda: checker(1))
  186. button1.grid(row=1, column=1)
  187. button2 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(2))
  188. button2.grid(row=1, column=2)
  189. button3 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(3))
  190. button3.grid(row=1, column=3)
  191. button4 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(4))
  192. button4.grid(row=2, column=1)
  193. button5 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(5))
  194. button5.grid(row=2, column=2)
  195. button6 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(6))
  196. button6.grid(row=2, column=3)
  197. button7 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(7))
  198. button7.grid(row=3, column=1)
  199. button8 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(8))
  200. button8.grid(row=3, column=2)
  201. button9 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(9))
  202. button9.grid(row=3, column=3)
  203. root.mainloop()

如果你对Python感兴趣,想要学习pyhton,这里给大家分享一份Python全套学习资料,里面的内容都是适合零基础小白的笔记和资料,超多实战案例,不懂编程也能听懂、看懂。

需要的话可以微信扫描下方二维码免费获得。

一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
在这里插入图片描述
二、Python学习软件

学习Python常用的开发软件都在这里了!每个都有详细的安装教程,保证你可以安装成功哦!
在这里插入图片描述
三、Python入门学习视频

还有很多适合0基础入门的学习视频,有了这些视频,轻轻松松上手Python~
在这里插入图片描述
四、Python实战案例

光学理论是没用的,要学会跟着一起敲代码,动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。100+实战案例源码等你来拿!
在这里插入图片描述
五、Python小游戏源码
如果觉得上面的实战案例有点枯燥,可以试试自己用Python编写小游戏,让你的学习过程中增添一点趣味!
在这里插入图片描述
六、副业兼职
而且学会Python以后,还可以在各大兼职平台接单赚钱,各种兼职渠道+兼职注意事项+如何和客户沟通,我都整理成文档了。
在这里插入图片描述
七、资料领取
由于篇幅有限,很多资料图片放不上来。需要的小伙伴可以微信扫描下方CSDN官方认证二维码领取(免费免费免费)

文章知识点与官方知识档案匹配,可进一步学习相关知识
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/456340
推荐阅读
相关标签
  

闽ICP备14008679号