当前位置:   article > 正文

python简单易懂的小程序,python有趣小程序代码

python简单易懂的小程序,python有趣小程序代码

本篇文章给大家谈谈python简单易懂的小程序,以及python有趣小程序代码,希望对各位有所帮助,不要忘了收藏本站喔。

Source code download: 本文相关源码

本篇文章给大家谈谈python200行有趣小程序,以及python简单小游戏代码,希望对各位有所帮助,不要忘了收藏本站喔。

来源丨网络

经常听到有朋友说,学习编程是一件非常枯燥无味的事情python画流程图。其实,大家有没有认真想过,可能是我们的学习方法不对?

比方说,你有没有想过,可以通过打游戏来学编程?

今天我想跟大家分享几个Python小游戏,教你如何通过边打游戏边学编程!

1、吃金币

6501d1eda6632afbf7b7bfb22c8cd549.gif

源码分享:

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

2、打乒乓

0a1d997ff25fd8c5262bb2e42da4512c.gif

源码分享:

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

3、滑雪

090eb1677027e16c2ba43bc14b33ad09.gif

源码分享:

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

4、并夕夕版飞机大战

e1f301f3d32b400f21079213a9955367.gif

源码分享:

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

5、打地鼠

源码分享:

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

6、小恐龙

玩法:上下控制起跳躲避

源码分享:

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

7、消消乐

玩法:三个相连就能消除

2346bb7b31c128541a301673498266eb.gif

源码分享:

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

8、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的AI同义句转换好用的句子同义替换软件

1c835b0ed82df8a18e65747d62c350a2.gif

源码分享:

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

9、贪吃蛇

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

源码分享:

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

10、24点小游戏

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

b6cc28a28344a417169d80cf201f9d12.gif

源码分享:

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

11、平衡木

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

源码分享:

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

12、外星人入侵

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

b3da8fbbd2fcadd1cc6cc202ce8e02f7.gif

源码分享:

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

13、井字棋888

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

源码分享

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

万水千山总是情,点个 

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