大家好,小编来为大家解答以下问题,如何用python编写一个简单的小游戏,用python语言编简单游戏,今天让我们一起来看看吧!
Source code download: 本文相关源码
分享上班摸鱼的10个Python小游戏,看看你能摸鱼几天不被发现😏
具体项目源码,实现效果:
关注公众号:Python技术训练营
解锁 :
《1.python百万字PDF教程,手把手助你从零进阶拿高薪》
《2.2023python开发岗面试汇总大全》
《3.python10个上班摸鱼小游戏项目源码》
1丶坤坤打篮球
实现效果:
源码分享:
import pygame
import sys
import traceback
import CXK
import enemy
import bullet
import supply
form pygame.locals import *
form random import *
# 初始化pygame
pygame.init()
# 初始化pygame的音频模块
pygame.mixer.init()
# 定义背景尺寸宽和高
bg_size = wigth,height = 480,700
# 初始化窗口
screen = pygame.display.set_mode(bg_size)
# 设置显示在窗口上的名称
pygame.display.set_caption(''CXK打篮球'')
# 初始化背景图片
background = pygame.image.load(''images/backgroud.png'').convert()
# 定义RGB颜色
BLACK = (0,0,0)
GREEN = (0,255,0)
RED = (255,0,0)
# 载入背景音乐
pygame.mixer.music.load(''sound/game_music.ogg'')
pygame.mixer.music.set_volume(0.2)
# 载入游戏音效
background_sound = pygame.mixer.sound(''sound/background_sound.wav'')
background_sound.set_volume(0.1)
enemy3_fly_sound = pygame.mixer.sound(''sound/organic Rhythm Assault.wav'')
background_sound.set_volume(0.2)
enemy3_fly_sound = pygame.mixer.sound(''sound/爆炸.wav'')
background_sound.set_volume(0.2)
bomb_sound = pygame.mixer.sound(''sound/bomb_sound.wav'')
bomb_sound.set_volume(0.2)
get_supply_sound = pygame.mixer.sound(''sound/get_bullet_sound.wav'')
get_supply_sound.set_volume(0.2)
# 定义增加小型敌人的函数
def add_small_enemies(group1,group2,num):
for i in range(num)
e1 = enemy.SmallEnemy(bg_size)
group1.add(e1)
group2.add(e1)
# 定义增加中型敌人的函数
def add_mid_enemies(group1,group2,num):
for i in range(num)
e2 = enemy.MidEnemy(bg_size)
group1.add(e2)
group2.add(e2)
# 定义增加大型敌人的函数
def add_mid_enemies(group1,group2,num):
for i in range(num)
e3 = enemy.BigEnemy(bg_size)
group1.add(e3)
group2.add(e3)
# 定义增加敌人移动速度的函数
def inc_speed(target,inc):
for each in tatget:
each.speed+=inc
# 游戏主界面
def ui():
# 循环播放背景音乐
pygame.mixer.music.play(-1)
# 初始化界面按键图片并获取图片的矩形位置
start_game_image = pygame.image.load(''images/start_game.png'').convert_alpha()
start_game_image_rect = start_game_image.get_rect()
game_rules_image = pygame.image.load(''images/game_rules.png'').convert_alpha()
game_rules_image_rect = game_rules_image.get.rect()
game_quit_image = pygame.image.load(''image/game_quit.png'').convert_alpha()
game_quit_image_rect = game_quit_image.get_rect()
# 初始化游戏规则图片并获取图片的矩形位置
rules_image = pygame.image.load(''images/游戏玩法.png'').conver_talpha()
back_image = pygame.image.load(''image/back.png'').convert_alpha()
back_image_rect = back_image.get_rect()
# 标志是否在主界面
is_ui = True
# 帧率
clock = pygame.time.Clock()
# 主界面循环
while True:
# 获取事件信息
for event in pygame.event.get():
# 如果点击右上角退出
if event.type = = QUTT:
# 退出程序
pygame.quit()
sys.exit()
# 如果是主界面
if is_ui:
# 绘制背景
screen.blit(background,(0,0))
# 更改主界面按键图片的矩形位置并绘制主界面按键
start_game_image_rect.left,start_game_image_rect.top = (width - statr_game_image_rect.width)//2,height
screen.blit(start_game_image,start_game_image_rect)
game_rules_image_rect = game_rules_image.get_rect()
game_rules_image_rect.left,game_rules_image_rect.top = (width - game_rules_image_rect.width)//2,start_game
screen.blit(game_rules_image,game_rules_image_rect)
game_quit_image_rect.left,game_quit_image_rect.top = (width - game_quit_image_rect.width)//2,game_rules
screen.blit(game_quit_image,game_quit_image_rect)
# 检测用户的鼠标操作
# 如果用户按下鼠标左键
if pygame.mouse.get_pressed()[0]:
# 获取鼠标坐标
pos = pygame.mouse.get_pos()
# 如果用户点击''开始游戏''
if start_game_image_rect.left < pos[0] < start_game_image_rect.right and start_game_image_rect.top < pos[0]
# 调用主函数
main()
# 如果用户点击''退出游戏''
if game_quit_image_rect.left <pos[0] <game_quit_image_rect.right and game_quit_image_rect.top < pos[0]
pygame.quit()
sys.exit()
# 如果用户点击''游戏规则''
if game_rules_image_rect.left < pos[0] <game_rules_image_rect.right and game_rules_image_rect.top< pos[0]
# 李凯主界面
if_ui = False
# 进入游戏规则界面
else:
# 绘制游戏规则图片
screen.blit(rulse_image,(0,0))
# 停止播放背景音乐
pygame.mixer.music.stop()
# 循环播放游戏规则音效
background_sound.play(-1)
# 更改返回键的矩形位置并绘制返回按键
back_image_rect.left,game_quit_image_rect.top = width - back_image_rect.width - 10,10
screen.blit(back_image,(width - back_image_rect.width - 10,10))
if pygame.mouse.get_pressed()[0]:
# 获取鼠标坐标
pos = pygame.mouse.get_pos()
# 如果用户点击返回图片
pygame.mixer.stop()
ui()
# 刷新屏幕
pygame.display.flip()
....
代码省略部分
if_ _name_ _ = =''_ _main_ _'':
try:
ui()
except systemExit:
pass
# 异常处理
except:
traceback.print_exc()
pygame.quit()
os.system(''pause'')
2丶俄罗斯方块
实现效果:
源码分享
import sys
import random,copy
import pygame as pg
from pygame.locals import *
# 常量声明
EMPTY_CELL = 0 # 空区标识,表示没有方块
FALLING_BLOCK = 1 # 下落中的方块标识,也就是活动方块
STATIC_BLOCK = 2 # 固体方块标识
' ' '
全局变量声明
变量值以sysInit函数中初始化后的结果为准
' ' '
defaultFont = None # 默认字体
screen = None # 屏幕输出对象
backsurface = None # 图像输出缓冲画板
score = 0 # 玩家得分记录
clearLinescore = 0 # 玩家清除的方块行数
level = 1 # 关卡等级
clock = None # 游戏始终
nowBlock = None # 当前下落中的方块
nextblock = None # 下一个将出现的方块
fallspeed = 10 # 当前方块下落速度
beginFallspeed = fallspeed # 游戏初始时方块下落速度
speedBuff = 0 # 下落速度缓冲变量
keyBuff = None # 上一次按键记录
maxBlockwidth = 10 # 舞台堆叠区X轴最大可容纳基础方块数
maxBlockHeight = 18 # 舞台堆叠区Y轴最大可容纳基础方块数
blockwidth = 30 # 以像素为单位的基础方块宽度
blockHeight = 30 # 以像素为单位的基础方块高度
blocks = [] # 方块形状矩形四维列表。第一维为不同的方块形状,第二维为每个方块形状不同的方向(以0标起始,一共四个方向),第三维为Y轴方块形状占用情况,第四维为X轴方块形状占用情况
stage = [] # 舞台堆叠去矩形二维列表,第一维为Y轴方块占用情况,第二维为X轴方块占用情况python创意turtle作品。矩阵中0表示没有方块,1表示有固实方块,2表示有活动方块。
gameover = False # 游戏结束标志
pause = False # 游戏暂停标志
def printTxt(content,x,y,font,screen,color=(255,255,255)):
'''显示文本
args:
content:待显示文本内容
x,y:显示坐标
font:字体
screen:输出的screen
color:颜色
'''
imgTxt = font.render(content,True,color)
screen.blit(imgTxt,(x,y))
class point(object):
'''平面坐标点类
attributes:
x,y:坐标值
'''
def _ _init _ _(self,x,y):
self._ _x = x
self._ _y = y
def getx(self):
return self. _ _x
def setx(self,x)
self._ _x = x
x = property(getx,setx)
def gety(self):
ruturn self. _ _y
def sety(self,y):
self. _ _y = y
y = property(gety,sety)
def _ _str_ _(self):
rutunrn ''{x:'' + ''{:.of}''.format(self._ _x) + '',y:''{:.of}''.format(self._ _y) + '' }''
class blocksprite(object):
'''
方块形状精灵类
下落方块的定义全靠它了。
attributes:
shape:方块形状编号
direction:方块方向编号
xy,方块形状左上角方块坐标
block:方块形状矩形
'''
def _ _init_ _(self,shape,direction,xy):
self.shape = shape
self.direction = direction
self.xy = xy
def chgDirection(self,direction):
'''
改变方块的方向
args:
direction:1为向右转,0为向左转
'''
dirNumb = len(block[self.shape]) - 1
if direction = = 1:
self.direction + =1
if self.dirction > dirNumb:
self.direction = dirNumb
def clone(self):
'''
克隆本体
return:
返回自身的克隆
'''
return blocksprite(self.shape,self.direction,point(self.xy.x,self.xy.y))
def _getBlock(self):
return blocks[self.shape][self.direction]
block = property(_getBlock)
def getconf(fileName):
'''
从配置文件中读取方块形状数据
每个方块以4*4矩阵表示形状,配置文件每行代表一个方块,用分号分隔矩阵行,用逗号分隔矩列阵,0表示没有方块,1表示有方块
因为此程序只针对俄罗斯方块的经典版,所以方块矩阵大小以硬编码的形式写为4*4
args:
fileName:配置文件名
'''
global blocks # blocks记录方块形状
with open(fileName,'rt')as fp:
for temp in fp.readlines()
blocks.append([])
blocksNumb = len(blocks) - 1
....
省略部分
if _ _name_ _ = ='' _ _main_ _'':
main()
3.猜数字
实现效果:
源码分享
import random
# 模拟电脑随机生成1~100的整数
computer = random.randint(1,101)
while True:
number = int(input(''请输入100以内的整数:‘’))
if (number > computer):
print(''你猜大了'')
elif (number < computer) :
print(''你猜小了'')
else:
print(''恭喜你赢了'')
break
4丶开心消消乐
实现效果:
源码分享
import os
import pygame
from utils import *
from config import *
'''游戏主程序'''
def main()
pygame.init()
screen = pygame.display.set_mode(WIDTH,HEIGHT))
pygame.display.set_caption('游戏-python版开心消消乐‘)
# 加载背景音乐
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(ROOTDIR,''resources/audios/bg.mp3''))
pygame.mixer.music.set_volume(0.6)
pygame.mixer.music.play(-1)
# 加载音效
sound = {}
sound['mismatch'] = pygame.mixer.sound(os.path.join(ROOTDIR,resources/audios/badswap.wav'))
sound['match'] = []
for i in range(6)
sound['match'].append(pygame.mixer.sound(os.path.join(ROOEDIR,'resources/audios/match%s.wav' % i)))
# 加载字体
font = pygame.font.Font(os.path.join(ROOTDIR,'resoureces/font.TTF'),25)
# 图片加载
gem_imgs = []
for i in range(1,8):
gem_imgs.append(os.path.join(ROOTDIR,'resoureces/images/gem%s.png' % i))
# 主循环
game = gamGame(screen,sounds,font,gem_imgs)
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()
if __name__ == '__main__':
main()
5丶接金币,苹果游戏
实现效果:
源码分享
import os
import sys
import random
import pygame
'''获取历史最高分'''
def getscore():
if os.path.isfile('score'):
with open('score','r') as f:
score = f.readline().strip()
if not score:
score = 0
else:
score = 0
return score
'''保存分数(仅当超过历史最高分时)'''
def savescore(score):
with open('score','w') as f:
f.write(score)
'''定义接苹果/金币的人类精灵'''
class Farmersprite(pygame.sprite.sprite):
def__init__(self,WIDTH,HEIGHT):
pygame.sprite.sprite.__init__(self)
self.imgs = [ './imgs/farmer.png']
self.farmer = pygame.image.load(self.imgs[0]).convert_alpha()
self.direction_dict = {
'top': [0,(0, -1)],
'rigttop': [1,(1,-1)]
'right' : [2,(1,0)],
'rightbottom' : [3,(1,1)],
'bottom' : [4,(0,1)],
'left' : [6,(-1,0)],
'lefttop' :[7,(-1,-1)]
}
# 当前农民方向
self.direction = 'left'
# 实现农民行走的效果
self.farmerIdx = 0
self.farmerIdxNum = 8
# 农民的位置
self.x,self.y = WIDTH/2,HEIGHT/1.1
# 速度
self.speed = 10
self.WIDTH,self.HEIGHT =WIDTH,HEIGHT
# 激活一下
self.move()
'''移动'''
def move(self,direction = 'left'):
if direction ! = self.direction:
self.direction = direction
self.farmerIdx = 0
else:
self.farmerIdx += 1
self.farmerIdx = self.farmerIdx % self.farmerIdxNum
farmerpos = self.farmerIdx *96,self.direction_dict[seld.direction][0]*96
self.image = self.farmer.subsurface(farmerpos,(96,96))
self.rect = self.image.get_rect()
self.x = self.x + self.direction_dict[self.direction][1][0]* self.speed
self.y = self.y + self.direction_dict[self.direction][1][1]* self.speed
self.rect.left,self.rect.top = self.x,self.y
# 避免农民走出游戏界面
self.rect.right = self.WIDTH if self.rect.right >self.WIDTH else self.rect.right
self.rect.left = 0 if self.rect.left <0 else self.rect.left
self.rect.top = 0 if self.top < 0 else self.rect.top
self.rect.bottom = self.HEIGHT if self.rect.bottom > self.HEIGHT else self.rect.bottom
'''画上去'''
def draw(self,screen):
screen.blit(self.image,self.rect)
'''掉落的食物类'''
class foodsprite(pygame.sprite.sprite):
def __init__(self,WIDTH,HEIGHT):
pygame.sprite.sprite.__init__(self)
self.imgs = ['./imgs/apple.png','./imgs/gold.png']
# 食物种类
self.kind = random.randint(0,1)
# 食物价值
self.value = 10 if self.kind ==0 else 100
# 下落速度
self.speed = 3 if self.kind == 0 else 6
self.image = pygame.image.load(self.imgs[]self.kind]).convert_alpha()
self.rect = self.image.get_rect()
self.x = random.randint(0,WIDTH-self.rect.width)
self.y = -50
self.rect.left,self.rect.top = self.x,self.y
'''移动'''
def move(self):
self.y += self.speed
self.rect.top = self.y
'''画到屏幕上'''
def draw(self,screen):
screen.blit(self.image, self.rect)
'''显示游戏结束界面'''
def Gameover(screen,width,height,score,highest):
screen.fill((255,255,255))
tfont = pygame.font.Font('./font/simkai.ttf',width//10)
cfont = pygame.font.Font('./font/simkai.ttf',width//20)
title = tfont.render('Gameover',True,(255,0,0))
content = cfont.render('score:%s,Highest:%s' %(score,highest),True,(0,0,255))
trect = title.get_rect()
trect.midtop = (width/2,height/4)
crect = content.get_rect()
crect.midtop =(width/2,height/2)
screen.blit(title,trect)
screen.blit(content,crect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
return
'''主函数'''
def main():
# 初始化
pygame.init()
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode([WIDTH,HEIGHT])
pygame.display.set_caption('初级入门游戏')
pygame.mixer.init()
pygame.mixer.music.load(''./audios/DasBeste.map'')
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
get_sound = pygame.mixer.sound(''./audios/get.wav'')
get_sound.set_volume(6)
clock = pygame.time.clock()
# 定义一些必要的参数并实例化农民
farmer = Farmersprite(WIDTH,HEIGHT)
foodGroup = pygame.sprite.Group()
foodInterval = 100
foodcount = 0
direction = 'left'
font = pygame.font.Font('./font/simkai.ttf',20)
score = 0
# 如果20个食物没接住的话就Game over
maxDown = 20
while True:
if maxDown < 0:
highest = getscore()
if int(highest) <score:
savescore(str(score))
GameOver(screen,WIDTH,HEIGHT,score,highest)
screen.fill([0,160,233])
for event in pygame.event.get():
if event.type ==pygame.QUIT:
pygame.quit()
sys.exit()
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LEFT] or key_pressed[pygame.k_a]:
if direction in ['top','bottom','right']:
direction = 'left'
elif direction =='left':
farmer.move(direction)
elif key pressed[pygame.K_RIGHT] or key_pressed[pygame.k_d]:
if direction in['top','bottom','left']:
direction = 'reght'
elif direction == 'right':
farmer.move(direction)
elif key_pressed[pygame.K_UP] or key_pressed[pygame.K_w]:
if direction in ['right','left','bottom']:
direction = 'top
elif direction == 'top'
farmer.move(direction)
elif key_pressed[pygame.K_DOWN] or key_pressed[pygame.K_s]:
if direction in ['right','left','top']:
direction = 'bottom'
elif direction == 'bottom':
farmer.move(direction)
farmer.draw(screen)
foodcount += 1
if foodcount > foodInterval:
food = foodsprite(WIDTH,HEIGHT)
foodGroup.add(food)
foodcount = 0
for food on foodGroup:
food.move()
if pygame.sprite.collide_rect(food,farmer):
foodGroup.remove(food)
score += food.value
get_sound.play()
continue
if food.rect.top > HEIGHT:
foodGroup.remove(food)
if food.kind == 0:
maxDown -= 1
continue
food.draw(screen)
life_text = font.render(''life: ''+str(maxDown),1,(0,0,0))
score_text = font.render(''score: ''+str(score),1,(0,0,0))
screen.blit(score_text,[10,10])
screen.blit(life_text,[10,35])
pygame.display.flip()
clock.tick(60)
'''run'''
if__name__ == '__main__':
main()
6丶简易五子棋
实现效果:
源码分享:
finish = False # 游戏是否结束
flagNum = 1 # 当前下棋者标记
flagch = '*' # 当前下棋者棋子
x = 0 # 当前棋子的横坐标
y = 0 # 当前棋子的纵坐标
print('---------五子棋游戏(控制台版)---------')
# 棋盘初始化
checkerboard = []
for i in range(10):
checkerboard.append([])
for j in range(10):
checkerboard[i].append('-')
def mas():
# 输出最后胜利的棋盘
print(''\033[1;37;44m-----------'')
print('' 1 2 3 4 5 6 7 8 9 10'')
for i in range(len(checkerboard)):
print(chr(i +ord('A')) + ''.'',end='')
for j in range(len(checkerboard[i])):
print(checkerboard[i][j] + '' '',end='')
print()
print(''------------------------------\033[0m'')
# 输出赢家
if(flagNum ==1):
print('\033[32m*棋胜利!***\033[0m')
else:
print('\033[32mo棋胜利! ***\033[0m')
while not finish:
# 打印棋盘
print(''\033[1;30;46m-----------------'')
print('' 1 2 3 4 5 6 7 8 9 10'')
for i in range(len(checkerboard)):
print(chr(i + ord('A')) + '' '',end='');
for j in range(len(checkerboard[i])):
print(checkerboard[i][j] + '' '',end='')
print()
print('' -----------------------------\033[0m'')
# 判断当前下棋者
if flagNum == 1:
flagch = '*'
print('\033[1;37;40m请*输入棋子坐标(例如A1)):\033[0m,end='') # 白字黑底
else:
flagch = 'o'
print('\033[1;30;42m请o输入棋子坐标(例如J5)):\033[0m',end'') # 黑子绿底
# 输入棋子坐标
str = input()
ch = str[0] # 获取第一个字符的大写形式
x = ord(ch) -65
y = int(str[1]) - 1
# 判断坐标是不在棋盘之中
if(x<0 or x>9 or y<0 or y>9):
print('\033[31m***您输入的坐标有误请重新输入! ***\033[0m')
continue
# 判断坐标上是否有棋子
if(checkerboard[x][y] == '-'):
if(flagNum == 1):
checkerboard[x][y] = '*'
else:
checkerboard[x][y] = 'o'
else:
print('\033[31m******您输入位置已经有其他棋子,请重新输入!\033[0m']
continue
# 判断棋子左侧
if(y - 4 >= 0):
if(checkerboard[x][y - 1] == flagch
and checkerboard[x][y - 2] == flagch
and checkerboard[x][y - 3] == flagch
and checkerboard[x][y - 4] == flagch):
finish = Ture
msg()
# 判断棋子右上方向
if(x - 4 >= 0 and y - 4 >= 0):
if(checkerboard[x - 1][y - 1] == flagch
and checkerboard[x - 2][y - 2] == flagch
and checkerboard[x - 3][y - 3] == flagch
and checkerboard[x - 4][y - 4] == flagch):
finish = True
mag()
# 判断棋子右下方向
if(x + 4 <= 9 and y - 4 >= 0):
if(checkerboard[x +1][y - 1] == flagch
and checkerboard[x + 2][y - 2] == flagch
and checkerboard[x + 3][y - 3] == flagch
and checkerboard[x + 4][y - 4] == flagch):
finish = True
mag()
# 判断棋子左上方向
if(x - 4 >= 0 and y + 4 <= 9):
if(checkerboard[x +1][y +1] == flagch
and checkerboard[x + 2][y + 2] == flagch
and checkerboard[x + 3][y +3] == flagch
and checkerboard[x + 4][y + 4] == flagch):
finish = True
mag()
flagNum *= -1; #更换下棋者标记
7丶热血足球
实现效果:
源码分享
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import itertools,sys,time,random,math,pygame
from pygame.locals import *
from Mylibrary import *
from football import *
from I0 import *
def bias(x,y):
x = x + 16
y = y + 24
x_cent = 0
y_cent = 0
if(x >= 100 and x<= 700):
x_cent = -1 * x + 100
elif(x > 700):
x_cent = -600
else:
x_cent = 0
if(y >=75 and y <=525):
y_cent = -1 * y + 75
elif(y > 525):
y_cent = -450
else:
y_cent = 0
return x_cent,y_cent
def draw_background(screen):
rc = (255,255,255)
rp = (600,400)
rr = 80
width = 5
screen.fill((0,100,0))
pygame.draw.circle(screen,rc,rr,width)
pygame.draw.rect(screen,(255,255,255),(10,10,600,790),5)
pygame.draw.rect(screen,(255,255,255),(600,10,590,790),5)
pygame.draw.rect(screen,(255,255,255),(10,150,300,500),5)
pygame.draw.rect(screen,(255,255,255),(890,150,300,500),5)
def draw_ball_goal(screen):
goal1 = pygame.image.load(''goal1.bmp'').convert()
goal2 = pygame.image.load(''goal2.bmp'').convert()
screen.blit(goal1,(8,305))
screen.blit(goal2,1121,305))
def begin_a_game(n1,n2):
nn = 0
filename = 'p2.png'
filename2 = 'p1.png'
size_of_player = (32,47.5)
size_of_action = 4
size_of_playground = (1920,1080)
dict_ = {(-1,0):3,(1,0):0(0,1):2,(0,-1):1,(-1,1):3,(-1,-1):1,(1,-1):0,(1,1):2};
x_bias = 0
y_bias = 0
kick_off = 0
player_group = pygame.sprite.Group()
player_group1 = pygame.sprite.Group()
player_group2 = pygame.sprite.Group()
player = Mysprite()
x,y = random.randint(250,250),randint(350-25,450-25)
# x_bias,y_bias = bias(x,y);
player.load(filename,size_of_player[0],size_of_player[1],size_of_action)
player.position = X + x_bias,Y +y_bias
player.direction = 1,0
player.tag =1
player_group.add(player)
player_group1.add(player)
player2 = Mysprite()
x2,y2 = random,randint(700,950),random.randint(350-25,450-25)
player2.load(filename2,size_of_player[0],size_of_player[1],size_of_action)
player2.position = X2 + x_bias, Y2 + y_bias
player2.direction = 1,0
player2.tag =2
player_group.add(player2)
player_group2.add(player2)
b_x,b_y = 1200/2,800/2;
ball_group = pygame.sprite.Group()
myball = ball()
myball.load()
myball.position = b_X+x_bias,b_Y+y_bias
ball_group.add(myball)
p1 = robot()
p1.X,p1.Y = random.randint(250,500),random.randint(50-25,350-25)
p1.direction = 1,0
player_group1.add(p1)
player_group.add(p1)
pp2 = robot_B()
pp2.leader = p1
pp2.ball = myball
pp2.goal_pos = [892,399]
pp2.goal = [1120,405]
pp2.tag = 1
pp2.wonder = 300;
pp2.other_group = player_group2
pp2.load(''p3.png'',size_of_player[0],size_of_player[1],size_of_action)
pp2.X,pp2.Y = random.randint(250,500),random.randint(450-25,750-25)
pp2.direction = 1,0
player_group1.add(pp20)
player_group.add(pp2)
d1 =defence()
d1.leader = player
d1.ball = myball
d1.wonder = 85
d1.tag = 1
d1.other_group = player_group2
d1.load(''p3.png'',size_of_player[0],size_of_player[1],size_of_action)
d1.x,d1.Y = 85,390
d1.direction = 1,0
player_group1.add(d1)
player_group.add(d1)
t = robot()
t.leader = player2
t.ball = myball
t.tag = 2
t.other_group = player_group1
t.goal_pos = [309,389]
t.goal = [70,405]
t.load(''p4.png'',size_of_player[0],size_of_player[1],size_of_action)
t.X,t.Y = random.randint(700,950),random.randint(50-25,350-25)
t.direction = 1,0
player_group2.add(t)
player_group.add(t)
d2 = defence2()
d2.leader = player2
d2.ball = myball
d2.wonder = 1070
d2.tag = 2
d2.other_group = player_group1
d2.load(''p4.png'',size_of_player[0],size_of_player[1],size_of_action)
d2.X,d2.Y = 1070,390
d2.direction = 1,0
player_group2.add(d2)
player_group.add(d2)
game_over = False
player_moving = False
player2_moving = False
while True:
timer.tick(50)
ticks = pygame.time.get_ticks()
myball.call +=1;
for event in pygame.event.get():
if event.type == QUTI:
pygame.quit()
sys.exit()
if nn == 0.00001:
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:sys.exit()
if keys[K_SPACE]:nn+=0.00001
continue
nn+0.00001
mx,my = pygame.mouse.get_pos()
# print(str(mx)+'' ''+str(my))
# print(myball.position)
Reference = [x_bias,y_bias,X,Y]
player1_AI(myball,player,game_over,player_moving,Reference)
x_bias,y_bias,X,Y = Reference
reference = [x_bias,y_bias,X2,Y2]
player2_AI(myball,player2,game_over,player2_moving,Reference)
x_bias,y_bias,X2,Y2 = Reference
# print(d1.shoot)
if d1.shoot ==True of d2.shoot == True:
p1.state = ''back''
pp2.state = ''back''
r.state = ~~~''back''
t.state = ~~~''back''
player_group.update(ticks,30)
if mayball.cal > 10:
the_player = None
if myball.player == None:
the_player = pygame.sprite.spritecollideany(myball,player_group);
if~~~the_player ! = None:
if pygame.sprite.collide_circle_ratin(1)(teh_player,myball):
myball.fetched(the_player;
the_player.state = ''catch''
if the_player == d1 or the_player == d2:
the_player.shoot = True;
else myball.player.tag ==1:
the_player = pygame.sprite.spritecollideany(myball,player_group2);
if~~~the_player ! = None:
if pygame.sprite.collide_circle_ratio(1)(the_player,myball):
if the_player ! = d1 and the_player ! = d2:
mybal.player.state = ''chase''
the_player.state = ''catch''
myball.fetched(the_player)
......省略部分......
if __name__ == '__main__'
pygame.init()
screen = pygame.display.set_mode((1200,800))
pygame.display.set_caption(''简单足球'’)
font = pygame.font.Font(None,36)
myinit()
timer = pygame.time.clock()
n1 = 0
n2 = 0
screen = pygame.display.set_mode((1200,800))
for x in range(10000):
t = begin_a_game(n1,n2);
if t == 1:
n1 +=1
else:
n2 += 1
敲了一天有点脑子糊了(キ`゚Д゚´)!!
8丶打兵乓球
实现效果:
源码分享:
import sys
import config
import pygame
from sprites 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+bheigth),5)
pygame.draw.Line(screen,50,50,50),(left,top+bheight),(left,+bwidth,top+bheigth),5)
pygame.draw.Line(screen,50,50,50),(left+bwidth,top+bheight),(left+bwidth,top),5)
......省略部分.....
'''run'''
if __name__ =='__main__':
main()
9丶全民大战飞机
实现效果
源码分享:
import pygame
# 敌方子弹
class Small_n1s(pygame.sprite.Sprite):
def __init__(self,position,size):
pygame.sprite.Sprite.__init__(self)
# 设置子弹对象
self.image = pygame.image.load(r'image\aircraft_inage\small_n1s.png).convert_alpha()
self.rect = self.image.get_rect()
self.rect.left,self.rect.top = position[0] - 7,position[1]
self.speed = 15
self.action = True
self.width,self.height = size[0],size[1]
self.mask = pygame.mask.from_surface(self.image)
...省略部分...
def reset(self):
self.action = True
self.hit = False
self.energy =30
self.rect.left,self.rect.top = randint(0,self.width - self.rect.width),\
randint(-15*self.heightm-self.height)
10丶一站到底
实现效果:
源码分享:
import easygui as 界面
用户名称 = 界面.enterbox('请输入您的姓名:','小明一站到底')
界面.msgbox('欢迎登陆:'+用户名称,
'小明一站到底!')
成绩 = 0
第一答案 = 界面.enterbpc('''第一题:‘铁观音’茶的原产发源地在中国哪个省份?
1.浙江 2.湖北 3.湖南 4.福建''',''风俗相关'')
if 第一题答案 == '4':
界面.msgbox('恭喜你,答对了');
成绩 +=25
elif 第一题答案 in(''1'',''2'',''3''):
界面.msgbox(''你确定吗?'')
else:
界面.msgbox(''输入错误'')
....第二题目(依次类推).....
....第N题目.........................
if 成绩 < 60:
界面.msgbox(''您的成绩为:'' + str(成绩) + ',不用一站到底了,站不住了!',''不及格'')
elif 成绩 <80:
界面.msgbox(''您的成绩为:'' + str(成绩) + ',凑合还能站住,继续加油!',''勉强'')
else:
界面.msgbox(''您的成绩为:'' + str(成绩) + ',游戏一站到底,金鸡独立!',''优秀'')
这样的小游戏,上班摸鱼岂不是美哉😜
具体项目源码,实现效果:
关注公众号:Python技术训练营
解锁 :
《1.python百万字教程,手把手助你从零进阶拿高薪》
《2.2023python开发岗面试汇总大全》
《3.python10个上班摸鱼小游戏项目源码》