作者 :“程序员梨子”
**文章简介 **:本篇文章主要是写了Pygame的合集系列六个游戏都有源码啦~
**文章源码免费获取 : 为了感谢每一个关注我的小可爱每篇文章的项目源码都是无
偿分享滴
点这里蓝色这行字体自取,需要什么源码记得说标题名字哈!私信我也可!
欢迎小伙伴们 点赞、收藏⭐、留言
过了2000年后,PC与各类主机逐渐兴起,街机店纷纷倒闭,到目前为止街机已经基本灭绝。现在
只能在一些大型电玩城里才能看到街机的身影了,可是这类场所的消费一般都比较高,这也导致很
多00后的小朋友甚至根本就没玩过街机。
今天就小编来说一说当年你最喜欢玩的6款游戏叭,一起来回味一下吧!
(顺便说下:这个系列都是有完整的素材跟源码的哦,需要的找我啦)
被认为是80年代最经典的街机游戏之一,也是最受大家欢迎的。游戏的主角小精灵的形象甚至被作
为一种大众文化符号。
import sys
import cfg
import pygame
import modules.Levels as Levels
'''开始某一关游戏'''
def startLevelGame(level, screen, font):
clock = pygame.time.Clock()
SCORE = 0
wall_sprites = level.setupWalls(cfg.SKYBLUE)
gate_sprites = level.setupGate(cfg.WHITE)
hero_sprites, ghost_sprites = level.setupPlayers(cfg.HEROPATH, [cfg.BlinkyPATH, cfg.ClydePATH, cfg.InkyPATH, cfg.PinkyPATH])
food_sprites = level.setupFood(cfg.YELLOW, cfg.WHITE)
is_clearance = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(-1)
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
for hero in hero_sprites:
hero.changeSpeed([-1, 0])
hero.is_move = True
elif event.key == pygame.K_RIGHT:
for hero in hero_sprites:
hero.changeSpeed([1, 0])
hero.is_move = True
elif event.key == pygame.K_UP:
for hero in hero_sprites:
hero.changeSpeed([0, -1])
hero.is_move = True
elif event.key == pygame.K_DOWN:
for hero in hero_sprites:
hero.changeSpeed([0, 1])
hero.is_move = True
if event.type == pygame.KEYUP:
if (event.key == pygame.K_LEFT) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_UP) or (event.key == pygame.K_DOWN):
hero.is_move = False
screen.fill(cfg.BLACK)
for hero in hero_sprites:
hero.update(wall_sprites, gate_sprites)
hero_sprites.draw(screen)
for hero in hero_sprites:
food_eaten = pygame.sprite.spritecollide(hero, food_sprites, True)
SCORE += len(food_eaten)
wall_sprites.draw(screen)
gate_sprites.draw(screen)
food_sprites.draw(screen)
for ghost in ghost_sprites:
# 幽灵随机运动(效果不好且有BUG)
'''
res = ghost.update(wall_sprites, None)
while not res:
ghost.changeSpeed(ghost.randomDirection())
res = ghost.update(wall_sprites, None)
'''
# 指定幽灵运动路径
if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
ghost.tracks_loc[1] += 1
else:
if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
ghost.tracks_loc[0] += 1
elif ghost.role_name == 'Clyde':
ghost.tracks_loc[0] = 2
else:
ghost.tracks_loc[0] = 0
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
ghost.tracks_loc[1] = 0
if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
else:
if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
loc0 = ghost.tracks_loc[0] + 1
elif ghost.role_name == 'Clyde':
loc0 = 2
else:
loc0 = 0
ghost.changeSpeed(ghost.tracks[loc0][0: 2])
ghost.update(wall_sprites, None)
ghost_sprites.draw(screen)
score_text = font.render("Score: %s" % SCORE, True, cfg.RED)
screen.blit(score_text, [10, 10])
if len(food_sprites) == 0:
is_clearance = True
break
if pygame.sprite.groupcollide(hero_sprites, ghost_sprites, False, False):
is_clearance = False
break
pygame.display.flip()
clock.tick(10)
return is_clearance
'''显示文字'''
def showText(screen, font, is_clearance, flag=False):
clock = pygame.time.Clock()
msg = 'Game Over!' if not is_clearance else 'Congratulations, you won!'
positions = [[235, 233], [65, 303], [170, 333]] if not is_clearance else [[145, 233], [65, 303], [170, 333]]
surface = pygame.Surface((400, 200))
surface.set_alpha(10)
surface.fill((128, 128, 128))
screen.blit(surface, (100, 200))
texts = [font.render(msg, True, cfg.WHITE),
font.render('Press ENTER to continue or play again.', True, cfg.WHITE),
font.render('Press ESCAPE to quit.', True, cfg.WHITE)]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if is_clearance:
if not flag:
return
else:
main(initialize())
else:
main(initialize())
elif event.key == pygame.K_ESCAPE:
sys.exit()
pygame.quit()
for idx, (text, position) in enumerate(zip(texts, positions)):
screen.blit(text, position)
pygame.display.flip()
clock.tick(10)
'''初始化'''
def initialize():
pygame.init()
icon_image = pygame.image.load(cfg.ICONPATH)
pygame.display.set_icon(icon_image)
screen = pygame.display.set_mode([606, 606])
pygame.display.set_caption('吃豆豆小游戏')
return screen
'''主函数'''
def main(screen):
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1, 0.0)
pygame.font.init()
font_small = pygame.font.Font(cfg.FONTPATH, 18)
font_big = pygame.font.Font(cfg.FONTPATH, 24)
for num_level in range(1, Levels.NUMLEVELS+1):
level = getattr(Levels, f'Level{num_level}')()
is_clearance = startLevelGame(level, screen, font_small)
if num_level == Levels.NUMLEVELS:
showText(screen, font_big, is_clearance, True)
else:
showText(screen, font_big, is_clearance)
'''run'''
if __name__ == '__main__':
main(initialize())
《魂斗罗》魂斗罗的故事背景是根据著名恐怖片《异形(Alien)》改编,人物原型来源于著名影星施
瓦辛格和史泰龙。1987年第一款魂斗罗诞生在名为Jamma的街机上。“魂斗罗”的含义是“具有优秀
战斗能力和素质的人”,它是赋予最强战士的称呼。
这部游戏最好玩的地方,莫过于极其丰富的战斗场景、怪物类型、弹药强化,合作模式更是超神一
般的体验,至今还在80后心中留下了许多传说。
import pygame
import sys
from pygame.locals import *
from settings import Settings
from game_player import Game_Player
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameStats
from game_boss import Game_Boss
from button import Button
def run_game():
bg = pygame.image.load("图片/map01.jpeg")
game_settings = Settings()
pos_x = 0#地图移动o
pygame.init()
screen = pygame.display.set_mode(
(game_settings.screen_width,game_settings.screen_height))
pygame.display.set_caption("经典像素风游戏——魂斗罗")
stats = GameStats(game_settings)
player = Game_Player(game_settings,screen)
bullets = Group()
boss = Group()
enemys = Group()
win_button = Button(game_settings,screen,"YOU WIN")
gf.create_legion(game_settings,screen,enemys)
gf.create_boss(game_settings,screen,player,boss)
while True:
pygame.mouse.set_visible(False)
gf.check_events(game_settings,screen,player,bullets)
gf.update_player(game_settings,stats,player,enemys)
gf.update_bullet(game_settings,bullets,screen,enemys,boss)
gf.update_enemys(game_settings,enemys)
gf.update_boss(game_settings,boss)
gf.update_screen(game_settings,bg,pos_x,screen,player,bullets,enemys,boss,win_button)
if player.moving_right and player.center > player.screen_rect.centerx and game_settings.boss_appear == False:
game_settings.screen_rolling = True
pos_x -= 5#屏幕滚动速度
else:
game_settings.screen_rolling = False
run_game()
马里奥的出道可以追溯到1981年的街机游戏《大金刚》,那时还没有马里奥这个名字,只是单纯
地将他设定为一个意大利人角色。当游戏《大金刚》被拿到美国任天堂分部的时候,公司员工发现
在有一个在仓库中工作的工人Mario,相貌和动作酷似游戏中的“跳跃人”,于是“马里奥”也就成了这
个明星角色的正式名字。
帽子加背带工作服、大鼻子和胡子等特征,离英雄的形象相差甚远。再加上少许肥胖的身材,稍不
留神可能就会把我们的英雄马里奥当成在便利店打工的中年大叔。
#!/usr/bin/env python
__author__ = '超级玛丽-源码基地'
"""
This is an attempt to recreate the first level of
Super Mario Bros for the NES.
"""
import sys
import pygame as pg
from data.main import main
import cProfile
if __name__=='__main__':
main()
pg.quit()
sys.exit()
《坦克大战》里的地形包括砖墙、海水、钢板、森林、地板5种。敌方的种类则包括装甲车、轻型
坦克、反坦克炮、重型坦克4种。
有时候还能打出各种协助武器,比如说手雷、时钟等。不知道可有哪位无耻的玩家每次都会将自己
的“老巢”设成钢板乌龟壳,刀枪不入,躺着赢得胜利?
'''
Function:
经典坦克大战小游戏
'''
import os
import cfg
import pygame
from modules import *
'''主函数'''
def main(cfg):
# 游戏初始化
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
pygame.display.set_caption(cfg.TITLE)
# 加载游戏素材
sounds = {}
for key, value in cfg.AUDIO_PATHS.items():
sounds[key] = pygame.mixer.Sound(value)
sounds[key].set_volume(1)
# 开始界面
is_dual_mode = gameStartInterface(screen, cfg)
# 关卡数
levelfilepaths = [os.path.join(cfg.LEVELFILEDIR, filename) for filename in sorted(os.listdir(cfg.LEVELFILEDIR))]
# 主循环
for idx, levelfilepath in enumerate(levelfilepaths):
switchLevelIterface(screen, cfg, idx+1)
game_level = GameLevel(idx+1, levelfilepath, sounds, is_dual_mode, cfg)
is_win = game_level.start(screen)
if not is_win: break
is_quit_game = gameEndIterface(screen, cfg, is_win)
return is_quit_game
'''run'''
if __name__ == '__main__':
while True:
is_quit_game = main(cfg)
if is_quit_game:
break
五、《植物大战僵尸》小游戏
《植物大战僵尸》相信大家一定不陌生,不知道曾经有多少人曾经沉浸在打僵尸、种太阳的乐趣中
难以自拔。
'''
'''
import pygame,sys
from peashooter import peaShooter
from setting import Setting
class PvsZ(object):
''' 1.mian() 函数 '''
def main(self):
# 1.1设置标题
pygame.display.set_caption("植物大战僵尸")
# 1.2 死循环
while True:
# 1.4 业务逻辑执行
self.action()
# 1.5 绘制图形
self.paint()
# 1.3 刷新屏幕
pygame.display.update()
''' 2. action() '''
def action(self):
# 2.1 事件迭代监听
for event in pygame.event.get():
# 2.2 退出
if event.type == pygame.QUIT:
sys.exit()
# 2.3 鼠标监听
if event.type == pygame.MOUSEBUTTONDOWN:
# 2.4获取鼠标信息
mouseX, mouseY = pygame.mouse.get_pos()
# 2.5 获取鼠标点击
leftFlag = pygame.mouse.get_pressed()[0]
for i in range(10):
if leftFlag and 100< mouseX < 250\
and 100 < mouseY <250:
# 2.8 制定区域创建豌豆对象
self.peashooter.append(peaShooter(self.screen, self.peaImage, 200+i*50, 200+i*50))
# 2.9 设置图片集转换值
self.index = 0
self.change()
# 变化业务逻辑执行
def change(self):
for pea in self.peashooter:
pea.change()
''' 3. paint()'''
def paint(self):
# 3.1绘制背景图片
self.screen.blit(pygame.transform.scale(self.background, (1200, 600)),(0, 0))
self.paintPeashooter()
# 画豌豆
def paintPeashooter(self):
for pea in self.peashooter:
pea.blitMe()
''' 4. init() '''
def __init__(self):
# 4.1 背景
self.screen = pygame.display.set_mode((906, 601),0,0)
self.sets = Setting()
# 4.2 背景图
self.background = self.sets.background
# 创建豌豆对象
self.peaImage = self.sets.getPlantsImage(7, "peashooter", "idle")
self.peashooter = []
if __name__ == '__main__':
pvsz = PvsZ()
pvsz.main()
六、《打地鼠》小游戏
一只只调皮的小地鼠时不时的从地洞里面冒出小脑袋,它这是挑衅,你要一锤一锤的把它闷在地洞
中。游戏要求在限定时间内,敲打的地鼠越多,分数才越高。
不要以为游戏很简单,其实难度还是很高的,不光要玩家快速不停地打,还要灵活利用游戏场景内
的各种道具才能快速提高分数,只有这样才能进入下一关。打地鼠游戏最大的核心是考验玩家判断
力,而最恶心的是你最后总也搞不赢。
'''
Function:
打地鼠(Whac-A-Mole)小游戏
源码基地:#806965976#
公众号:Python顾木子吖
'''
import cfg
import sys
import pygame
import random
from modules import *
'''游戏初始化'''
def initGame():
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('打地鼠')
return screen
'''主函数'''
def main():
# 初始化
screen = initGame()
# 加载背景音乐和其他音效
pygame.mixer.music.load(cfg.BGM_PATH)
pygame.mixer.music.play(-1)
audios = {
'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
}
# 加载字体
font = pygame.font.Font(cfg.FONT_PATH, 40)
# 加载背景图片
bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
# 开始界面
startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
# 地鼠改变位置的计时
hole_pos = random.choice(cfg.HOLE_POSITIONS)
change_hole_event = pygame.USEREVENT
pygame.time.set_timer(change_hole_event, 800)
# 地鼠
mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
# 锤子
hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
# 时钟
clock = pygame.time.Clock()
# 分数
your_score = 0
flag = False
# 初始时间
init_time = pygame.time.get_ticks()
# 游戏主循环
while True:
# --游戏时间为60s
time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
# --游戏时间减少, 地鼠变位置速度变快
if time_remain == 40 and not flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 650)
flag = True
elif time_remain == 20 and flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 500)
flag = False
# --倒计时音效
if time_remain == 10:
audios['count_down'].play()
# --游戏结束
if time_remain < 0: break
count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
# --按键检测
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEMOTION:
hammer.setPosition(pygame.mouse.get_pos())
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
hammer.setHammering()
elif event.type == change_hole_event:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
# --碰撞检测
if hammer.is_hammering and not mole.is_hammer:
is_hammer = pygame.sprite.collide_mask(hammer, mole)
if is_hammer:
audios['hammering'].play()
mole.setBeHammered()
your_score += 10
# --分数
your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
# --绑定必要的游戏元素到屏幕(注意顺序)
screen.blit(bg_img, (0, 0))
screen.blit(count_down_text, (875, 8))
screen.blit(your_score_text, (800, 430))
mole.draw(screen)
hammer.draw(screen)
# --更新
pygame.display.flip()
clock.tick(60)
# 读取最佳分数(try块避免第一次游戏无.rec文件)
try:
best_score = int(open(cfg.RECORD_PATH).read())
except:
best_score = 0
# 若当前分数大于最佳分数则更新最佳分数
if your_score > best_score:
f = open(cfg.RECORD_PATH, 'w')
f.write(str(your_score))
f.close()
# 结束界面
score_info = {'your_score': your_score, 'best_score': best_score}
is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
return is_restart
'''run'''
if __name__ == '__main__':
while True:
is_restart = main()
if not is_restart:
break
小伙伴们,上面的六种童年游戏,你玩过几种呢?
有你喜欢的游戏记得三联哦~阅读关注多的话就继续更新这个系列游戏啦!
安啦!文章就写到这里,你们的支持是我最大的动力,记得三连哦!
关注小编获取更多精彩内容!记得点击传送门哈
记得三连哦! 如需打包好的完整源码+素材免费分享滴!!!传送门