当前位置:   article > 正文

用python制作简单的小游戏,用python设计一个小游戏_python编写简单小游戏

python编写简单小游戏

大家好,本文将围绕python编写小游戏详细教程展开说明,用python制作简单的小游戏是一个很多人都想弄明白的事情,想搞清楚用python设计一个小游戏需要先了解以下几个事情。

本篇文章给大家谈谈如何用python编写一个简单的小游戏,以及如何用Python做小游戏让别人玩,希望对各位有所帮助,不要忘了收藏本站喔。

1、小恐龙

玩法:上下控制起跳躲避

  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

2、消消乐

玩法:三个相连就能消除

  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()

3、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的python中turtle怎么画

  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_())

 4、贪吃蛇

玩法:童年经典,普通魔术也没啥意思,小时候玩的也是加速的如何安装python的软件包

  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

5、平衡木

玩法:也是小时候的经典

  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()

6、外星人入侵

玩法:这让我想起了魂斗罗那第几关的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()

7、井字棋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()

最后,七个小游戏到这里就没有了,不管是放松还是拿来练手,都是很不错滴。看着这密密麻麻的代码,我都要给自己一个大大的赞,你确定不赞我一个?

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

闽ICP备14008679号