首页 文章详情

二十种Python代码游戏源代码分享

python教程 | 843 2021-04-06 10:51 0 0 0
UniSMS (合一短信)

学python中,自我感觉学的还不错的亚子~想做点什么来练练手,然后我疯狂的找各种小游戏的教程源码什么的,于是我就疯狂的找呀找呀,就找到了一大堆,哈哈哈
毕竟我是从小就有一个游戏梦,现在就弥补一下自己小时候没有玩过瘾的游戏补上叭~

提示:爱学习哦,不要沉迷游戏,平时打发一下无聊时间最好啦

1、21点数字小游戏展示:

首先配置文件的源码:

  1. '''配置文件'''

  2. import os

  3. # 一些常量

  4. RED = (255, 0, 0)

  5. BLACK = (0, 0, 0)

  6. AZURE = (240, 255, 255)

  7. WHITE = (255, 255, 255)

  8. MISTYROSE = (255, 228, 225)

  9. PALETURQUOISE = (175, 238, 238)

  10. PAPAYAWHIP = (255, 239, 213)

  11. CURRENTPATH = os.getcwd()

  12. FONTPATH = os.path.join(CURRENTPATH, 'resources/fonts/font.TTF')

  13. AUDIOWINPATH = os.path.join(CURRENTPATH, 'resources/audios/win.wav')

  14. AUDIOLOSEPATH = os.path.join(CURRENTPATH, 'resources/audios/lose.wav')

  15. AUDIOWARNPATH = os.path.join(CURRENTPATH, 'resources/audios/warn.wav')

  16. BGMPATH = os.path.join(CURRENTPATH, 'resources/audios/bgm.mp3')

  17. # 数字卡片

  18. # --数字卡片字体颜色

  19. NUMBERFONT_COLORS = [BLACK, RED]

  20. # --数字卡片背景颜色

  21. NUMBERCARD_COLORS = [MISTYROSE, PALETURQUOISE]

  22. # --数字卡片字体路径与大小

  23. NUMBERFONT = [FONTPATH, 50]

  24. # --数字卡片位置

  25. NUMBERCARD_POSITIONS = [(25, 50, 150, 200), (225, 50, 150, 200), (425, 50, 150, 200), (625, 50, 150, 200)]

  26. # 运算符卡片

  27. # --运算符种类

  28. OPREATORS = ['+', '-', '', '']

  29. # --运算符卡片字体颜色

  30. OPREATORFONT_COLORS = [BLACK, RED]

  31. # --运算符卡片背景颜色

  32. OPERATORCARD_COLORS = [MISTYROSE, PALETURQUOISE]

  33. # --运算符卡片字体路径与大小

  34. OPERATORFONT = [FONTPATH, 30]

  35. # --运算符卡片位置

  36. OPERATORCARD_POSITIONS = [(230, 300, 50, 50), (330, 300, 50, 50), (430, 300, 50, 50), (530, 300, 50, 50)]

  37. # 按钮卡片

  38. # --按钮类型

  39. BUTTONS = ['RESET', 'ANSWERS', 'NEXT']

  40. # --按钮卡片字体颜色

  41. BUTTONFONT_COLORS = [BLACK, BLACK]

  42. # --按钮卡片背景颜色

  43. BUTTONCARD_COLORS = [MISTYROSE, PALETURQUOISE]

  44. # --按钮卡片字体路径与大小

  45. BUTTONFONT = [FONTPATH, 30]

  46. # --按钮卡片位置

  47. BUTTONCARD_POSITIONS = [(25, 400, 700/3, 150), (50+700/3, 400, 700/3, 150), (75+1400/3, 400, 700/3, 150)]

  48. # 屏幕大小

  49. SCREENSIZE = (800, 600)

  50. # 卡片类型

  51. GROUPTYPES = ['NUMBER', 'OPREATOR', 'BUTTON']

游戏源码:

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

2、保卫森林大作战啦啦

展示:

首先配置文件的源码:

  1. '''配置文件'''

  2. import os

  3. '''屏幕大小'''

  4. SCREENSIZE = (800, 600)

  5. '''图片路径'''

  6. IMAGEPATHS = {

  7. 'choice': {

  8. 'load_game': os.path.join(os.getcwd(), 'resources/images/choice/load_game.png'),

  9. 'map1': os.path.join(os.getcwd(), 'resources/images/choice/map1.png'),

  10. 'map1_black': os.path.join(os.getcwd(), 'resources/images/choice/map1_black.png'),

  11. 'map1_red': os.path.join(os.getcwd(), 'resources/images/choice/map1_red.png'),

  12. 'map2': os.path.join(os.getcwd(), 'resources/images/choice/map2.png'),

  13. 'map2_black': os.path.join(os.getcwd(), 'resources/images/choice/map2_black.png'),

  14. 'map2_red': os.path.join(os.getcwd(), 'resources/images/choice/map2_red.png'),

  15. 'map3': os.path.join(os.getcwd(), 'resources/images/choice/map3.png'),

  16. 'map3_black': os.path.join(os.getcwd(), 'resources/images/choice/map3_black.png'),

  17. 'map3_red': os.path.join(os.getcwd(), 'resources/images/choice/map3_red.png'),

  18. },

  19. 'end': {

  20. 'gameover': os.path.join(os.getcwd(), 'resources/images/end/gameover.png'),

  21. 'continue_red': os.path.join(os.getcwd(), 'resources/images/end/continue_red.png'),

  22. 'continue_black': os.path.join(os.getcwd(), 'resources/images/end/continue_black.png'),

  23. },

  24. 'game': {

  25. 'arrow1': os.path.join(os.getcwd(), 'resources/images/game/arrow1.png'),

  26. 'arrow2': os.path.join(os.getcwd(), 'resources/images/game/arrow2.png'),

  27. 'arrow3': os.path.join(os.getcwd(), 'resources/images/game/arrow3.png'),

  28. 'basic_tower': os.path.join(os.getcwd(), 'resources/images/game/basic_tower.png'),

  29. 'boulder': os.path.join(os.getcwd(), 'resources/images/game/boulder.png'),

  30. 'bush': os.path.join(os.getcwd(), 'resources/images/game/bush.png'),

  31. 'cave': os.path.join(os.getcwd(), 'resources/images/game/cave.png'),

  32. 'dirt': os.path.join(os.getcwd(), 'resources/images/game/dirt.png'),

  33. 'enemy_blue': os.path.join(os.getcwd(), 'resources/images/game/enemy_blue.png'),

  34. 'enemy_pink': os.path.join(os.getcwd(), 'resources/images/game/enemy_pink.png'),

  35. 'enemy_red': os.path.join(os.getcwd(), 'resources/images/game/enemy_red.png'),

  36. 'enemy_yellow': os.path.join(os.getcwd(), 'resources/images/game/enemy_yellow.png'),

  37. 'godark': os.path.join(os.getcwd(), 'resources/images/game/godark.png'),

  38. 'golight': os.path.join(os.getcwd(), 'resources/images/game/golight.png'),

  39. 'grass': os.path.join(os.getcwd(), 'resources/images/game/grass.png'),

  40. 'healthfont': os.path.join(os.getcwd(), 'resources/images/game/healthfont.png'),

  41. 'heavy_tower': os.path.join(os.getcwd(), 'resources/images/game/heavy_tower.png'),

  42. 'med_tower': os.path.join(os.getcwd(), 'resources/images/game/med_tower.png'),

  43. 'nexus': os.path.join(os.getcwd(), 'resources/images/game/nexus.png'),

  44. 'othergrass': os.path.join(os.getcwd(), 'resources/images/game/othergrass.png'),

  45. 'path': os.path.join(os.getcwd(), 'resources/images/game/path.png'),

  46. 'rock': os.path.join(os.getcwd(), 'resources/images/game/rock.png'),

  47. 'tiles': os.path.join(os.getcwd(), 'resources/images/game/tiles.png'),

  48. 'unitfont': os.path.join(os.getcwd(), 'resources/images/game/unitfont.png'),

  49. 'water': os.path.join(os.getcwd(), 'resources/images/game/water.png'),

  50. 'x': os.path.join(os.getcwd(), 'resources/images/game/x.png'),

  51. },

  52. 'pause': {

  53. 'gamepaused': os.path.join(os.getcwd(), 'resources/images/pause/gamepaused.png'),

  54. 'resume_black': os.path.join(os.getcwd(), 'resources/images/pause/resume_black.png'),

  55. 'resume_red': os.path.join(os.getcwd(), 'resources/images/pause/resume_red.png'),

  56. },

  57. 'start': {

  58. 'play_black': os.path.join(os.getcwd(), 'resources/images/start/play_black.png'),

  59. 'play_red': os.path.join(os.getcwd(), 'resources/images/start/play_red.png'),

  60. 'quit_black': os.path.join(os.getcwd(), 'resources/images/start/quit_black.png'),

  61. 'quit_red': os.path.join(os.getcwd(), 'resources/images/start/quit_red.png'),

  62. 'start_interface': os.path.join(os.getcwd(), 'resources/images/start/start_interface.png'),

  63. },

  64. }

  65. '''地图路径'''

  66. MAPPATHS = {

  67. '1': os.path.join(os.getcwd(), 'resources/maps/1.map'),

  68. '2': os.path.join(os.getcwd(), 'resources/maps/2.map'),

  69. '3': os.path.join(os.getcwd(), 'resources/maps/3.map'),

  70. }

  71. '''字体路径'''

  72. FONTPATHS = {

  73. 'Calibri': os.path.join(os.getcwd(), 'resources/fonts/Calibri.ttf'),

  74. 'm04': os.path.join(os.getcwd(), 'resources/fonts/m04.ttf'),

  75. 'Microsoft Sans Serif': os.path.join(os.getcwd(), 'resources/fonts/Microsoft Sans Serif.ttf'),

  76. }

  77. '''不同难度的settings'''

  78. DIFFICULTYPATHS = {

  79. 'easy': os.path.join(os.getcwd(), 'resources/difficulties/easy.json'),

  80. 'hard': os.path.join(os.getcwd(), 'resources/difficulties/hard.json'),

  81. 'medium': os.path.join(os.getcwd(), 'resources/difficulties/medium.json'),

  82. }

游戏源码:

  1. import cfg

  2. import pygame

  3. from modules import *

  4. '''主函数'''

  5. def main():

  6. pygame.init()

  7. pygame.mixer.init()

  8. pygame.mixer.music.load(cfg.AUDIOPATHS['bgm'])

  9. pygame.mixer.music.play(-1, 0.0)

  10. pygame.mixer.music.set_volume(0.25)

  11. screen = pygame.display.set_mode(cfg.SCREENSIZE)

  12. pygame.display.set_caption("塔防游戏 —— 九歌")

  13. # 调用游戏开始界面

  14. start_interface = StartInterface(cfg)

  15. is_play = start_interface.update(screen)

  16. if not is_play:

  17. return

  18. # 调用游戏界面

  19. while True:

  20. choice_interface = ChoiceInterface(cfg)

  21. map_choice, difficulty_choice = choice_interface.update(screen)

  22. game_interface = GamingInterface(cfg)

  23. game_interface.start(screen, map_path=cfg.MAPPATHS[str(map_choice)], difficulty_path=cfg.DIFFICULTYPATHS[str(difficulty_choice)])

  24. end_interface = EndInterface(cfg)

  25. end_interface.update(screen)

  26. '''run'''

  27. if __name__ == '__main__':

  28. main()

3、超级大的迷宫

展示:

首先配置文件的源码:

  1. '''配置文件'''

  2. import os

  3. '''屏幕大小'''

  4. SCREENSIZE = (800, 625)

  5. '''游戏素材'''

  6. BGMPATH = os.path.join(os.getcwd(), 'resources/audios/bgm.mp3')

  7. HEROPICPATH = os.path.join(os.getcwd(), 'resources/images/hero.png')

  8. '''FPS'''

  9. FPS = 20

  10. '''块大小'''

  11. BLOCKSIZE = 15

  12. MAZESIZE = (35, 50) # num_rows * num_cols

  13. BORDERSIZE = (25, 50) # 25 * 2 + 50 * 15 = 800, 50 * 2 + 35 * 15 = 625

游戏源码:

  1. import cfg

  2. import sys

  3. import pygame

  4. from modules import *

  5. '''主函数'''

  6. def main(cfg):

  7. # 初始化

  8. pygame.init()

  9. pygame.mixer.init()

  10. pygame.font.init()

  11. pygame.mixer.music.load(cfg.BGMPATH)

  12. pygame.mixer.music.play(-1, 0.0)

  13. screen = pygame.display.set_mode(cfg.SCREENSIZE)

  14. pygame.display.set_caption('Maze —— 九歌')

  15. font = pygame.font.SysFont('Consolas', 15)

  16. # 开始界面

  17. Interface(screen, cfg, 'game_start')

  18. # 记录关卡数

  19. num_levels = 0

  20. # 记录最少用了多少步通关

  21. best_scores = 'None'

  22. # 关卡循环切换

  23. while True:

  24. num_levels += 1

  25. clock = pygame.time.Clock()

  26. screen = pygame.display.set_mode(cfg.SCREENSIZE)

  27. # --随机生成关卡地图

  28. maze_now = RandomMaze(cfg.MAZESIZE, cfg.BLOCKSIZE, cfg.BORDERSIZE)

  29. # --生成hero

  30. hero_now = Hero(cfg.HEROPICPATH, [0, 0], cfg.BLOCKSIZE, cfg.BORDERSIZE)

  31. # --统计步数

  32. num_steps = 0

  33. # --关卡内主循环

  34. while True:

  35. dt = clock.tick(cfg.FPS)

  36. screen.fill((255, 255, 255))

  37. is_move = False

  38. # ----↑↓←→控制hero

  39. for event in pygame.event.get():

  40. if event.type == pygame.QUIT:

  41. pygame.quit()

  42. sys.exit(-1)

  43. elif event.type == pygame.KEYDOWN:

  44. if event.key == pygame.K_UP:

  45. is_move = hero_now.move('up', maze_now)

  46. elif event.key == pygame.K_DOWN:

  47. is_move = hero_now.move('down', maze_now)

  48. elif event.key == pygame.K_LEFT:

  49. is_move = hero_now.move('left', maze_now)

  50. elif event.key == pygame.K_RIGHT:

  51. is_move = hero_now.move('right', maze_now)

  52. num_steps += int(is_move)

  53. hero_now.draw(screen)

  54. maze_now.draw(screen)

  55. # ----显示一些信息

  56. showText(screen, font, 'LEVELDONE: %d' % num_levels, (255, 0, 0), (10, 10))

  57. showText(screen, font, 'BESTSCORE: %s' % best_scores, (255, 0, 0), (210, 10))

  58. showText(screen, font, 'USEDSTEPS: %s' % num_steps, (255, 0, 0), (410, 10))

  59. showText(screen, font, 'S: your starting point D: your destination', (255, 0, 0), (10, 600))

  60. # ----判断游戏是否胜利

  61. if (hero_now.coordinate[0] == cfg.MAZESIZE[1] - 1) and (hero_now.coordinate[1] == cfg.MAZESIZE[0] - 1):

  62. break

  63. pygame.display.update()

  64. # --更新最优成绩

  65. if best_scores == 'None':

  66. best_scores = num_steps

  67. else:

  68. if best_scores > num_steps:

  69. best_scores = num_steps

  70. # --关卡切换

  71. Interface(screen, cfg, mode='game_switch')

  72. '''run'''

  73. if __name__ == '__main__':

  74. main(cfg)

...未完

太多了,好累呀!

扫下方二维码加老师微信

或是搜索老师微信号:XTUOL1988【切记备注学习Python】

邀您来听Python web开发,Python爬虫,Python数据分析,人工智能 免费精品教程0基础入门到企业项目实战教学!


扫一扫
更多咨询早知道!



欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持


万水千山总是情,点个【在看】行不行

*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜

good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter