大游戏小游戏有千千万万,这些小游戏应该只有90后才玩过和懂吧
儿童节即将到来,虽然秃头程序员没有头发,但是童心还是一直都在的,今天就分享一些私藏的童年游戏,十几行代码就能进入使用Python开发的小游戏快乐玩耍!
使用工具:
Python3.8、pycharm2020
也可以不安装pycharm2020也可以直接运行~但是安装了些会好一点
1.五子棋
源码:
'''游戏开始界面'''class gameStartUI(QWidget):def __init__(self, parent=None, **kwargs):super(gameStartUI, self).__init__(parent)self.setFixedSize(760, 650)self.setWindowTitle('五子棋 —— 九歌')self.setWindowIcon(QIcon(cfg.ICON_FILEPATH))# 背景图片palette = QPalette()palette.setBrush(self.backgroundRole(), QBrush(QPixmap(cfg.BACKGROUND_IMAGEPATHS.get('bg_start'))))self.setPalette(palette)# 按钮# --人机对战self.ai_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('ai'), self)self.ai_button.move(250, 200)self.ai_button.show()self.ai_button.click_signal.connect(self.playWithAI)# --联机对战self.online_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('online'), self)self.online_button.move(250, 350)self.online_button.show()self.online_button.click_signal.connect(self.playOnline)'''人机对战'''def playWithAI(self):self.close()self.gaming_ui = playWithAIUI(cfg)self.gaming_ui.exit_signal.connect(lambda: sys.exit())self.gaming_ui.back_signal.connect(self.show)self.gaming_ui.show()'''联机对战'''def playOnline(self):self.close()self.gaming_ui = playOnlineUI(cfg, self)self.gaming_ui.show()'''run'''if __name__ == '__main__':app = QApplication(sys.argv)handle = gameStartUI()font = QFont()font.setPointSize(12)handle.setFont(font)handle.show()sys.exit(app.exec_())
2.超级玛丽
这个源码超级多多,文件很大很大~
else:breakInterface(screen, cfg, mode='game_end')可以关注公众号:学习py最风sao的方式pygame.display.update()clock.tick(cfg.FPS)if is_win_flag:
3.炸弹人
源码:
'''游戏主程序'''def main(cfg):# 初始化pygame.init()pygame.mixer.init()pygame.mixer.music.load(cfg.BGMPATH)pygame.mixer.music.play(-1, 0.0)screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption('Bomber Man —— 九歌')# 开始界面Interface(screen, cfg, mode='game_start')# 游戏主循环font = pygame.font.SysFont('Consolas', 15)for gamemap_path in cfg.GAMEMAPPATHS:# -地图map_parser = mapParser(gamemap_path, bg_paths=cfg.BACKGROUNDPATHS, wall_path20000s=cfg.WALLPATHS, blocksize=cfg.BLOCKSIZE)# -水果fruit_sprite_group = pygame.sprite.Group()used_spaces = []for i in range(5):coordinate = map_parser.randomGetSpace(used_spaces)used_spaces.append(coordinate)fruit_sprite_group.add(Fruit(random.choice(cfg.FRUITPATHS), coordinate=coordinate, blocksize=cfg.BLOCKSIZE))# -我方Herocoordinate = map_parser.randomGetSpace(used_spaces)used_spaces.append(coordinate)ourhero = Hero(imagepaths=cfg.HEROZELDAPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='ZELDA')# -电脑Heroaihero_sprite_group = pygame.sprite.Group()coordinate = map_parser.randomGetSpace(used_spaces)aihero_sprite_group.add(Hero(imagepaths=cfg.HEROBATMANPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='BATMAN'))used_spaces.append(coordinate)coordinate = map_parser.randomGetSpace(used_spaces)aihero_sprite_group.add(Hero(imagepaths=cfg.HERODKPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='DK'))used_spaces.append(coordinate)# -炸弹bombbomb_sprite_group = pygame.sprite.Group()# -用于判断游戏胜利或者失败的flagis_win_flag = False# -主循环screen = pygame.display.set_mode(map_parser.screen_size)clock = pygame.time.Clock()while True:dt = clock.tick(cfg.FPS)for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit(-1)# --↑↓←→键控制上下左右, 空格键丢炸弹elif event.type == pygame.KEYDOWN:if event.key == pygame.K_UP:ourhero.move('up')elif event.key == pygame.K_DOWN:ourhero.move('down')elif event.key == pygame.K_LEFT:ourhero.move('left')elif event.key == pygame.K_RIGHT:ourhero.move('right')elif event.key == pygame.K_SPACE:if ourhero.bomb_cooling_count <= 0:bomb_sprite_group.add(ourhero.generateBomb(imagepath=cfg.BOMBPATH, digitalcolor=cfg.YELLOW, explode_imagepath=cfg.FIREPATH))screen.fill(cfg.WHITE)# --电脑Hero随机行动for hero in aihero_sprite_group:action, flag = hero.randomAction(dt)if flag and action == 'dropbomb':bomb_sprite_group.add(hero.generateBomb(imagepath=cfg.BOMBPATH, digitalcolor=cfg.YELLOW, explode_imagepath=cfg.FIREPATH))# --吃到水果加生命值(只要是Hero, 都能加)ourhero.eatFruit(fruit_sprite_group)for hero in aihero_sprite_group:hero.eatFruit(fruit_sprite_group)# --游戏元素都绑定到屏幕上map_parser.draw(screen)for bomb in bomb_sprite_group:if not bomb.is_being:bomb_sprite_group.remove(bomb)explode_area = bomb.draw(screen, dt, map_parser)if explode_area:# --爆炸火焰范围内的Hero生命值将持续下降if ourhero.coordinate in explode_area:ourhero.health_value -= bomb.harm_valuefor hero in aihero_sprite_group:if hero.coordinate in explode_area:hero.health_value -= bomb.harm_valuefruit_sprite_group.draw(screen)for hero in aihero_sprite_group:hero.draw(screen, dt)ourhero.draw(screen, dt)# --左上角显示生命值pos_x = showText(screen, font, text=ourhero.hero_name+'(our):'+str(ourhero.health_value), color=cfg.YELLOW, position=[5, 5])for hero in aihero_sprite_group:pos_x, pos_y = pos_x+15, 5pos_x = showText(screen, font, text=hero.hero_name+'(ai):'+str(hero.health_value), color=cfg.YELLOW, position=[pos_x, pos_y])# --我方玩家生命值小于等于0/电脑方玩家生命值均小于等于0则判断游戏结束if ourhero.health_value <= 0:is_win_flag = Falsebreakfor hero in aihero_sprite_group:if hero.health_value <= 0:aihero_sprite_group.remove(hero)if len(aihero_sprite_group) == 0:is_win_flag = Truebreakpygame.display.update()clock.tick(cfg.FPS)if is_win_flag:Interface(screen, cfg, mode='game_switch')else:breakInterface(screen, cfg, mode='game_end')'''run'''if __name__ == '__main__':while True:main(cfg)
4.推箱子
源码:
'''开始游戏'''def startGame(screen):clock = pygame.time.Clock()# 加载字体font = pygame.font.SysFont('arial', 18)if not os.path.isfile('score'):f = open('score', 'w')f.write('0')f.close()with open('score', 'r') as f:highest_score = int(f.read().strip())# 敌方enemies_group = pygame.sprite.Group()for i in range(55):if i < 11:enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)elif i < 33:enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)else:enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)enemy.rect.x = 85 + (i % 11) * 50enemy.rect.y = 120 + (i // 11) * 45enemies_group.add(enemy)boomed_enemies_group = pygame.sprite.Group()en_bullets_group = pygame.sprite.Group()ufo = ufoSprite(color=cfg.RED)# 我方myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)my_bullets_group = pygame.sprite.Group()# 用于控制敌方位置更新# --移动一行enemy_move_count = 24enemy_move_interval = 24enemy_move_flag = False# --改变移动方向(改变方向的同时集体下降一次)enemy_change_direction_count = 0enemy_change_direction_interval = 60enemy_need_down = Falseenemy_move_right = Trueenemy_need_move_row = 6enemy_max_row = 5# 用于控制敌方发射子弹enemy_shot_interval = 100enemy_shot_count = 0enemy_shot_flag = False# 游戏进行中running = Trueis_win = False# 主循环while running:screen.fill(cfg.BLACK)for event in pygame.event.get():# --点右上角的X或者按Esc键退出游戏if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_ESCAPE:pygame.quit()sys.exit()# --射击if event.type == pygame.MOUSEBUTTONDOWN:my_bullet = myaircraft.shot()if my_bullet:my_bullets_group.add(my_bullet)# --我方子弹与敌方/UFO碰撞检测for enemy in enemies_group:if pygame.sprite.spritecollide(enemy, my_bullets_group, True, None):boomed_enemies_group.add(enemy)enemies_group.remove(enemy)myaircraft.score += enemy.rewardif pygame.sprite.spritecollide(ufo, my_bullets_group, True, None):ufo.is_dead = Truemyaircraft.score += ufo.reward# --更新并画敌方# ----敌方子弹enemy_shot_count += 1if enemy_shot_count > enemy_shot_interval:enemy_shot_flag = Trueenemies_survive_list = [enemy.number for enemy in enemies_group]shot_number = random.choice(enemies_survive_list)enemy_shot_count = 0# ----敌方移动enemy_move_count += 1if enemy_move_count > enemy_move_interval:enemy_move_count = 0enemy_move_flag = Trueenemy_need_move_row -= 1if enemy_need_move_row == 0:enemy_need_move_row = enemy_max_rowenemy_change_direction_count += 1if enemy_change_direction_count > enemy_change_direction_interval:enemy_change_direction_count = 1enemy_move_right = not enemy_move_rightenemy_need_down = True# ----每次下降提高移动和射击速度enemy_move_interval = max(15, enemy_move_interval-3)enemy_shot_interval = max(50, enemy_move_interval-10)# ----遍历更新for enemy in enemies_group:if enemy_shot_flag:if enemy.number == shot_number:en_bullet = enemy.shot()en_bullets_group.add(en_bullet)if enemy_move_flag:if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):if enemy_move_right:enemy.update('right', cfg.SCREENSIZE[1])else:enemy.update('left', cfg.SCREENSIZE[1])else:enemy.update(None, cfg.SCREENSIZE[1])if enemy_need_down:if enemy.update('down', cfg.SCREENSIZE[1]):running = Falseis_win = Falseenemy.change_count -= 1enemy.draw(screen)enemy_move_flag = Falseenemy_need_down = Falseenemy_shot_flag = False# ----敌方爆炸特效for boomed_enemy in boomed_enemies_group:if boomed_enemy.boom(screen):boomed_enemies_group.remove(boomed_enemy)del boomed_enemy# --敌方子弹与我方飞船碰撞检测if not myaircraft.one_dead:if pygame.sprite.spritecollide(myaircraft, en_bullets_group, True, None):myaircraft.one_dead = Trueif myaircraft.one_dead:if myaircraft.boom(screen):myaircraft.resetBoom()myaircraft.num_life -= 1if myaircraft.num_life < 1:running = Falseis_win = Falseelse:# ----更新飞船myaircraft.update(cfg.SCREENSIZE[0])# ----画飞船myaircraft.draw(screen)if (not ufo.has_boomed) and (ufo.is_dead):if ufo.boom(screen):ufo.has_boomed = Trueelse:# ----更新UFOufo.update(cfg.SCREENSIZE[0])# ----画UFOufo.draw(screen)# --画我方飞船子弹for bullet in my_bullets_group:if bullet.update():my_bullets_group.remove(bullet)del bulletelse:bullet.draw(screen)# --画敌方子弹for bullet in en_bullets_group:if bullet.update(cfg.SCREENSIZE[1]):en_bullets_group.remove(bullet)del bulletelse:bullet.draw(screen)if myaircraft.score > highest_score:highest_score = myaircraft.score# --得分每增加2000我方飞船增加一条生命if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old_score):myaircraft.old_score = myaircraft.scoremyaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)# --敌人都死光了的话就胜利了if len(enemies_group) < 1:is_win = Truerunning = False# --显示文字# ----当前得分showText(screen, 'SCORE: ', cfg.WHITE, font, 200, 8)showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)# ----敌人数量showText(screen, 'ENEMY: ', cfg.WHITE, font, 370, 8)showText(screen, str(len(enemies_group)), cfg.WHITE, font, 370, 24)# ----历史最高分showText(screen, 'HIGHEST: ', cfg.WHITE, font, 540, 8)showText(screen, str(highest_score), cfg.WHITE, font, 540, 24)# ----FPSshowText(screen, 'FPS: ' + str(int(clock.get_fps())), cfg.RED, font, 8, 8)# --显示剩余生命值showLife(screen, myaircraft.num_life, cfg.GREEN)pygame.display.update()clock.tick(cfg.FPS)with open('score', 'w') as f:f.write(str(highest_score))return is_win'''主函数'''def main():# 初始化pygame.init()pygame.display.set_caption('外星人入侵 —— 九歌')screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.mixer.init()pygame.mixer.music.load(cfg.BGMPATH)pygame.mixer.music.set_volume(0.4)pygame.mixer.music.play(-1)while True:is_win = startGame(screen)endInterface(screen, cfg.BLACK, is_win)'''run'''if __name__ == '__main__':main()
5.扫雷
上学时恨不得一直待在电脑房玩这个游戏,哈哈哈
第二种AI贪吃蛇
经典游戏俄罗斯方块
太多了就不一一展示啦