14个Python⼩游戏源码分享
⽬录
1、吃⾦币
2、打乒乓
3、滑雪
4、并⼣⼣版飞机⼤战
5、打地⿏
6、⼩恐龙
7、消消乐
8、俄罗斯⽅块
9、贪吃蛇
10、24点⼩游戏
11、平衡⽊
12、外星⼈⼊侵
13、贪⼼鸟
14、井字棋888‘'
1、吃⾦币
源码分享:
import os
import cfg
import sys
import pygame
import random
from modules import *
'''游戏初始化'''
def initGame():
# 初始化pygame, 设置展⽰窗⼝
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('catch coins —— 九歌')
# 加载必要的游戏素材
game_images = {}
for key, value in cfg.IMAGE_PATHS.items():
if isinstance(value, list):
images = []
for item in value: images.append(pygame.image.load(item))
game_images[key] = images
else:
game_images[key] = pygame.image.load(value)
game_sounds = {}
for key, value in cfg.AUDIO_PATHS.items():
if key == 'bgm': continue
game_sounds[key] = pygame.mixer.Sound(value)
# 返回初始化数据
return screen, game_images, game_sounds
'''主函数'''
def main():
# 初始化
screen, game_images, game_sounds = initGame()
# 播放背景⾳乐
pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
pygame.mixer.music.play(-1, 0.0)
# 字体加载
font = pygame.font.Font(cfg.FONT_PATH, 40)
# 定义hero
hero = Hero(game_images['hero'], position=(375, 520))
# 定义⾷物组
food_sprites_group = pygame.sprite.Group()
generate_food_freq = random.randint(10, 20)
generate_food_count = 0
# 当前分数/历史最⾼分
score = 0
highest_score = 0 if not ists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())    # 游戏主循环
clock = pygame.time.Clock()
while True:
# --填充背景
screen.fill(0)
screen.blit(game_images['background'], (0, 0))
# --倒计时信息
countdown_text = 'Count down: ' + str((90000 - _ticks()) // 60000) + ":" + str((90000 - _ticks()) // 1000 % 60).zfill(2)
countdown_text = der(countdown_text, True, (0, 0, 0))
countdown_rect = _rect()
pright = [cfg.SCREENSIZE[0]-30, 5]
screen.blit(countdown_text, countdown_rect)
# --按键检测
for event in ():
pe == pygame.QUIT:
pygame.quit()
key_pressed = _pressed()
if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
# --随机⽣成⾷物
generate_food_count += 1
if generate_food_count > generate_food_freq:
generate_food_freq = random.randint(10, 20)
generate_food_count = 0
food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)            food_sprites_group.add(food)
# --更新⾷物
for food in food_sprites_group:
if food.update(): food_ve(food)
# --碰撞检测
bigdecimal小于for food in food_sprites_group:
if llide_mask(food, hero):
game_sounds['get'].play()
food_ve(food)
score += food.score
if score > highest_score: highest_score = score
# --画hero
hero.draw(screen)
# --画⾷物
food_sprites_group.draw(screen)
# --显⽰得分
score_text = f'Score: {score}, Highest: {highest_score}'
score_text = der(score_text, True, (0, 0, 0))
score_rect = _rect()
pleft = [5, 5]
soapclient函数在vbscreen.blit(score_text, score_rect)
# --判断游戏是否结束
if _ticks() >= 90000:
break
# --更新屏幕
pygame.display.flip()
clock.tick(cfg.FPS)
# 游戏结束, 记录最⾼分并显⽰游戏结束画⾯
fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
fp.write(str(highest_score))
fp.close()
return showEndGameInterface(screen, cfg, score, highest_score)
'''run'''
if __name__ == '__main__':
while main():
pass
2、打乒乓
源码分享:
import sys
import cfg
import pygame
from modules import *
'''定义按钮'''
def Button(screen, position, text, button_size=(200, 50)):
left, top = position
bwidth, bheight = button_size
pygame.draw.line(screen, (150, 150, 150), (left, top), (left+bwidth, top), 5)
pygame.draw.line(screen, (150, 150, 150), (left, top-2), (left, top+bheight), 5)
pygame.draw.line(screen, (50, 50, 50), (left, top+bheight), (left+bwidth, top+bheight), 5)
pygame.draw.line(screen, (50, 50, 50), (left+bwidth, top+bheight), (left+bwidth, top), 5)
(screen, (100, 100, 100), (left, top, bwidth, bheight))
font = pygame.font.Font(cfg.FONTPATH, 30)
text_render = der(text, 1, (255, 235, 205))
return screen.blit(text_render, (left+50, top+10))
'''
怎么当地的微帮平台Function:
开始界⾯
Input:
--screen: 游戏界⾯
Return:
--game_mode: 1(单⼈模式)/2(双⼈模式)
'''
def startInterface(screen):
clock = pygame.time.Clock()
while True:
screen.fill((41, 36, 33))
button_1 = Button(screen, (150, 175), '1 Player')
button_2 = Button(screen, (150, 275), '2 Player')
for event in ():
pe == pygame.QUIT:
pygame.quit()
pe == pygame.MOUSEBUTTONDOWN:
if _pos()):
return 1
elif _pos()):
return 2
clock.tick(10)
pygame.display.update()
'''结束界⾯'''
def endInterface(screen, score_left, score_right):
clock = pygame.time.Clock()
font1 = pygame.font.Font(cfg.FONTPATH, 30)
font2 = pygame.font.Font(cfg.FONTPATH, 20)
msg = 'Player on left won!' if score_left > score_right else 'Player on right won!'    texts = [der(msg, True, cfg.WHITE),
while True:
screen.fill((41, 36, 33))
for event in ():
pe == pygame.QUIT:
pygame.quit()
pe == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
return
elif event.key == pygame.K_ESCAPE:
pygame.quit()
for text, pos in zip(texts, positions):
screen.blit(text, pos)
clock.tick(10)
pygame.display.update()
'''运⾏游戏Demo'''
def runDemo(screen):
# 加载游戏素材
hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
goal_sound = pygame.mixer.Sound(cfg.GOALSOUNDPATH)
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1, 0.0)
font = pygame.font.Font(cfg.FONTPATH, 50)
# 开始界⾯
game_mode = startInterface(screen)
# 游戏主循环
# --左边球拍(ws控制, 仅双⼈模式时可控制)
score_left = 0
racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)
# --右边球拍(↑↓控制)
score_right = 0
racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)
# --球
ball = Ball(cfg.BALLPICPATH, cfg)
clock = pygame.time.Clock()
while True:
for event in ():
pe == pygame.QUIT:
pygame.quit()
screen.fill((41, 36, 33))
# 玩家操作
pressed_keys = _pressed()
if pressed_keys[pygame.K_UP]:
ve('UP')
elif pressed_keys[pygame.K_DOWN]:
ve('DOWN')
if game_mode == 2:
if pressed_keys[pygame.K_w]:
ve('UP')
elif pressed_keys[pygame.K_s]:
ve('DOWN')
else:
racket_left.automove(ball)
# 球运动
scores = ve(ball, racket_left, racket_right, hit_sound, goal_sound)        score_left += scores[0]
score_right += scores[1]
# 显⽰
# --分隔线
(screen, cfg.WHITE, (247, 0, 6, 500))
# --球
ball.draw(screen)
# --拍
racket_left.draw(screen)
racket_right.draw(screen)
# --得分
screen.der(str(score_left), False, cfg.WHITE), (150, 10))java switchcase语句用法
screen.der(str(score_right), False, cfg.WHITE), (300, 10))
if score_left == 11 or score_right == 11:
return score_left, score_right
clock.tick(100)
pygame.display.update()
'''主函数'''
def main():
# 初始化
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
pygame.display.set_caption('pingpong —— 九歌')
# 开始游戏
while True:
score_left, score_right = runDemo(screen)
endInterface(screen, score_left, score_right)
'''run'''
if __name__ == '__main__':
main()
3、滑雪
源码分享:
import sys
import cfg
import pygame
import random
'''滑雪者类'''
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# 滑雪者的朝向(-2到2)
self.direction = 0
self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]
self.image = pygame.image.load(self.imagepaths[self.direction])
< = _rect()
self.speed = [self.direction, 6-abs(self.direction)*2]
'''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''
def turn(self, num):
self.direction += num
self.direction = max(-2, self.direction)
self.direction = min(2, self.direction)
center =
self.image = pygame.image.load(self.imagepaths[self.direction])
< = _rect()
self.speed = [self.direction, 6-abs(self.direction)*2]
return self.speed
'''移动滑雪者'''
def move(self):
'''设置为摔倒状态'''
def setFall(self):
self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
'''设置为站⽴状态'''
def setForward(self):
self.direction = 0
self.image = pygame.image.load(self.imagepaths[self.direction])
'''
Function:
障碍物类
Input:
img_path: 障碍物图⽚路径
location: 障碍物位置
attribute: 障碍物类别属性
'''
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, img_path, location, attribute):
pygame.sprite.Sprite.__init__(self)
self.img_path = img_path
self.image = pygame.image.load(self.img_path)
self.location = location
< = _rect()
self.attribute = attribute
self.passed = False
'''移动'''
def move(self, num):
'''创建障碍物'''
def createObstacles(s, e, num=10):
oracle数据库很难下吗obstacles = pygame.sprite.Group()
locations = []
for i in range(num):
row = random.randint(s, e)
col = random.randint(0, 9)
location  = [col*64+20, row*64+20]
if location not in locations:
locations.append(location)
attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))            img_path = cfg.OBSTACLE_PATHS[attribute]
obstacle = ObstacleClass(img_path, location, attribute)
obstacles.add(obstacle)
return obstacles
'''合并障碍物'''
def AddObstacles(obstacles0, obstacles1):
obstacles = pygame.sprite.Group()
for obstacle in obstacles0:
obstacles.add(obstacle)
for obstacle in obstacles1:
obstacles.add(obstacle)
return obstacles
'''显⽰游戏开始界⾯'''
def ShowStartInterface(screen, screensize):
screen.fill((255, 255, 255))
python基础代码大全下载tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)
cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)
title = der(u'滑雪游戏', True, (255, 0, 0))
content = der(u'按任意键开始游戏', True, (0, 0, 255))
trect = _rect()
trect.midtop = (screensize[0]/2, screensize[1]/5)
crect = _rect()
crect.midtop = (screensize[0]/2, screensize[1]/2)
screen.blit(title, trect)
screen.blit(content, crect)
while True:
for event in ():
pe == pygame.QUIT:
pygame.quit()
pe == pygame.KEYDOWN:
return
pygame.display.update()
'''显⽰分数'''
def showScore(screen, score, pos=(10, 10)):
font = pygame.font.Font(cfg.FONTPATH, 30)
score_text = der("Score: %s" % score, True, (0, 0, 0))
screen.blit(score_text, pos)
'''更新当前帧的游戏画⾯'''
def updateFrame(screen, obstacles, skier, score):
screen.fill((255, 255, 255))
obstacles.draw(screen)
screen.blit(skier.image, )
showScore(screen, score)
pygame.display.update()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。