大家好,小编来为大家解答以下问题,20行python代码的入门级小游戏,python有什么好玩的代码嘛,今天让我们一起来看看吧!
哈喽铁子们
表弟最近在学Python,总是跟我抱怨很枯燥无味,其实,他有没有认真想过,可能是自己学习姿势不对?
比方说,可以通过打游戏来学编程!
今天给大家分享100个Python小游戏,一定要收藏!
飞机大战相信大家都玩过吧,非常简单有意思的游戏,咱们通过Python给它复刻出来,回味童年。
素材文件
全部源码:
import sys
import cfg
import pygame
from modules import *
'''游戏界面'''
def GamingInterface(num_player, screen):
# 初始化
pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
font = pygame.font.Font(cfg.FONTPATH, 20)
# 游戏背景图
bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']]
bg_move_dis = 0
bg_1 = pygame.image.load(bg_imgs[0]).convert()
bg_2 = pygame.image.load(bg_imgs[1]).convert()
bg_3 = pygame.image.load(bg_imgs[2]).convert()
# 玩家, 子弹和小行星精灵组
player_group = pygame.sprite.Group()
bullet_group = pygame.sprite.Group()
asteroid_group = pygame.sprite.Group()
# 产生小行星的时间间隔
asteroid_ticks = 90
for i in range(num_player):
player_group.add(Ship(i+1, cfg))
clock = pygame.time.Clock()
# 分数
score_1, score_2 = 0, 0
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# --玩家一: ↑↓←→控制, j射击; 玩家二: wsad控制, 空格射击
pressed_keys = pygame.key.get_pressed()
for idx, player in enumerate(player_group):
direction = None
if idx == 0:
if pressed_keys[pygame.K_UP]:
direction = 'up'
elif pressed_keys[pygame.K_DOWN]:
direction = 'down'
elif pressed_keys[pygame.K_LEFT]:
direction = 'left'
elif pressed_keys[pygame.K_RIGHT]:
direction = 'right'
if direction:
player.move(direction)
if pressed_keys[pygame.K_j]:
if player.cooling_time == 0:
fire_sound.play()
bullet_group.add(player.shot())
player.cooling_time = 20
elif idx == 1:
if pressed_keys[pygame.K_w]:
direction = 'up'
elif pressed_keys[pygame.K_s]:
direction = 'down'
elif pressed_keys[pygame.K_a]:
direction = 'left'
elif pressed_keys[pygame.K_d]:
direction = 'right'
if direction:
player.move(direction)
if pressed_keys[pygame.K_SPACE]:
if 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
if (score_1 + score_2) < 500:
background = bg_1
elif (score_1 + score_2) < 1500:
background = bg_2
else:
background = bg_3
# --向下移动背景图实现飞船向上移动的效果
screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
screen.blit(background, (0, bg_move_dis))
bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
# --生成小行星
if asteroid_ticks == 0:
asteroid_ticks = 90
asteroid_group.add(Asteroid(cfg))
else:
asteroid_ticks -= 1
# --画飞船
for player in player_group:
if pygame.sprite.spritecollide(player, asteroid_group, True, None):
player.explode_step = 1
explosion_sound.play()
elif player.explode_step > 0:
if player.explode_step > 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()
都是一些大家耳熟能详的小游戏
素材
全部源码:
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('开心消消乐')
# 加载背景音乐
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 to restart the game.'
text2 = 'Press 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()
还是直接上目录吧~
免子
八音符
外星人入侵
推箱子
俄罗斯方块
飞机大战
接金币月饼
塔防
小恐龙
像素鸟
坦克大战
滑雪
拼图
走迷宫
炸弹人
打砖块
乒乓球
24点游戏
宝石版本消消乐
吃豆豆
斗地主
大富翁
21点游戏
我的世界
魂斗罗
记忆
愤怒小鸟
扫雷
贪吃蛇
2048游戏
五子棋
打地康
2048
下一百层
切水果
数独游戏
空洞机甲
打地鼠
PythonAngryBirds
chess 象棋
彩色版本飞机大战
嗷大喵快跑代码
Tom猫
Sokoban
PythonPlantsVsZombies
Mine-game-master
gluttonous-master
FlappyBird
EatBeans
AlD1904-game 2048-master
2048--master
21点-python-practice-master
贪吃蛇AI
中国急棋
冒险岛
黄金矿工原版
飞机大战2
飞船
大战
蔡徐坤
债怒的小鸟
拼图游戏
XiaoXiaoLe
超级玛丽
幸运大转盘
智慧校园考试系统
植物大战
黑白飞机大战
一只单身狗
小狗快跑
象棋
五子棋
贪吃蛇
忍者奔跑
愤怒的小鸟
天天跑酷
五子棋AI
超级马里奥
连连看
植物大战僵尸
走四棋儿
末世文字版本游戏
FlyFight宇宙激战
泡泡躲障碍
打飞鸟
齿据气球
吃水果
吃掉一切
射击游戏
无敌狙击手
消灭病毒小游戏
扫雷小游戏
病毒小游戏01
简易版推箱子
简易版塔防游戏
彩色版贪吃蛇
躲避小球
鱿鱼游戏
猜教字游戏升级版界面
自动玩俄罗斯方块
好了,大家快去拿源码熟悉一下,下周就可以开始愉快的摸鱼啦!