本文主要介绍一个用Python写的经典游戏合集,包括:贪吃蛇、扫雷、俄罗斯方块、五子棋。有兴趣的朋友可以跟边肖学习一下。
目录
一、效果展示1、俄罗斯方块2、扫雷3、五子棋4、蛇2、代码展示1、俄罗斯方块2、扫雷3、五子棋4、蛇2。
一、效果展示
1、俄罗斯方块
这个应该是最容易玩的…
2、扫雷
幸运的是,我没有在四次点击后踩雷。哈哈…
3、五子棋
我是菜鸡,打不过电脑人…
4、贪吃蛇
害,这是最惊心动魄的,为了我的小心脏,别玩了…
女朋友:你只是趁机玩了个游戏,抓住了。
啊,这个.
那我就不吹牛了,大家敲码吧~
二、代码展示
1、俄罗斯方块
部分正方形
这部分代码单独保存py文件,我在这里命名为blocks.py。
正方形的设计,一开始,我做的是4 4。如果长、宽、最长都是4,我旋转它的时候不考虑怎么转,就是把一个图形换成另一个图形。
要实现这个功能,只需固定左上角的坐标即可。
随机导入
从集合导入命名元组
Point=namedtuple('Point ',' X Y ')
Shape=namedtuple('Shape ',' X Y宽度高度')
Block=namedtuple('Block ',' template start _ pos end _ pos name next ')
# S广场
S_BLOCK=[Block(['。OO ',
“哦,”,
'.'],点(0,0),点(2,1),' S ',1),
块(['O . ',
“哦,”,
. O.'],点(0,0),点(1,2),' S ',0)]
# Z形正方形
Z_BLOCK=[Block(['OO。OO ',
'.'],点(0,0),点(2,1),' Z ',1),
块([' o . ',
“哦,”,
“哦.”],点(0,0),点(1,2),' Z ',0)]
#我的广场
I_BLOCK=[Block(['。“哦.”,“哦.”,“哦.”,“哦.”],Point(1,0),Point(1,3),' I ',1),
块([' .
'.',
呜,
'.'],点(0,2),点(3,2),' I ',0)]
# O块
O_BLOCK=[Block(['OO ',
OO'],Point(0,0),Point(1,1),' O ',0)]
# J广场
J_BLOCK=[Block(['O . ',
OOO,
'.'],Point(0,0),Point(2,1),' J ',1),
块(['。OO ',
' o '
. O.'],点(1,0),点(2,2),' J ',2),
块([' . ',
OOO,
'.O'],点(0,1),点(2,2),' J ',3),
块([' o . ',
' o '
“哦,”],点(0,0),点(1,2),' J ',0)]
# L形正方形
L_BLOCK=[Block(['.o ',
OOO,
'.'],点(0,0),点(2,1),' L ',1),
块([' o . ',
' o '。OO'],Point(1,0),Point(2,2),' L ',2),
块([' . ',
OOO,
“哦.”],点(0,1),点(2,2),' L ',3),
块(['OO。
' o '
. O.'],点(0,0),点(1,2),' L ',0)]
# T形方形
t _ BLOCK=[BLOCK([' o . ',
OOO,
'.'],Point(0,0),Point(2,1),' T ',1),
块([' o . '。OO ',
. O.'],点(1,0),点(2,2),' T ',2),
块([' . ',
OOO,
. O.'],点(0,1),点(2,2),' T ',3),
块([' o . ',
“哦,”,
. O.'],点(0,0),点(1,2),' T ',0)]
BLOCKS={'O': O_BLOCK,
' I': I_BLOCK,
Z': Z_BLOCK,
T': T_BLOCK,
' L': L_BLOCK,
S': S_BLOCK,
J': J_BLOCK}
def get_block():
block _ name=random . choice(' OIZTLSJ ')
b=块[块名]
idx=random.randint(0,len(b) - 1)
返回b[idx]
def get_next_block(block):
b=BLOCKS[block.name]
返回b[block.next]
游戏主代码
导入系统
导入时间
导入pygame
从pygame.locals导入*
导入块
尺寸=30 #每个小方格大小
BLOCK_HEIGHT=25 #游戏区高度
BLOCK_WIDTH=10 #游戏区宽度
BORDER_WIDTH=4 #游戏区边框宽度
BORDER_COLOR=(40,40,200) #游戏区边框颜色
SCREEN _ WIDTH=SIZE *(BLOCK _ WIDTH 5)#游戏屏幕的宽
SCREEN _ HEIGHT=SIZE * BLOCK _ HEIGHT #游戏屏幕的高
BG_COLOR=(40,40,60) #背景色
BLOCK_COLOR=(20,128,200) #
黑色=(0,0,0)
RED=(200,30,30) #游戏结束的字体颜色
def print_text(screen,font,x,y,text,fcolor=(255,255,255)):
imgText=font.render(text,True,fcolor)
screen.blit(imgText,(x,y))
def main():
pygame.init()
屏幕=py游戏。展示。set _ mode((屏幕_宽度,屏幕_高度))
pygame.display.set_caption('俄罗斯方块)
font 1=py游戏。字体。sys font(' sim hei ',24) #黑体24
font2=pygame.font.Font(None,72) #游戏结束的字体
font _ pos _ x=BLOCK _ WIDTH * SIZE BORDER _ WIDTH 10 #右侧信息显示区域字体位置的X坐标
gameover_size=font2.size("游戏结束")
font1_height=int(font1.size('得分')[1])
cur_block=None #当前下落方块
next_block=None #下一个方块
当前位置x,当前位置y=0,0
game_area=无#整个游戏区域
游戏结束=真
start=False #是否开始,当start=True,game_over=True时,才显示游戏结束
分数=0 #得分
orispeed=0.5 #原始速度
速度=或速度#当前速度
暂停=假#暂停
最后一次丢弃时间=无#上次下落时间
最后一次新闻时间=无#上次按键时间
def _dock():
非本地cur_block,next_block,game_area,cur_pos_x,cur_pos_y,game_over分数,速度
for _ I in range(cur _ block。开始位置.y,cur_block.end_pos .Y 1):
for _ j in range(cur _ block。开始位置.x,cur_block.end_pos .X 1):
if cur_block.template[_i][_j]!='.':
game _ area[cur _ pos _ y _ I][cur _ pos _ x _ j]=' 0 '
if cur_pos_y cur_block .Y=0:
游戏结束=真
否则:
# 计算消除
remove_idxs=[]
for _ I in range(cur _ block。开始位置.y,cur_block.end_pos .Y 1):
如果all(_ x==' 0 ' for _ x in game _ area[cur _ pos _ y _ I]):
移除_idxs.append(cur_pos_y _i)
if remove_idxs:
# 计算得分
移除_计数=len(移除_idxs)
如果移除计数==1:
分数=100
elif remove_count==2:
分数=300
否则如果移除计数==3:
分数=700
elif remove _ count==:
分数=1500
速度=或速度-0.03 *(分数//10000)
# 消除
_i=_j=remove_idxs[-1]
while _i=0:
移除_idxs中的while _j:
_j -=1
if _j 0:
game_area[_i]=[' . '] *块宽
否则:
游戏区[_i]=游戏区[_j]
_i -=1
_j -=1
cur_block=next_block
next_block=blocks.get_block()
cur_pos_x,cur _ pos _ y=(BLOCK _ WIDTH-cur _ BLOCK。end _ pos .X - 1) //2,-1 - cur_block.end_pos .Y
def _judge(位置x,位置y,块):
非本地游戏区
for _i in range(block.start_pos .y,block.end_pos .Y 1):
if pos_y block.end_pos .Y=块高度:
返回错误的
for _j in range(block.start_pos .x,block.end_pos .X 1):
如果pos_y _i=0且block.template[_i][_j]!='.'还有游戏_区域[pos_y _i][pos_x _j]!='.':
返回错误的
返回真实的
虽然正确:
对于pygame.event.get()中的事件:
如果event.type==退出:
sys.exit()
elif event.type==KEYDOWN:
if event.key==K_RETURN:
如果游戏结束:
开始=真
游戏结束=假
分数=0
last_drop_time=time.time()
last_press_time=time.time()
game_area=[[' . '] *块宽度为_英寸范围(块_高度)]
cur_block=blocks.get_block()
next_block=blocks.get_block()
cur_pos_x,cur _ pos _ y=(BLOCK _ WIDTH-cur _ BLOCK。end _ pos .X - 1) //2,-1 - cur_block.end_pos .Y
elif event.key==K_SPACE:
如果游戏没有结束:
暂停=不暂停
elif event.key in (K_w,K_UP):
if 0=cur _ pos _ x=BLOCK _ WIDTH-len(cur _ BLOCK。模板[0]):
_ next _ block=块。get _ next _ block(当前块)
if _judge(cur_pos_x,cur_pos_y,_next_block):
cur_block=_next_block
if event.type==pygame .按键:
if event.key==pygame .K_LEFT:
如果游戏没有结束并且没有暂停:
如果时间。time()-last _ press _ time 0.1:
last_press_time=time.time()
if cur _ pos _ x-cur _ block。开始位置.x:
if _judge(当前位置x - 1,当前位置y,当前块):
cur_pos_x -=1
if event.key==pygame .K_RIGHT:
如果游戏没有结束并且没有暂停:
如果时间。time()-last _ press _ time 0.1:
last_press_time=time.time()
# 不能移除右边框
if cur_pos_x cur_block。X 1块宽:
if _judge(cur_pos_x 1,cur_pos_y,cur_block):
cur_pos_x=1
if event.key==pygame .K_DOWN:
如果游戏没有结束并且没有暂停:
如果时间。time()-last _ press _ time 0.1:
last_press_time=time.time()
如果不是_judge(cur_pos_x,cur_pos_y 1,cur_block):
_dock()
否则:
last_drop_time=time.time()
cur_pos_y=1
_ draw _背景(屏幕)
_draw_game_area(屏幕,游戏区)
_ draw _ gridlines(屏幕)
_绘图_信息(屏幕,字体1,字体位置x,字体一高度,分数)
# 画显示信息中的下一个方块
_draw_block(screen,next_block,font_pos_x,30 (font1_height 6) * 5,0,0)
如果游戏没有结束:
cur_drop_time=time.time()
如果当前丢弃时间-最后丢弃时间速度:
如果没有暂停:
如果不是_judge(cur_pos_x,cur_pos_y 1,cur_block):
_dock()
否则:
最后丢弃时间=当前丢弃时间
cur_pos_y=1
否则:
如果开始:
打印文本(屏幕,字体2,
(SCREEN _ WIDTH-game over _ size[0])//2,(SCREEN _ HEIGHT-game over _ size[1])//2,
游戏结束,红色)
# 画当前下落方块
_draw_block(screen,cur_block,0,0,cur_pos_x,cur_pos_y)
pygame.display.flip()
# 画背景
定义_绘制_背景(屏幕):
# 填充背景色
屏幕填充(背景颜色)
# 画游戏区域分隔线
pygame.draw.line(screen,BORDER_COLOR,
(SIZE * BLOCK _ WIDTH BORDER _ WIDTH//2,0),
(SIZE * BLOCK _ WIDTH BORDER_WIDTH//2,SCREEN_HEIGHT),BORDER _ WIDTH)
# 画网格线
定义_绘制_网格线(屏幕):
# 画网格线竖线
对于范围内的x(块宽度):
pygame.draw.line(screen,BLACK,(x * SIZE,0),(x * SIZE,SCREEN_HEIGHT),1)
# 画网格线横线
对于范围内的y(块高度):
pygame.draw.line(screen,BLACK,(0,y * SIZE),(BLOCK_WIDTH * SIZE,y * SIZE),1)
# 画已经落下的方块
def _draw_game_area(屏幕,游戏_区域):
如果游戏_区域:
对于我,枚举中的行(游戏_区域):
对于j,枚举中的单元格(行):
如果细胞!='.':
pygame.draw.rect(screen,BLOCK_COLOR,(j * SIZE,i * SIZE,SIZE,SIZE),0)
# 画单个方块
定义_绘制_块(屏幕,块,偏移量_x,偏移量_y,位置_x,位置_y):
如果阻止:
对于范围内的我(拦。开始位置.y,block.end_pos .Y 1):
对于范围内的j(块。开始位置.x,block.end_pos .X 1):
if block.template[i][j]!='.':
pygame.draw.rect(screen,BLOCK_COLOR,
(offset_x (pos_x j) * SIZE,offset_y (pos_y i) * SIZE,SIZE,SIZE),0)
# 画得分等信息
定义_绘图_信息(屏幕、字体、位置x,字体高度、分数):
print_text(screen,font,pos_x,10,f '得分: ')
print_text(screen,font,pos_x,10 font_height 6,f"{ score } ")
print_text(screen,font,pos_x,20 (font_height 6) * 2,f '速度: ')
print_text(screen,font,pos_x,20 (font_height 6) * 3,f'{score //10000} ')
print_text(screen,font,pos_x,30 (font_height 6) * 4,f '下一个:')
if __name__=='__main__ ':
主()
2、扫雷
地雷部分
一样的,单独保存巴拉圭文件,mineblock.py
随机导入
从枚举导入枚举
BLOCK_WIDTH=30
BLOCK_HEIGHT=16
尺寸=20 #块大小
MINE_COUNT=99 #地雷数
类块状态(枚举):
正常=1 #未点击
打开=2 #已点击
我的=3 #地雷
flag=4 #标记为地雷
ask=5 #标记为问号
炸弹=6 #踩中地雷
提示=7 #被双击的周围
double=8 #正被鼠标左右键双击
地雷等级:
def __init__(self,x,y,value=0):
自我. x=x
自我. y=y
自我. value=0
自我. around_mine_count=-1
自我. status=BlockStatus.normal
自我设置值(值)
def __repr__(self):
返回字符串(自我._value)
# return f'({self ._x}、{self ._y})={self ._value},status={self.status} '
def get_x(self):
回归自我. x
def set_x(self,x):
自我. x=x
x=属性(fget=get_x,fset=set_x)
def get_y(自身):
回归自我. y
def set_y(self,y):
自我. y=y
y=属性(fget=get_y,fset=set_y)
定义获取值(自身):
回归自我。_值
定义集合值(自身,值):
如果值:
自我. value=1
否则:
自我. value=0
value=property(fget=get_value,fset=set_value,doc='0:非地雷1:雷)
def get_around_mine_count(self):
回归自我。_围绕_我的_计数
def set_around_mine_count(self,around_mine_count):
自我我的周围。计数=我的周围_计数
around _ mine _ count=property(fget=get _ around _ mine _ count,fset=set_around_mine_count,doc='四周地雷数量)
定义获取状态(自身):
回归自我。_状态
定义集合_状态(自身,值):
自我. status=值
status=property(fget=get _ status,fset=set_status,doc='BlockStatus ')
等级矿块:
def __init__(self):
自我. block=[[Mine(i,j)for I in range(BLOCK _ WIDTH)]for j in range(BLOCK _ HEIGHT)]
# 埋雷
对于我在胡乱猜测。样本(范围(块宽*块高),矿数):
自我. block[i //块宽度][i %块宽度]。值=1
def get_block(self):
回归自我。_阻止
block=property(fget=get_block)
def getmine(self,x,y):
回归自我. block[y][x]
def open_mine(self,x,y):
# 踩到雷了
如果自我. block[y][x].价值:
自我. block[y][x].status=BlockStatus.bomb
返回错误的
# 先把状态改为开的
自我. block[y][x].status=BlockStatus.opened
around=_get_around(x,y)
_sum=0
对于我,j在左右:
如果自我块[j][i].价值:
_sum=1
自我. block[y][x].大约_mine_count=_sum
# 如果周围没有雷,那么将周围8个未中未点开的递归算一遍
# 这就能实现一点出现一大片打开的效果了
if _sum==0:
对于我,j在左右:
如果自我块[j][i].around_mine_count==-1:
self.open_mine(i,j)
返回真实的
def double _ mouse _ button _ down(self,x,y):
如果自我. block[y][x].about _ mine _ count==:
返回真实的
自我. block[y][x].status=BlockStatus.double
around=_get_around(x,y)
sumflag=0 #周围被标记的雷数量
对于I,j in _get_around(x,y):
如果自我块[j][i].status==BlockStatus.flag:
sumflag=1
# 周边的雷已经全部被标记
结果=真
如果sumflag==self ._block[y][x].大约_我的_计数:
对于我,j在左右:
如果自我块[j][i].状态==BlockStatus.normal
如果不是self.open_mine(i,j):
结果=假
否则:
对于我,j在左右:
如果自我块[j][i].状态==BlockStatus.normal
自我块[j][i].status=BlockStatus.hint
回送结果
def double_mouse_button_up(self,x,y):
自我. block[y][x].status=BlockStatus.opened
对于I,j in _get_around(x,y):
如果自我块[j][i].状态==块状态。提示:
自我块[j][i].状态=块状态.正常
def _get_around(x,y):
'''返回(x,y)周围的点的坐标'''
# 这里注意,范围末尾是开区间,所以要加一
return [(i,j) for i in range(max(0,x - 1),min(BLOCK_WIDTH - 1,x-1)1)
对于范围内的j(max(0,y - 1),min(BLOCK_HEIGHT - 1,y-1)1)如果我!=x或者j!=y]
素材
主代码
导入系统
导入时间
从枚举导入枚举
导入pygame
从pygame.locals导入*
从雷区导入*
# 游戏屏幕的宽
SCREEN_WIDTH=BLOCK_WIDTH * SIZE
# 游戏屏幕的高
SCREEN _ HEIGHT=(BLOCK _ HEIGHT 2)* SIZE
类游戏状态(枚举):
就绪=1,
开始=2,
over=3,
win=4
def print_text(screen,font,x,y,text,fcolor=(255,255,255)):
imgText=font.render(text,True,fcolor)
screen.blit(imgText,(x,y))
def main():
pygame.init()
屏幕=py游戏。展示。set _ mode((屏幕_宽度,屏幕_高度))
pygame.display.set_caption('扫雷)
font 1=py游戏。字体。font(' resources/a . TTF ',SIZE * 2) #得分的字体
fwidth,FH height=font 1。大小(' 999 ')
红色=(200,40,40)
# 加载资源图片,因为资源文件大小不一,所以做了统一的缩放处理
img 0=py游戏。形象。load(' resources/0。BMP’).转换()
img 0=py游戏。转变。平滑缩放(img 0,(大小,大小))
img 1=py游戏。形象。加载(' resources/1。BMP’).转换()
img 1=py游戏。转变。平滑缩放(img 1,(大小,大小))
img 2=py游戏。形象。加载(' resources/2。BMP’).转换()
img 2=py游戏。转变。平滑缩放(img 2,(大小,大小))
img 3=py游戏。形象。加载('资源/3。BMP’).转换()
img 3=py游戏。转变。平滑缩放(img 3,(大小,大小))
im G4=py游戏。形象。加载(' resources/4。BMP’).转换()
img 4=py游戏。转变。平滑缩放(img 4,(大小,大小))
im G5=py游戏。形象。加载(' resources/5。BMP’).转换()
im G5=py游戏。转变。平滑刻度(im G5,(大小,尺寸))
im g6=py游戏。形象。加载(' resources/6。BMP’).转换()
im g6=py游戏。转变。平滑缩放(im g6,(大小,大小))
im G7=py游戏。形象。加载(' resources/7。BMP’).转换()
im G7=py游戏。转变。平滑缩放(im G7,(大小,大小))
im G8=py游戏。形象。加载(' resources/8。BMP’).转换()
im G8=py游戏。转变。平滑缩放(im G8,(大小,大小))
img _ blank=py游戏。形象。加载('资源/空白。BMP’).转换()
img _ blank=py游戏。转变。平滑缩放(img _ blank,(大小,大小))
img _ flag=py游戏。形象。load(' resources/flag。BMP’).转换()
img _ flag=py游戏。转变。平滑缩放(img _ flag,(SIZE,SIZE))
img _ ask=py游戏。形象。加载('资源/ask。BMP’).转换()
img _ ask=py游戏。转变。平滑缩放(img _ ask,(大小,大小))
img _ mine=py游戏。形象。加载('资源/矿。BMP’).转换()
img _ mine=py游戏。转变。平滑缩放(img _ mine,(大小,大小))
img _ blood=py游戏。形象。加载('资源/血。BMP’).转换()
img _ blood=py游戏。转变。平滑缩放(img _ blood,(大小,大小))
img _ error=py游戏。形象。加载('资源/错误。BMP’).转换()
img _ error=py游戏。转变。平滑缩放(img _ error,(SIZE,SIZE))
face_size=int(SIZE * 1.25)
img _ face _ fail=py游戏。形象。load(' resources/face _ fail。BMP’).转换()
img _ face _ fail=py游戏。转变。平滑缩放(img _ face _ fail,(face_size,face_size))
img _ face _ normal=py游戏。形象。load(' resources/face _ normal。BMP’).转换()
img _ face _ normal=py游戏。转变。平滑缩放(img _ face _ normal,(face_size,face_size))
img _ face _ success=py游戏。形象。load(' resources/face _ success。BMP’).转换()
img _ face _ success=py游戏。转变。平滑缩放(img _ face _ success,(face_size,face_size))
face_pos_x=(SC
REEN_WIDTH - face_size) // 2 face_pos_y = (SIZE * 2 - face_size) // 2 img_dict = { 0: img0, 1: img1, 2: img2, 3: img3, 4: img4, 5: img5, 6: img6, 7: img7, 8: img8 } bgcolor = (225, 225, 225) # 背景色 block = MineBlock() game_status = GameStatus.readied start_time = None # 开始时间 elapsed_time = 0 # 耗时 while True: # 填充背景色 screen.fill(bgcolor) for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == MOUSEBUTTONDOWN: mouse_x, mouse_y = event.pos x = mouse_x // SIZE y = mouse_y // SIZE - 2 b1, b2, b3 = pygame.mouse.get_pressed() if game_status == GameStatus.started: # 鼠标左右键同时按下,如果已经标记了所有雷,则打开周围一圈 # 如果还未标记完所有雷,则有一个周围一圈被同时按下的效果 if b1 and b3: mine = block.getmine(x, y) if mine.status == BlockStatus.opened: if not block.double_mouse_button_down(x, y): game_status = GameStatus.over elif event.type == MOUSEBUTTONUP: if y < 0: if face_pos_x <= mouse_x <= face_pos_x + face_size \ and face_pos_y <= mouse_y <= face_pos_y + face_size: game_status = GameStatus.readied block = MineBlock() start_time = time.time() elapsed_time = 0 continue if game_status == GameStatus.readied: game_status = GameStatus.started start_time = time.time() elapsed_time = 0 if game_status == GameStatus.started: mine = block.getmine(x, y) if b1 and not b3: # 按鼠标左键 if mine.status == BlockStatus.normal: if not block.open_mine(x, y): game_status = GameStatus.over elif not b1 and b3: # 按鼠标右键 if mine.status == BlockStatus.normal: mine.status = BlockStatus.flag elif mine.status == BlockStatus.flag: mine.status = BlockStatus.ask elif mine.status == BlockStatus.ask: mine.status = BlockStatus.normal elif b1 and b3: if mine.status == BlockStatus.double: block.double_mouse_button_up(x, y) flag_count = 0 opened_count = 0 for row in block.block: for mine in row: pos = (mine.x * SIZE, (mine.y + 2) * SIZE) if mine.status == BlockStatus.opened: screen.blit(img_dict[mine.around_mine_count], pos) opened_count += 1 elif mine.status == BlockStatus.double: screen.blit(img_dict[mine.around_mine_count], pos) elif mine.status == BlockStatus.bomb: screen.blit(img_blood, pos) elif mine.status == BlockStatus.flag: screen.blit(img_flag, pos) flag_count += 1 elif mine.status == BlockStatus.ask: screen.blit(img_ask, pos) elif mine.status == BlockStatus.hint: screen.blit(img0, pos) elif game_status == GameStatus.over and mine.value: screen.blit(img_mine, pos) elif mine.value == 0 and mine.status == BlockStatus.flag: screen.blit(img_error, pos) elif mine.status == BlockStatus.normal: screen.blit(img_blank, pos) print_text(screen, font1, 30, (SIZE * 2 - fheight) // 2 - 2, '%02d' % (MINE_COUNT - flag_count), red) if game_status == GameStatus.started: elapsed_time = int(time.time() - start_time) print_text(screen, font1, SCREEN_WIDTH - fwidth - 30, (SIZE * 2 - fheight) // 2 - 2, '%03d' % elapsed_time, red) if flag_count + opened_count == BLOCK_WIDTH * BLOCK_HEIGHT: game_status = GameStatus.win if game_status == GameStatus.over: screen.blit(img_face_fail, (face_pos_x, face_pos_y)) elif game_status == GameStatus.win: screen.blit(img_face_success, (face_pos_x, face_pos_y)) else: screen.blit(img_face_normal, (face_pos_x, face_pos_y)) pygame.display.update() if __name__ == '__main__': main()3、五子棋
五子棋就没那么多七七八八的素材和其它代码了
import sys import random import pygame from pygame.locals import * import pygame.gfxdraw from collections import namedtuple Chessman = namedtuple('Chessman', 'Name Value Color') Point = namedtuple('Point', 'X Y') BLACK_CHESSMAN = Chessman('黑子', 1, (45, 45, 45)) WHITE_CHESSMAN = Chessman('白子', 2, (219, 219, 219)) offset = [(1, 0), (0, 1), (1, 1), (1, -1)] class Checkerboard: def __init__(self, line_points): self._line_points = line_points self._checkerboard = [[0] * line_points for _ in range(line_points)] def _get_checkerboard(self): return self._checkerboard checkerboard = property(_get_checkerboard) # 判断是否可落子 def can_drop(self, point): return self._checkerboard[point.Y][point.X] == 0 def drop(self, chessman, point): """ 落子 :param chessman: :param point:落子位置 :return:若该子落下之后即可获胜,则返回获胜方,否则返回 None """ print(f'{chessman.Name} ({point.X}, {point.Y})') self._checkerboard[point.Y][point.X] = chessman.Value if self._win(point): print(f'{chessman.Name}获胜') return chessman # 判断是否赢了 def _win(self, point): cur_value = self._checkerboard[point.Y][point.X] for os in offset: if self._get_count_on_direction(point, cur_value, os[0], os[1]): return True def _get_count_on_direction(self, point, value, x_offset, y_offset): count = 1 for step in range(1, 5): x = point.X + step * x_offset y = point.Y + step * y_offset if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value: count += 1 else: break for step in range(1, 5): x = point.X - step * x_offset y = point.Y - step * y_offset if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value: count += 1 else: break return count >= 5 SIZE = 30 # 棋盘每个点时间的间隔 Line_Points = 19 # 棋盘每行/每列点数 Outer_Width = 20 # 棋盘外宽度 Border_Width = 4 # 边框宽度 Inside_Width = 4 # 边框跟实际的棋盘之间的间隔 Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width # 边框线的长度 Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width # 网格线起点(左上角)坐标 SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2 # 游戏屏幕的高 SCREEN_WIDTH = SCREEN_HEIGHT + 200 # 游戏屏幕的宽 Stone_Radius = SIZE // 2 - 3 # 棋子半径 Stone_Radius2 = SIZE // 2 + 3 Checkerboard_Color = (0xE3, 0x92, 0x65) # 棋盘颜色 BLACK_COLOR = (0, 0, 0) WHITE_COLOR = (255, 255, 255) RED_COLOR = (200, 30, 30) BLUE_COLOR = (30, 30, 200) RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10 def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)): imgText = font.render(text, True, fcolor) screen.blit(imgText, (x, y)) def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('五子棋') font1 = pygame.font.SysFont('SimHei', 32) font2 = pygame.font.SysFont('SimHei', 72) fwidth, fheight = font2.size('黑方获胜') checkerboard = Checkerboard(Line_Points) cur_runner = BLACK_CHESSMAN winner = None computer = AI(Line_Points, WHITE_CHESSMAN) black_win_count = 0 white_win_count = 0 while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: if event.key == K_RETURN: if winner is not None: winner = None cur_runner = BLACK_CHESSMAN checkerboard = Checkerboard(Line_Points) computer = AI(Line_Points, WHITE_CHESSMAN) elif event.type == MOUSEBUTTONDOWN: if winner is None: pressed_array = pygame.mouse.get_pressed() if pressed_array[0]: mouse_pos = pygame.mouse.get_pos() click_point = _get_clickpoint(mouse_pos) if click_point is not None: if checkerboard.can_drop(click_point): winner = checkerboard.drop(cur_runner, click_point) if winner is None: cur_runner = _get_next(cur_runner) computer.get_opponent_drop(click_point) AI_point = computer.AI_drop() winner = checkerboard.drop(cur_runner, AI_point) if winner is not None: white_win_count += 1 cur_runner = _get_next(cur_runner) else: black_win_count += 1 else: print('超出棋盘区域') # 画棋盘 _draw_checkerboard(screen) # 画棋盘上已有的棋子 for i, row in enumerate(checkerboard.checkerboard): for j, cell in enumerate(row): if cell == BLACK_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color) elif cell == WHITE_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color) _draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count) if winner: print_text(screen, font2, (SCREEN_WIDTH - fwidth)//2, (SCREEN_HEIGHT - fheight)//2, winner.Name + '获胜', RED_COLOR) pygame.display.flip() def _get_next(cur_runner): if cur_runner == BLACK_CHESSMAN: return WHITE_CHESSMAN else: return BLACK_CHESSMAN # 画棋盘 def _draw_checkerboard(screen): # 填充棋盘背景色 screen.fill(Checkerboard_Color) # 画棋盘网格线外的边框 pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width) # 画网格线 for i in range(Line_Points): pygame.draw.line(screen, BLACK_COLOR, (Start_Y, Start_Y + SIZE * i), (Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i), 1) for j in range(Line_Points): pygame.draw.line(screen, BLACK_COLOR, (Start_X + SIZE * j, Start_X), (Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)), 1) # 画星位和天元 for i in (3, 9, 15): for j in (3, 9, 15): if i == j == 9: radius = 5 else: radius = 3 # pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius) pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR) pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR) # 画棋子 def _draw_chessman(screen, point, stone_color): # pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius) pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color) pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color) # 画左侧信息显示 def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count): _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), BLACK_CHESSMAN.Color) _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), WHITE_CHESSMAN.Color) print_text(screen, font, RIGHT_INFO_POS_X, Start_X + 3, '玩家', BLUE_COLOR) print_text(screen, font, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3 + 3, '电脑', BLUE_COLOR) print_text(screen, font, SCREEN_HEIGHT, SCREEN_HEIGHT - Stone_Radius2 * 8, '战况:', BLUE_COLOR) _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - int(Stone_Radius2 * 4.5)), BLACK_CHESSMAN.Color) _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - Stone_Radius2 * 2), WHITE_CHESSMAN.Color) print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - int(Stone_Radius2 * 5.5) + 3, f'{black_win_count} 胜', BLUE_COLOR) print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - Stone_Radius2 * 3 + 3, f'{white_win_count} 胜', BLUE_COLOR) def _draw_chessman_pos(screen, pos, stone_color): pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color) pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color) # 根据鼠标点击位置,返回游戏区坐标 def _get_clickpoint(click_pos): pos_x = click_pos[0] - Start_X pos_y = click_pos[1] - Start_Y if pos_x < -Inside_Width or pos_y < -Inside_Width: return None x = pos_x // SIZE y = pos_y // SIZE if pos_x % SIZE > Stone_Radius: x += 1 if pos_y % SIZE > Stone_Radius: y += 1 if x >= Line_Points or y >= Line_Points: return None return Point(x, y) class AI: def __init__(self, line_points, chessman): self._line_points = line_points self._my = chessman self._opponent = BLACK_CHESSMAN if chessman == WHITE_CHESSMAN else WHITE_CHESSMAN self._checkerboard = [[0] * line_points for _ in range(line_points)] def get_opponent_drop(self, point): self._checkerboard[point.Y][point.X] = self._opponent.Value def AI_drop(self): point = None score = 0 for i in range(self._line_points): for j in range(self._line_points): if self._checkerboard[j][i] == 0: _score = self._get_point_score(Point(i, j)) if _score > score: score = _score point = Point(i, j) elif _score == score and _score > 0: r = random.randint(0, 100) if r % 2 == 0: point = Point(i, j) self._checkerboard[point.Y][point.X] = self._my.Value return point def _get_point_score(self, point): score = 0 for os in offset: score += self._get_direction_score(point, os[0], os[1]) return score def _get_direction_score(self, point, x_offset, y_offset): count = 0 # 落子处我方连续子数 _count = 0 # 落子处对方连续子数 space = None # 我方连续子中有无空格 _space = None # 对方连续子中有无空格 both = 0 # 我方连续子两端有无阻挡 _both = 0 # 对方连续子两端有无阻挡 # 如果是 1 表示是边上是我方子,2 表示敌方子 flag = self._get_stone_color(point, x_offset, y_offset, True) if flag != 0: for step in range(1, 6): x = point.X + step * x_offset y = point.Y + step * y_offset if 0 <= x < self._line_points and 0 <= y < self._line_points: if flag == 1: if self._checkerboard[y][x] == self._my.Value: count += 1 if space is False: space = True elif self._checkerboard[y][x] == self._opponent.Value: _both += 1 break else: if space is None: space = False else: break # 遇到第二个空格退出 elif flag == 2: if self._checkerboard[y][x] == self._my.Value: _both += 1 break elif self._checkerboard[y][x] == self._opponent.Value: _count += 1 if _space is False: _space = True else: if _space is None: _space = False else: break else: # 遇到边也就是阻挡 if flag == 1: both += 1 elif flag == 2: _both += 1 if space is False: space = None if _space is False: _space = None _flag = self._get_stone_color(point, -x_offset, -y_offset, True) if _flag != 0: for step in range(1, 6): x = point.X - step * x_offset y = point.Y - step * y_offset if 0 <= x < self._line_points and 0 <= y < self._line_points: if _flag == 1: if self._checkerboard[y][x] == self._my.Value: count += 1 if space is False: space = True elif self._checkerboard[y][x] == self._opponent.Value: _both += 1 break else: if space is None: space = False else: break # 遇到第二个空格退出 elif _flag == 2: if self._checkerboard[y][x] == self._my.Value: _both += 1 break elif self._checkerboard[y][x] == self._opponent.Value: _count += 1 if _space is False: _space = True else: if _space is None: _space = False else: break else: # 遇到边也就是阻挡 if _flag == 1: both += 1 elif _flag == 2: _both += 1 score = 0 if count == 4: score = 10000 elif _count == 4: score = 9000 elif count == 3: if both == 0: score = 1000 elif both == 1: score = 100 else: score = 0 elif _count == 3: if _both == 0: score = 900 elif _both == 1: score = 90 else: score = 0 elif count == 2: if both == 0: score = 100 elif both == 1: score = 10 else: score = 0 elif _count == 2: if _both == 0: score = 90 elif _both == 1: score = 9 else: score = 0 elif count == 1: score = 10 elif _count == 1: score = 9 else: score = 0 if space or _space: score /= 2 return score # 判断指定位置处在指定方向上是我方子、对方子、空 def _get_stone_color(self, point, x_offset, y_offset, next): x = point.X + x_offset y = point.Y + y_offset if 0 <= x < self._line_points and 0 <= y < self._line_points: if self._checkerboard[y][x] == self._my.Value: return 1 elif self._checkerboard[y][x] == self._opponent.Value: return 2 else: if next: return self._get_stone_color(Point(x, y), x_offset, y_offset, False) else: return 0 else: return 0 if __name__ == '__main__': main()4、贪吃蛇
import random import sys import time import pygame from pygame.locals import * from collections import deque SCREEN_WIDTH = 600 # 屏幕宽度 SCREEN_HEIGHT = 480 # 屏幕高度 SIZE = 20 # 小方格大小 LINE_WIDTH = 1 # 网格线宽度 # 游戏区域的坐标范围 SCOPE_X = (0, SCREEN_WIDTH // SIZE - 1) SCOPE_Y = (2, SCREEN_HEIGHT // SIZE - 1) # 食物的分值及颜色 FOOD_STYLE_LIST = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))] LIGHT = (100, 100, 100) DARK = (200, 200, 200) # 蛇的颜色 BLACK = (0, 0, 0) # 网格线颜色 RED = (200, 30, 30) # 红色,GAME OVER 的字体颜色 BGCOLOR = (40, 40, 60) # 背景色 def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)): imgText = font.render(text, True, fcolor) screen.blit(imgText, (x, y)) # 初始化蛇 def init_snake(): snake = deque() snake.append((2, SCOPE_Y[0])) snake.append((1, SCOPE_Y[0])) snake.append((0, SCOPE_Y[0])) return snake def create_food(snake): food_x = random.randint(SCOPE_X[0], SCOPE_X[1]) food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1]) while (food_x, food_y) in snake: # 如果食物出现在蛇身上,则重来 food_x = random.randint(SCOPE_X[0], SCOPE_X[1]) food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1]) return food_x, food_y def get_food_style(): return FOOD_STYLE_LIST[random.randint(0, 2)] def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('贪吃蛇') font1 = pygame.font.SysFont('SimHei', 24) # 得分的字体 font2 = pygame.font.Font(None, 72) # GAME OVER 的字体 fwidth, fheight = font2.size('GAME OVER') # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER # b 变量就是用于防止这种情况的发生 b = True # 蛇 snake = init_snake() # 食物 food = create_food(snake) food_style = get_food_style() # 方向 pos = (1, 0) game_over = True start = False # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER score = 0 # 得分 orispeed = 0.5 # 原始速度 speed = orispeed last_move_time = None pause = False # 暂停 while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: if event.key == K_RETURN: if game_over: start = True game_over = False b = True snake = init_snake() food = create_food(snake) food_style = get_food_style() pos = (1, 0) # 得分 score = 0 last_move_time = time.time() elif event.key == K_SPACE: if not game_over: pause = not pause elif event.key in (K_w, K_UP): # 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER if b and not pos[1]: pos = (0, -1) b = False elif event.key in (K_s, K_DOWN): if b and not pos[1]: pos = (0, 1) b = False elif event.key in (K_a, K_LEFT): if b and not pos[0]: pos = (-1, 0) b = False elif event.key in (K_d, K_RIGHT): if b and not pos[0]: pos = (1, 0) b = False # 填充背景色 screen.fill(BGCOLOR) # 画网格线 竖线 for x in range(SIZE, SCREEN_WIDTH, SIZE): pygame.draw.line(screen, BLACK, (x, SCOPE_Y[0] * SIZE), (x, SCREEN_HEIGHT), LINE_WIDTH) # 画网格线 横线 for y in range(SCOPE_Y[0] * SIZE, SCREEN_HEIGHT, SIZE): pygame.draw.line(screen, BLACK, (0, y), (SCREEN_WIDTH, y), LINE_WIDTH) if not game_over: curTime = time.time() if curTime - last_move_time > speed: if not pause: b = True last_move_time = curTime next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1]) if next_s == food: # 吃到了食物 snake.appendleft(next_s) score += food_style[0] speed = orispeed - 0.03 * (score // 100) food = create_food(snake) food_style = get_food_style() else: if SCOPE_X[0] <= next_s[0] <= SCOPE_X[1] and SCOPE_Y[0] <= next_s[1] <= SCOPE_Y[1] \ and next_s not in snake: snake.appendleft(next_s) snake.pop() else: game_over = True # 画食物 if not game_over: # 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了 pygame.draw.rect(screen, food_style[1], (food[0] * SIZE, food[1] * SIZE, SIZE, SIZE), 0) # 画蛇 for s in snake: pygame.draw.rect(screen, DARK, (s[0] * SIZE + LINE_WIDTH, s[1] * SIZE + LINE_WIDTH, SIZE - LINE_WIDTH * 2, SIZE - LINE_WIDTH * 2), 0) print_text(screen, font1, 30, 7, f'速度: {score//100}') print_text(screen, font1, 450, 7, f'得分: {score}') if game_over: if start: print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER', RED) pygame.display.update() if __name__ == '__main__': main()以上就是Python实现四个经典小游戏合集的详细内容,更多关于Python游戏合集的资料请关注我们其它相关文章!
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。