13个有趣又好玩的python游戏代码分享大全,python最简单游戏代码

13个有趣又好玩的python游戏代码分享大全,python最简单游戏代码,13个有趣又好玩的Python游戏代码分享

今天小编跟大家分享13个有趣又好玩的计算机编程语言小游戏示例代码,教你如何通过边打游戏边学编程!感兴趣的小伙伴快跟随小编一起学习起来

目录

1、吃金币2、打乒乓3、滑雪4、并夕夕版飞机大战5、打地鼠6、小恐龙7、消消乐8、俄罗斯方块9、贪吃蛇10、24点小游戏11、平衡木12、外星人入侵13、井字棋888经常听到有朋友说,学习编程是一件非常枯燥无味的事情。其实,大家有没有认真想过,可能是我们的学习方法不对?

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

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

1、吃金币

源码分享:

导入操作系统

导入稳频发电机(发生器)(constant frequency generator的缩写)

导入系统

导入pygame

随机导入

从模块导入*

'''游戏初始化'''

def initGame():

# 初始化pygame,设置展示窗口

pygame.init()

屏幕=py游戏。展示。设置模式(CFG .屏幕尺寸)

pygame.display.set_caption('抓硬币——九歌)

# 加载必要的游戏素材

game_images={}

对于关键字,以稳频发电机(发生器)(constant frequency generator的缩写)表示的值IMAGE_PATHS.items():

if isinstance(value,list):

图像=[]

对于值中的项目:图片。追加(py游戏。形象。负载(项目))

game_images[key]=图像

否则:

game _ images[key]=py game。形象。负载(值)

game_sounds={}

对于关键字,以稳频发电机(发生器)(constant frequency generator的缩写)表示的值AUDIO _ PATHS.items():

if key=='bgm ':继续

游戏_声音[键]=py游戏。搅拌机。声音(值)

# 返回初始化数据

返回屏幕,游戏图像,游戏声音

'''主函数'''

def main():

# 初始化

screen,game_images,game_sounds=initGame()

# 播放背景音乐

pygame.mixer.music.load(cfg .音频路径['bgm'])

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

# 字体加载

font=pygame.font.Font(cfg .FONT_PATH,40)

# 定义英雄

hero=Hero(game_images['hero'],position=(375,520))

# 定义食物组

food _ sprites _ group=py游戏。雪碧。群组()

generate _ food _ freq=随机。randint(10,20)

生成_食物_计数=0

# 当前分数/历史最高分

分数=0

最高分=0如果不是操作系统路径存在(cfg .最高分数记录文件路径)else int(open(CFG .最高分记录文件路径)。read())

# 游戏主循环

clock=pygame.time.Clock()

虽然正确:

# - 填充背景

screen.fill(0)

屏幕。blit(game _ images[' background '],(0,0))

# - 倒计时信息

Count down _ text=' Count down:' str((90000-py游戏。时间。get _ ticks())//60000)':' str((90000-py游戏。时间。get _ ticks())//1000% 60).零填充(2)

向下计数_ text=font。render(count down _ text,True,(0,0,0))

count down _ rect=向下计数_ text。get _ rect()

countdown_rect.topright=[cfg .屏幕大小[0]-30,5]

screen.blit(countdown_text,countdown_rect)

# - 按键检测

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit()

游戏。钥匙。get _ pressed()

如果按下[pygame .K_a]或按键pygame .K_LEFT]:

hero.move(cfg .屏幕大小,"左")

如果按下[pygame .K_d]或按下[pygame .K_RIGHT]:

hero.move(cfg .屏幕大小,"右")

# - 随机生成食物

生成_食物_计数=1

如果生成_食物_计数生成_食品_频率:

generate _ food _ freq=随机。randint(10,20)

生成_食物_计数=0

food=Food(game_images,random.choice(['gold ',] * 10 ['apple']),cfg .屏幕尺寸)

food_sprites_group.add(食品)

# - 更新食物

对于食物_烈酒_团体中的食物:

如果食物。update():food _ sprites _ group。移走(食物)

# - 碰撞检测

对于食物_烈酒_团体中的食物:

如果pygame.sprite.collide_mask(食物,英雄):

游戏_声音['get'].播放()

food_sprites_group.remove(食品)

得分=食物。得分

如果分数最高_分数:最高_分数=分数

# - 画英雄

hero.draw(屏幕)

# - 画食物

food_sprites_group.draw(屏幕)

# - 显示得分

score_text=f '分数:{score},最高:{最高分} '

score _ text=font。render(score _ text,True,(0,0,0))

score_rect=score_text.get_rect()

score_rect.topleft=[5,5]

screen.blit(score_text,score_rect)

# - 判断游戏是否结束

如果pygame.time.get_ticks()=90000:

破裂

# - 更新屏幕

pygame.display.flip()

clock.tick(cfg .FPS)

# 游戏结束,记录最高分并显示游戏结束画面

fp=打开(cfg .最高分数记录文件路径,' w ')

fp.write(字符串(最高分数))

fp.close()

返回showEndGameInterface(屏幕,配置,分数,最高分数)

'''跑' ' '

if __name__=='__main__ ':

while main():

及格

2、打乒乓

源码分享:

导入系统

导入稳频发电机(发生器)(constant frequency generator的缩写)

导入pygame

从模块导入*

'''定义按钮'''

极好的按钮(屏幕,位置,文本,button_size=(200,50)):

左侧,顶部=位置

bwidth,bheight=button_size

pygame.draw.line(screen,(150,150,150),(left,top),(left bwidth,top),5)

pygame.draw.line(屏幕,(150,150,150),(左,顶部2),(左,顶部高度),5)

pygame.draw.line(screen,(50,50,50),(左侧,顶部BH高度),(左侧bwidth,顶部BH高度),5)

pygame.draw.line(screen,(50,50,50),(left bwidth,top bheight),(left bwidth,top),5)

pygame.draw.rect(screen,(100,100,100),(left,top,bwidth,bheight))

font=pygame.font.Font(cfg .FONTPATH,30岁岁)

text_render=font.render(text,1,(255,235,205))

return screen.blit(text_render,(左50,前10))

'''

功能:

开始界面

输入:

-屏幕:游戏界面

返回:

- game_mode: 1(单人模式)/2(双人模式)

'''

定义开始界面(屏幕):

clock=pygame.time.Clock()

虽然正确:

screen.fill((41,36,33))

button_1=按钮(屏幕,(150,175),'1个玩家)

button_2=按钮(屏幕,(150,275),'2个玩家)

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit()

if event.type==pygame .鼠标按钮按下:

如果button _ 1。碰撞点(py游戏。老鼠。get _ pos()):

返回一

elif按钮_ 2。碰撞点(py游戏。老鼠。get _ pos()):

返回2

时钟。滴答(10)

pygame.display.update()

'''结束界面'''

定义结束接口(屏幕,左分数,右分数):

clock=pygame.time.Clock()

font1=pygame.font.Font(cfg .FONTPATH,30岁岁)

font2=pygame.font.Font(cfg .FONTPATH,20)

msg='左边的玩家赢了!'if score_left score_right else右边的玩家赢了!'

texts=[font1.render(msg,True,cfg .白色),

font2.render('按逃跑退出。真的,cfg .白色),

font2.render('按回车键继续或再次播放。',真的,cfg .白色)]

位置=[[120,200],[155,270],[80,300]]

虽然正确:

screen.fill((41,36,33))

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit()

if event.type==pygame .按键:

if event.key==pygame .k _返回:

返回

elif event.key==pygame .K_ESCAPE:

sys.exit()

pygame.quit()

对于文本,以活力格式发布(文本、位置):

screen.blit(文本、位置)

时钟。滴答(10)

pygame.display.update()

'''运行游戏''演示'''

def runDemo(屏幕):

# 加载游戏素材

hit _ sound=py游戏。搅拌机。声音(CFG .HITSOUNDPATH)

goal _ sound=py游戏。搅拌机。声音(CFG .GOALSOUNDPATH)

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

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

font=pygame.font.Font(cfg .FONTPATH,50岁岁)

# 开始界面

游戏模式=开始界面(屏幕)

# 游戏主循环

# - 左边球拍(ws控制,仅双人模式时可控制)

score_left=0

球拍_左=球拍(cfg .球拍路径,'左,cfg)

# - 右边球拍(控制)

score_right=0

球拍_右=球拍(cfg .“球拍路径”右,cfg)

# - 球

球=球(cfg .圆珠笔路径,cfg)

clock=pygame.time.Clock()

虽然正确:

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit(-1)

screen.fill((41,36,33))

# 玩家操作

按下的键=py游戏。钥匙。get _ pressed()

如果按下_keys[pygame .K_UP]:

球拍_右移('向上)

elif pressed_keys[pygame .K_DOWN]:

球拍_右移('下)

如果游戏模式==2:

如果按下_keys[pygame .K_w]:

球拍_left.move('UP ')

elif pressed_keys[pygame .K_s]:

球拍_向左移动('向下)

否则:

球拍_左。自动移动(球)

# 球运动

分数=ball.move(球,球拍_左,球拍_右,击球_声音,进球_声音)

score_left=scores[0]

score_right=scores[1]

# 显示

# - 分隔线

pygame.draw.rect(screen,cfg .白色,(247,0,6,500))

# - 球

ball.draw(屏幕)

# - 拍

球拍_left.draw(屏幕)

球拍_right.draw(屏幕)

# - 得分

屏幕。blit(字体。render(str(score _ left),False,cfg .白色),(150,10))

屏幕。blit(字体。render(str(score _ right),False,cfg .白色),(300,10))

如果score_left==11或score_right==11:

返回得分_左,得分_右

clock.tick(100)

pygame.display.update()

'''主函数'''

def main():

# 初始化

pygame.init()

pygame.mixer.init()

屏幕=py游戏。展示。set _ mode((CFG .宽度,cfg .高度))

py游戏。展示。set _ caption('乒乓——九歌)

# 开始游戏

虽然正确:

score_left,score_right=runDemo(屏幕)

endInterface(screen,score_left,score_right)

'''跑' ' '

if __name__=='__main__ ':

主()

3、滑雪

源码分享:

导入系统

导入稳频发电机(发生器)(constant frequency generator的缩写)

导入pygame

随机导入

'''滑雪者类'''

班级滑雪者Class(pygame.sprite.Sprite):

def __init__(self):

py游戏。雪碧。雪碧。_ _ init _ _(self)

# 滑雪者的朝向(-2到2)

自我方向=0

self.imagepaths=cfg .滑雪者_图像_路径[:-1]

自我。image=pygame。形象。加载(自身。图像路径[自我。方向])

self.rect=self.image.get_rect()

self.rect.center=[320,100]

自我速度=[自我方向,6-abs(自我方向)*2]

'''改变滑雪者的朝向。负数为向左,正数为向右,0为向前'''

定义转弯(自身,数字):

自我方向=数字

self.direction=max(-2,自我方向)

self.direction=min(2,自我方向)

中心=自身矩形中心

自我。image=pygame。形象。加载(自身。图像路径[自我。方向])

self.rect=self.image.get_rect()

自身直角中心=中心

自我速度=[自我方向,6-abs(自我方向)*2]

返回自身速度

'''移动滑雪者'''

定义移动(自身):

自我。直肠。centex=self。速度[0]

自我。直肠。centex=max(20,self。直肠。centex)

自我。直肠。centex=min(620,self。直肠。centex)

'''设置为摔倒状态'''

def setFall(自身):

自我。image=py游戏。形象。负载(CFG .滑雪者_图像_路径[-1])

'''设置为站立状态'''

定义设置前进(自身):

自我方向=0

自我。image=pygame。形象。加载(自身。图像路径[自我。方向])

'''

功能:

障碍物类

输入:

img_path:障碍物图片路径

位置:障碍物位置

属性:障碍物类别属性

'''

类障碍类(py游戏。雪碧。雪碧):

def __init__(self,img_path,location,attribute):

py游戏。雪碧。雪碧。_ _ init _ _(self)

self.img_path=img_path

自我。image=py游戏。形象。加载(自身。img _ path)

自我定位=位置

self.rect=self.image.get_rect()

自身直角中心=自我定位

自我属性=属性

self.passed=False

'''移动'''

定义移动(自身,数量):

自我。直肠。centey=自我。位置[1]-编号

'''创建障碍物'''

极好的创建障碍(s,e,num=10):

障碍物=pygame.sprite.Group()

位置=[]

对于范围内的我(数量):

row=random.randint(s,e)

col=random.randint(0,9)

location=[col*64 20,row*64 20]

如果位置不在位置中:

位置。追加(位置)

属性=随机。选择(列表(CFG .障碍物_路径。钥匙()))

img_path=cfg .障碍物_路径[属性]

障碍物=ObstacleClass(img_path,location,attribute)

障碍物。添加(障碍物)

返回障碍

'''合并障碍物'''

极好的添加障碍物(障碍物0,障碍物1):

障碍物=pygame.sprite.Group()

对于障碍物中的障碍物0:

障碍物。添加(障碍物)

对于障碍物一中的障碍物:

障碍物。添加(障碍物)

返回障碍

'''显示游戏开始界面'''

def ShowStartInterface(屏幕,屏幕大小):

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

tfont=pygame.font.Font(cfg .FONTPATH,screensize[0]//5)

cfont=pygame.font.Font(cfg .FONTPATH,screensize[0]//20)

title=tfont.render(u '滑雪游戏,真,(255,0,0))

content=cfont.render(u '按任意键开始游戏,True,(0,0,255))

trect=title.get_rect()

trect.midtop=(屏幕大小[0]/2,屏幕大小[1]/5)

crect=content.get_rect()

crect.midtop=(屏幕大小[0]/2,屏幕大小[1]/2)

screen.blit(title,trect)

screen.blit(content,crect)

虽然正确:

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit()

elif event.type==pygame .按键:

返回

pygame.display.update()

'''显示分数'''

def showScore(screen,Score,pos=(10,10)):

font=pygame.font.Font(cfg .FONTPATH,30岁岁)

Score _ text=font。render(' Score:% s ' % Score,True,(0,0,0))

screen.blit(score_text,pos)

'''更新当前帧的游戏画面'''

定义updateFrame(屏幕、障碍物、滑雪者、比分):

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

障碍物。绘制(屏幕)

screen.blit(skier.image,skier.rect)

显示分数(屏幕,分数)

pygame.display.update()

'''主程序'''

def main():

# 游戏初始化

pygame.init()

pygame.mixer.init()

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

py游戏。搅拌机。音乐。设置_音量(0.4)

pygame.mixer.music.play(-1)

# 设置屏幕

屏幕=py游戏。展示。设置模式(CFG .屏幕尺寸)

pygame.display.set_caption('滑雪游戏—— 九歌)

# 游戏开始界面

ShowStartInterface(屏幕,cfg .屏幕尺寸)

# 实例化游戏精灵

# - 滑雪者

滑雪者=滑雪者类别()

# - 创建障碍物

障碍物0=创建障碍(20,29)

障碍物1=创建障碍(10,19)

obstaclesflag=0

障碍物=添加障碍物(障碍物0,障碍物1)

# 游戏时钟

clock=pygame.time.Clock()

# 记录滑雪的距离

距离=0

# 记录当前的分数

分数=0

# 记录当前的速度

速度=[0,6]

# 游戏主循环

虽然正确:

# - 事件捕获

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit()

if event.type==pygame .按键:

if event.key==pygame .k _左或event.key==pygame .K_a:

速度=滑雪者。转弯(-1)

elif event.key==pygame .k _右或event.key==pygame .K_d:

速度=滑雪者。转弯(1)

# - 更新当前游戏帧的数据

skier.move()

距离=速度[1]

如果距离=640且障碍物标志==0:

obstaclesflag=1

障碍物0=创建障碍(20,29)

障碍物=添加障碍物(障碍物0,障碍物1)

如果距离=1280且障碍物标志==1:

obstaclesflag=0

距离-=1280

对于障碍物中的障碍物0:

障碍物位置[1]=障碍物位置[1] - 1280

障碍物1=创建障碍(10,19)

障碍物=添加障碍物(障碍物0,障碍物1)

对于障碍中的障碍:

障碍。移动(距离)

# - 碰撞检测

hitted _障碍物=pygame.sprite.spritecollide(滑雪者,障碍物,假)

如果碰到障碍物:

如果击中_障碍物[0]。属性=='树'和未命中_障碍[0].通过:

得分-=50

滑雪者。setFall()

更新框架(屏幕、障碍物、滑雪者、比分)

pygame.time.delay(1000)

skier.setForward()

速度=[0,6]

hitted _障碍物[0]。通过=真

elif hitted _ barriers[0].属性=='标志'和未命中_障碍[0].通过:

得分=10

障碍物。移除(hitted _ barriers[0])

# - 更新屏幕

更新框架(屏幕、障碍物、滑雪者、比分)

clock.tick(cfg .FPS)

'''跑' ' '

if __name__=='__main__ ':

main();

4、并夕夕版飞机大战

源码分享:

导入系统

导入稳频发电机(发生器)(constant frequency generator的缩写)

导入pygame

从模块导入*

'''游戏界面'''

极好的游戏界面(数字播放器,屏幕):

# 初始化

pygame.mixer.music.load(cfg .声音路径['酷空间音乐'])

py游戏。搅拌机。音乐。设置_音量(0.4)

pygame.mixer.music.play(-1)

爆炸_声音=pygame。搅拌机。声音(CFG .声道['boom'])

fire _ sound=py游戏。搅拌机。声音(CFG .声道['shot'])

font=pygame.font.Font(cfg .FONTPATH,20)

# 游戏背景图

bg_imgs=[cfg .图像路径['bg_big'],cfg .图像路径[' seamless _ space '],cfg .图像路径['space3']]

bg_move_dis=0

BG _ 1=py游戏。形象。load(BG _ imgs[0]).转换()

BG _ 2=py游戏。形象。load(BG _ imgs[1]).转换()

BG _ 3=py游戏。形象。load(BG _ imgs[2]).转换()

# 玩家,子弹和小行星精灵组

player _ group=py游戏。雪碧。群组()

bullet _ group=py游戏。雪碧。群组()

asteroid _ group=py游戏。雪碧。群组()

# 产生小行星的时间间隔

小行星刻度=90

对于范围内的我(数字玩家):

player_group.add(Ship(i 1,cfg))

clock=pygame.time.Clock()

# 分数

分数1,分数2=0,0

# 游戏主循环

虽然正确:

对于pygame.event.get()中的事件:

if event.type==pygame .退出:

pygame.quit()

sys.exit()

# - 玩家一: 控制,j射击;玩家二:wsad控制,空格射击

按下的键=py游戏。钥匙。get _ pressed()

对于idx,枚举中的玩家(player_group):

方向=无

如果idx==0:

如果按下_keys[pygame .K_UP]:

方向='向上'

elif pressed_keys[pygame .K_DOWN]:

方向='向下'

elif pressed_keys[pygame .K_LEFT]:

方向='左'

elif pressed_keys[pygame .K_RIGHT]:

方向='右'

如果方向:

玩家。移动(方向)

如果按下_keys[pygame .K_j]:

如果player.cooling_time==0:

fire_sound.play()

bullet_group.add(player.shot())

player.cooling_time=20

elif idx==1:

如果按下_keys[pygame .K_w]:

方向='向上'

elif pressed_keys[pygame .K_s]:

方向='向下'

elif pressed_keys[pygame .K_a]:

方向='左'

elif pressed_keys[pygame .K_d]:

方向='右'

如果方向:

玩家。移动(方向)

如果按下_keys[pygame .K_SPACE]:

如果player.cooling_time==0:

fire_sound.play()

bullet_group.add(player.shot())

player.cooling_time=20

if player.cooling_time 0:

player.cooling_time -=1

如果(分数_1分数_2) 500:

背景=背景_1

elif(分数_1分数_2) 1500:

背景=背景_2

否则:

背景=背景_3

# - 向下移动背景图实现飞船向上移动的效果

screen.blit(background,(0,-background.get_rect().高度bg_move_dis))

screen.blit(background,(0,bg_move_dis))

BG _ move _ dis=(BG _ move _ dis 2)%后台。get _ rect().高度

# - 生成小行星

如果asteroid_ticks==0:

小行星刻度=90

小行星_群。添加(小行星(CFG))

否则:

asteroid_ticks -=1

# - 画飞船

对于玩家_群组中的玩家:

如果py游戏。雪碧。精灵碰撞(玩家,asteroid_group,真,无):

player.explode_step=1

explosion_sound.play()

elif player.explode_step 0:

if player.explode_ste

p > 3: player_group.remove(player) if len(player_group) == 0: return else: player.explode(screen) else: player.draw(screen) # --画子弹 for bullet in bullet_group: bullet.move() if pygame.sprite.spritecollide(bullet, asteroid_group, True, None): bullet_group.remove(bullet) if bullet.player_idx == 1: score_1 += 1 else: score_2 += 1 else: bullet.draw(screen) # --画小行星 for asteroid in asteroid_group: asteroid.move() asteroid.rotate() asteroid.draw(screen) # --显示分数 score_1_text = '玩家一得分: %s' % score_1 score_2_text = '玩家二得分: %s' % score_2 text_1 = font.render(score_1_text, True, (0, 0, 255)) text_2 = font.render(score_2_text, True, (255, 0, 0)) screen.blit(text_1, (2, 5)) screen.blit(text_2, (2, 35)) # --屏幕刷新 pygame.display.update() clock.tick(60) '''主函数''' def main(): pygame.init() pygame.font.init() pygame.mixer.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('飞机大战 —— 九歌') num_player = StartInterface(screen, cfg) if num_player == 1: while True: GamingInterface(num_player=1, screen=screen) EndInterface(screen, cfg) else: while True: GamingInterface(num_player=2, screen=screen) EndInterface(screen, cfg) '''run''' if __name__ == '__main__': main()

5、打地鼠

源码分享:

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

6、小恐龙

玩法:上下控制起跳躲避

源码分享:

import cfg import sys import random import pygame from modules import * '''main''' def main(highest_score): # 游戏初始化 pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('九歌') # 导入所有声音文件 sounds = {} for key, value in cfg.AUDIO_PATHS.items(): sounds[key] = pygame.mixer.Sound(value) # 游戏开始界面 GameStartInterface(screen, sounds, cfg) # 定义一些游戏中必要的元素和变量 score = 0 score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR) highest_score = highest_score highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True) dino = Dinosaur(cfg.IMAGE_PATHS['dino']) ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1])) cloud_sprites_group = pygame.sprite.Group() cactus_sprites_group = pygame.sprite.Group() ptera_sprites_group = pygame.sprite.Group() add_obstacle_timer = 0 score_timer = 0 # 游戏主循环 clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE or event.key == pygame.K_UP: dino.jump(sounds) elif event.key == pygame.K_DOWN: dino.duck() elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN: dino.unduck() screen.fill(cfg.BACKGROUND_COLOR) # --随机添加云 if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10: cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75)))) # --随机添加仙人掌/飞龙 add_obstacle_timer += 1 if add_obstacle_timer > random.randrange(50, 150): add_obstacle_timer = 0 random_value = random.randrange(0, 10) if random_value >= 5 and random_value <= 7: cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti'])) else: position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20] ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys)))) # --更新游戏元素 dino.update() ground.update() cloud_sprites_group.update() cactus_sprites_group.update() ptera_sprites_group.update() score_timer += 1 if score_timer > (cfg.FPS//12): score_timer = 0 score += 1 score = min(score, 99999) if score > highest_score: highest_score = score if score % 100 == 0: sounds['point'].play() if score % 1000 == 0: ground.speed -= 1 for item in cloud_sprites_group: item.speed -= 1 for item in cactus_sprites_group: item.speed -= 1 for item in ptera_sprites_group: item.speed -= 1 # --碰撞检测 for item in cactus_sprites_group: if pygame.sprite.collide_mask(dino, item): dino.die(sounds) for item in ptera_sprites_group: if pygame.sprite.collide_mask(dino, item): dino.die(sounds) # --将游戏元素画到屏幕上 dino.draw(screen) ground.draw(screen) cloud_sprites_group.draw(screen) cactus_sprites_group.draw(screen) ptera_sprites_group.draw(screen) score_board.set(score) highest_score_board.set(highest_score) score_board.draw(screen) highest_score_board.draw(screen) # --更新屏幕 pygame.display.update() clock.tick(cfg.FPS) # --游戏是否结束 if dino.is_dead: break # 游戏结束界面 return GameEndInterface(screen, cfg), highest_score '''run''' if __name__ == '__main__': highest_score = 0 while True: flag, highest_score = main(highest_score) if not flag: break

7、消消乐

玩法:三个相连就能消除

源码分享:

import os import sys import cfg import pygame from modules import * '''游戏主程序''' def main(): pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('Gemgem —— 九歌') # 加载背景音乐 pygame.mixer.init() pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3")) pygame.mixer.music.set_volume(0.6) pygame.mixer.music.play(-1) # 加载音效 sounds = {} sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav')) sounds['match'] = [] for i in range(6): sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i))) # 加载字体 font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25) # 图片加载 gem_imgs = [] for i in range(1, 8): gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i)) # 主循环 game = gemGame(screen, sounds, font, gem_imgs, cfg) while True: score = game.start() flag = False # 一轮游戏结束后玩家选择重玩或者退出 while True: for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() elif event.type == pygame.KEYUP and event.key == pygame.K_r: flag = True if flag: break screen.fill((135, 206, 235)) text0 = 'Final score: %s' % score text1 = 'Press <R> to restart the game.' text2 = 'Press <Esc> to quit the game.' y = 150 for idx, text in enumerate([text0, text1, text2]): text_render = font.render(text, 1, (85, 65, 0)) rect = text_render.get_rect() if idx == 0: rect.left, rect.top = (212, y) elif idx == 1: rect.left, rect.top = (122.5, y) else: rect.left, rect.top = (126.5, y) y += 100 screen.blit(text_render, rect) pygame.display.update() game.reset() '''run''' if __name__ == '__main__': main()

8、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的。

源码分享:

import os import sys import random from modules import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * '''定义俄罗斯方块游戏类''' class TetrisGame(QMainWindow): def __init__(self, parent=None): super(TetrisGame, self).__init__(parent) # 是否暂停ing self.is_paused = False # 是否开始ing self.is_started = False self.initUI() '''界面初始化''' def initUI(self): # icon self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg'))) # 块大小 self.grid_size = 22 # 游戏帧率 self.fps = 200 self.timer = QBasicTimer() # 焦点 self.setFocusPolicy(Qt.StrongFocus) # 水平布局 layout_horizontal = QHBoxLayout() self.inner_board = InnerBoard() self.external_board = ExternalBoard(self, self.grid_size, self.inner_board) layout_horizontal.addWidget(self.external_board) self.side_panel = SidePanel(self, self.grid_size, self.inner_board) layout_horizontal.addWidget(self.side_panel) self.status_bar = self.statusBar() self.external_board.score_signal[str].connect(self.status_bar.showMessage) self.start() self.center() self.setWindowTitle('Tetris —— 九歌') self.show() self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height()) '''游戏界面移动到屏幕中间''' def center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2) '''更新界面''' def updateWindow(self): self.external_board.updateData() self.side_panel.updateData() self.update() '''开始''' def start(self): if self.is_started: return self.is_started = True self.inner_board.createNewTetris() self.timer.start(self.fps, self) '''暂停/不暂停''' def pause(self): if not self.is_started: return self.is_paused = not self.is_paused if self.is_paused: self.timer.stop() self.external_board.score_signal.emit('Paused') else: self.timer.start(self.fps, self) self.updateWindow() '''计时器事件''' def timerEvent(self, event): if event.timerId() == self.timer.timerId(): removed_lines = self.inner_board.moveDown() self.external_board.score += removed_lines self.updateWindow() else: super(TetrisGame, self).timerEvent(event) '''按键事件''' def keyPressEvent(self, event): if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty: super(TetrisGame, self).keyPressEvent(event) return key = event.key() # P键暂停 if key == Qt.Key_P: self.pause() return if self.is_paused: return # 向左 elif key == Qt.Key_Left: self.inner_board.moveLeft() # 向右 elif key == Qt.Key_Right: self.inner_board.moveRight() # 旋转 elif key == Qt.Key_Up: self.inner_board.rotateAnticlockwise() # 快速坠落 elif key == Qt.Key_Space: self.external_board.score += self.inner_board.dropDown() else: super(TetrisGame, self).keyPressEvent(event) self.updateWindow() '''run''' if __name__ == '__main__': app = QApplication([]) tetris = TetrisGame() sys.exit(app.exec_())

9、贪吃蛇

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

源码分享:

import cfg import sys import pygame from modules import * '''主函数''' def main(cfg): # 游戏初始化 pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('Greedy Snake —— 九歌') clock = pygame.time.Clock() # 播放背景音乐 pygame.mixer.music.load(cfg.BGMPATH) pygame.mixer.music.play(-1) # 游戏主循环 snake = Snake(cfg) apple = Apple(cfg, snake.coords) score = 0 while True: screen.fill(cfg.BLACK) # --按键检测 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]: snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key]) # --更新贪吃蛇和食物 if snake.update(apple): apple = Apple(cfg, snake.coords) score += 1 # --判断游戏是否结束 if snake.isgameover: break # --显示游戏里必要的元素 drawGameGrid(cfg, screen) snake.draw(screen) apple.draw(screen) showScore(cfg, score, screen) # --屏幕更新 pygame.display.update() clock.tick(cfg.FPS) return endInterface(screen, cfg) '''run''' if __name__ == '__main__': while True: if not main(cfg): break

10、24点小游戏

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

源码分享:

import os import sys import pygame from cfg import * from modules import * from fractions import Fraction '''检查控件是否被点击''' def checkClicked(group, mouse_pos, group_type='NUMBER'): selected = [] # 数字卡片/运算符卡片 if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]: max_selected = 2 if group_type == GROUPTYPES[0] else 1 num_selected = 0 for each in group: num_selected += int(each.is_selected) for each in group: if each.rect.collidepoint(mouse_pos): if each.is_selected: each.is_selected = not each.is_selected num_selected -= 1 each.select_order = None else: if num_selected < max_selected: each.is_selected = not each.is_selected num_selected += 1 each.select_order = str(num_selected) if each.is_selected: selected.append(each.attribute) # 按钮卡片 elif group_type == GROUPTYPES[2]: for each in group: if each.rect.collidepoint(mouse_pos): each.is_selected = True selected.append(each.attribute) # 抛出异常 else: raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES)) return selected '''获取数字精灵组''' def getNumberSpritesGroup(numbers): number_sprites_group = pygame.sprite.Group() for idx, number in enumerate(numbers): args = (*NUMBERCARD_POSITIONS[idx], str(number), NUMBERFONT, NUMBERFONT_COLORS, NUMBERCARD_COLORS, str(number)) number_sprites_group.add(Card(*args)) return number_sprites_group '''获取运算符精灵组''' def getOperatorSpritesGroup(operators): operator_sprites_group = pygame.sprite.Group() for idx, operator in enumerate(operators): args = (*OPERATORCARD_POSITIONS[idx], str(operator), OPERATORFONT, OPREATORFONT_COLORS, OPERATORCARD_COLORS, str(operator)) operator_sprites_group.add(Card(*args)) return operator_sprites_group '''获取按钮精灵组''' def getButtonSpritesGroup(buttons): button_sprites_group = pygame.sprite.Group() for idx, button in enumerate(buttons): args = (*BUTTONCARD_POSITIONS[idx], str(button), BUTTONFONT, BUTTONFONT_COLORS, BUTTONCARD_COLORS, str(button)) button_sprites_group.add(Button(*args)) return button_sprites_group '''计算''' def calculate(number1, number2, operator): operator_map = {'+': '+', '-': '-', '×': '*', '÷': '/'} try: result = str(eval(number1+operator_map[operator]+number2)) return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2)) except: return None '''在屏幕上显示信息''' def showInfo(text, screen): rect = pygame.Rect(200, 180, 400, 200) pygame.draw.rect(screen, PAPAYAWHIP, rect) font = pygame.font.Font(FONTPATH, 40) text_render = font.render(text, True, BLACK) font_size = font.size(text) screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2)) '''主函数''' def main(): # 初始化, 导入必要的游戏素材 pygame.init() pygame.mixer.init() screen = pygame.display.set_mode(SCREENSIZE) pygame.display.set_caption('24 point —— 九歌') win_sound = pygame.mixer.Sound(AUDIOWINPATH) lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH) warn_sound = pygame.mixer.Sound(AUDIOWARNPATH) pygame.mixer.music.load(BGMPATH) pygame.mixer.music.play(-1, 0.0) # 24点游戏生成器 game24_gen = game24Generator() game24_gen.generate() # 精灵组 # --数字 number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now) # --运算符 operator_sprites_group = getOperatorSpritesGroup(OPREATORS) # --按钮 button_sprites_group = getButtonSpritesGroup(BUTTONS) # 游戏主循环 clock = pygame.time.Clock() selected_numbers = [] selected_operators = [] selected_buttons = [] is_win = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(-1) elif event.type == pygame.MOUSEBUTTONUP: mouse_pos = pygame.mouse.get_pos() selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER') selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR') selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON') screen.fill(AZURE) # 更新数字 if len(selected_numbers) == 2 and len(selected_operators) == 1: noselected_numbers = [] for each in number_sprites_group: if each.is_selected: if each.select_order == '1': selected_number1 = each.attribute elif each.select_order == '2': selected_number2 = each.attribute else: raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order) else: noselected_numbers.append(each.attribute) each.is_selected = False for each in operator_sprites_group: each.is_selected = False result = calculate(selected_number1, selected_number2, *selected_operators) if result is not None: game24_gen.numbers_now = noselected_numbers + [result] is_win = game24_gen.check() if is_win: win_sound.play() if not is_win and len(game24_gen.numbers_now) == 1: lose_sound.play() else: warn_sound.play() selected_numbers = [] selected_operators = [] number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now) # 精灵都画到screen上 for each in number_sprites_group: each.draw(screen, pygame.mouse.get_pos()) for each in operator_sprites_group: each.draw(screen, pygame.mouse.get_pos()) for each in button_sprites_group: if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']: is_win = False if selected_buttons and each.attribute == selected_buttons[0]: each.is_selected = False number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group) selected_buttons = [] each.draw(screen, pygame.mouse.get_pos()) # 游戏胜利 if is_win: showInfo('Congratulations', screen) # 游戏失败 if not is_win and len(game24_gen.numbers_now) == 1: showInfo('Game Over', screen) pygame.display.flip() clock.tick(30) '''run''' if __name__ == '__main__': main()

11、平衡木

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

源码分享:

import cfg from modules import breakoutClone '''主函数''' def main(): game = breakoutClone(cfg) game.run() '''run''' if __name__ == '__main__': main()

12、外星人入侵

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

源码分享:

import os import sys import cfg import random import pygame from modules import * '''开始游戏''' 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) * 50 enemy.rect.y = 120 + (i // 11) * 45 enemies_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 = 24 enemy_move_interval = 24 enemy_move_flag = False # --改变移动方向(改变方向的同时集体下降一次) enemy_change_direction_count = 0 enemy_change_direction_interval = 60 enemy_need_down = False enemy_move_right = True enemy_need_move_row = 6 enemy_max_row = 5 # 用于控制敌方发射子弹 enemy_shot_interval = 100 enemy_shot_count = 0 enemy_shot_flag = False # 游戏进行中 running = True is_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.reward if pygame.sprite.spritecollide(ufo, my_bullets_group, True, None): ufo.is_dead = True myaircraft.score += ufo.reward # --更新并画敌方 # ----敌方子弹 enemy_shot_count += 1 if enemy_shot_count > enemy_shot_interval: enemy_shot_flag = True enemies_survive_list = [enemy.number for enemy in enemies_group] shot_number = random.choice(enemies_survive_list) enemy_shot_count = 0 # ----敌方移动 enemy_move_count += 1 if enemy_move_count > enemy_move_interval: enemy_move_count = 0 enemy_move_flag = True enemy_need_move_row -= 1 if enemy_need_move_row == 0: enemy_need_move_row = enemy_max_row enemy_change_direction_count += 1 if enemy_change_direction_count > enemy_change_direction_interval: enemy_change_direction_count = 1 enemy_move_right = not enemy_move_right enemy_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 = False is_win = False enemy.change_count -= 1 enemy.draw(screen) enemy_move_flag = False enemy_need_down = False enemy_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 = True if myaircraft.one_dead: if myaircraft.boom(screen): myaircraft.resetBoom() myaircraft.num_life -= 1 if myaircraft.num_life < 1: running = False is_win = False else: # ----更新飞船 myaircraft.update(cfg.SCREENSIZE[0]) # ----画飞船 myaircraft.draw(screen) if (not ufo.has_boomed) and (ufo.is_dead): if ufo.boom(screen): ufo.has_boomed = True else: # ----更新UFO ufo.update(cfg.SCREENSIZE[0]) # ----画UFO ufo.draw(screen) # --画我方飞船子弹 for bullet in my_bullets_group: if bullet.update(): my_bullets_group.remove(bullet) del bullet else: bullet.draw(screen) # --画敌方子弹 for bullet in en_bullets_group: if bullet.update(cfg.SCREENSIZE[1]): en_bullets_group.remove(bullet) del bullet else: 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.score myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life) # --敌人都死光了的话就胜利了 if len(enemies_group) < 1: is_win = True running = 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) # ----FPS showText(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()

13、井字棋888

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

源码分享

from tkinter import * import tkinter.messagebox as msg root = Tk() root.title('TIC-TAC-TOE---Project Gurukul') # labels Label(root, text="player1 : X", font="times 15").grid(row=0, column=1) Label(root, text="player2 : O", font="times 15").grid(row=0, column=2) digits = [1, 2, 3, 4, 5, 6, 7, 8, 9] # for player1 sign = X and for player2 sign= Y mark = '' # counting the no. of click count = 0 panels = ["panel"] * 10 def win(panels, sign): return ((panels[1] == panels[2] == panels[3] == sign) or (panels[1] == panels[4] == panels[7] == sign) or (panels[1] == panels[5] == panels[9] == sign) or (panels[2] == panels[5] == panels[8] == sign) or (panels[3] == panels[6] == panels[9] == sign) or (panels[3] == panels[5] == panels[7] == sign) or (panels[4] == panels[5] == panels[6] == sign) or (panels[7] == panels[8] == panels[9] == sign)) def checker(digit): global count, mark, digits # Check which button clicked if digit == 1 and digit in digits: digits.remove(digit) ##player1 will play if the value of count is even and for odd player2 will play if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button1.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 2 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button2.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 3 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button3.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 4 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button4.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 5 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button5.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 6 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button6.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 7 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button7.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 8 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button8.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() if digit == 9 and digit in digits: digits.remove(digit) if count % 2 == 0: mark = 'X' panels[digit] = mark elif count % 2 != 0: mark = 'O' panels[digit] = mark button9.config(text=mark) count = count + 1 sign = mark if (win(panels, sign) and sign == 'X'): msg.showinfo("Result", "Player1 wins") root.destroy() elif (win(panels, sign) and sign == 'O'): msg.showinfo("Result", "Player2 wins") root.destroy() ###if count is greater then 8 then the match has been tied if (count > 8 and win(panels, 'X') == False and win(panels, 'O') == False): msg.showinfo("Result", "Match Tied") root.destroy() ####define buttons button1 = Button(root, width=15, font=('Times 16 bold'), height=7, command=lambda: checker(1)) button1.grid(row=1, column=1) button2 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(2)) button2.grid(row=1, column=2) button3 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(3)) button3.grid(row=1, column=3) button4 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(4)) button4.grid(row=2, column=1) button5 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(5)) button5.grid(row=2, column=2) button6 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(6)) button6.grid(row=2, column=3) button7 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(7)) button7.grid(row=3, column=1) button8 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(8)) button8.grid(row=3, column=2) button9 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(9)) button9.grid(row=3, column=3) root.mainloop()

以上就是13个有趣又好玩的Python游戏代码分享的详细内容,更多关于Python 游戏的资料请关注我们其它相关文章!

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: