python+pygame实现五子棋人机对战之二

python+pygame实现五子棋人机对战之一

有利一些基础的类,就可以开始编写主程序了。这是因为我们再编写程序的时候不是都有详细的设计才动手做,像这种非业务类程序通常是做一步看一步,慢慢拼凑出来的,说白了,就是脚踩西瓜皮,这才是这类程序开发常有的状态。

三、

有了基本类,现在是要显示在页面上来实现点击时可以有棋子显示出来。

没有涉及到核心逻辑,都是普通的代码:

# encoding:utf-8
import pygame
from pygame.locals import *
import sys
import os

import  piece
from params import Params
from utils import *

pygame.init()
pygame.mixer.init()

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
rows = int(Params.get('ROWS'))
blocksize = int(Params.get('blockSize'))
width = int(Params.get('WIDTH'))
height = int(Params.get('HEIGHT'))


# 棋盘
x = []    #x轴
y = []    #y轴

for i in range(0, rows):   #棋盘的所有交叉点坐标(x,y)
    x.append(28 + i * blocksize)
    y.append(28 + i * blocksize)

# 记录棋盘每个坐标的属性,没有棋子为0,白棋为1,黑棋为2
chess_map = {}    #结构是chess_map[28,28] = 0   ...


# 判断棋盘某位置上是否有棋子
def isempty(theposition):
    global chess_map
    existpiece = False
    if chess_map[str(theposition[0]) + ',' + str(theposition[1])]:
        existpiece = True
    return existpiece

# 电脑选取落子的位置
def computer():
    pass

# 初始化棋盘
def init():
    global chess_map
    for i in x:
        for j in y:
            chess_map[str(i) + ',' + str(j)] = 0   #清空


def main():
    bg_size = width, height
    os.environ['SDL_VIDEO_CENTERED'] = '1' 
    screen = pygame.display.set_mode(bg_size)
    pygame.display.set_caption('五子棋')
    bgimagepath = os.path.join(Params.get('resourcePath'), Params.get('imgFolder'), 'bg.png')
    bg_image = pygame.image.load(bgimagepath).convert_alpha()  # 背景图片加载

    zzimagepath = os.path.join(Params.get('resourcePath'), Params.get('imgFolder'), 'zz.png') #遮罩图片
    zz_image = pygame.image.load(zzimagepath).convert_alpha()

    # 背景音乐
    bgsoundpath = os.path.join(Params.get('resourcePath'), Params.get('soundFolder'), '齐豫 - 莲花处处开.mp3')
    bg_sound = pygame.mixer.music.load(bgsoundpath)   # 背景音乐加载
    pygame.mixer.music.set_volume(0.08)
    pygame.mixer.music.play(-1)

    clicksoundpath = os.path.join(Params.get('resourcePath'), Params.get('soundFolder'), 'drop.wav')
    piece_sound = pygame.mixer.Sound(clicksoundpath) 

    running = True

    clock = pygame.time.Clock()

    # 棋子
    white_chesses = []   #白棋子对象
    black_chesses = []   #黑棋子对象
    white_positions = [] #白棋子位置集合
    black_positions = [] #黑棋子位置集合
    chesses = []         #所有棋子集合,主要是显示用

    # 轮到哪方下棋,当is_player为True,表示轮到人下,为False表示轮到电脑下
    is_player = True 

    # 是否结束游戏
    is_finish = False

    # 赢方
    black_win = False   #黑棋赢
    white_win = False   #白棋赢

    # 人与人,后续开发网络版
    people2people = False

    # 人与电脑
    people2computer = False

    # 是否做出选择对战方式,是people2people 还是 people2computer , 通过菜单选择对战方式
    is_choise = False

    # 是否播放声音
    is_play_sound = True

    # 是否再来一局
    is_playagain = False

    # 字体
    fontpath = os.path.join(Params.get('resourcePath'), Params.get('fontFolder'), 'simkai.ttf')
    myfont = pygame.font.Font(fontpath, 38)

    # 起始选项
    txtplayerandplayer = myfont.render("玩家与玩家", True, WHITE)
    txtplayerandplayer_rect = txtplayerandplayer.get_rect()
    txtplayerandplayer_rect.left, txtplayerandplayer_rect.top = (bg_size[0] - txtplayerandplayer_rect.width) // 2, \
                                      (bg_size[1] - txtplayerandplayer_rect.height) // 2 - 100
    
    txtplayerandcomputer = myfont.render('玩家与电脑', True, WHITE)
    txtplayerandcomputer_rect = txtplayerandcomputer.get_rect()
    txtplayerandcomputer_rect.left, txtplayerandcomputer_rect.top = (bg_size[0] - txtplayerandplayer_rect.width) // 2, \
                                      (bg_size[1] - txtplayerandplayer_rect.height) // 2
    
    txtplaysound = myfont.render('音效:  开', True, WHITE)
    txtplaysound_rect = txtplaysound.get_rect()
    txtplaysound_rect.left, txtplaysound_rect.top = (bg_size[0] - txtplaysound_rect.width) // 2, \
                                      (bg_size[1] - txtplaysound_rect.height) // 2 + 100
    
    txtclosesound = myfont.render('音效:  关', True, WHITE)
    txtclosesound_rect = txtclosesound.get_rect()
    txtclosesound_rect.left, txtclosesound_rect.top = (bg_size[0] - txtclosesound_rect.width) // 2, \
                                      (bg_size[1] - txtclosesound_rect.height) // 2 + 100

     # 输赢
    successtext = myfont.render("你有点屌哦!!!", True, WHITE)
    successtext_rect = successtext.get_rect()
    successtext_rect.left, successtext_rect.top = (bg_size[0] - successtext_rect.width) // 2, \
                                            (bg_size[1] - successtext_rect.height) // 2
    failuretext = myfont.render("小趴菜...", True, WHITE)
    failuretext_rect = failuretext.get_rect()
    failuretext_rect.left, failuretext_rect.top = (bg_size[0] - failuretext_rect.width) // 2, \
                                              (bg_size[1] - failuretext_rect.height) // 2
    playagaintext = myfont.render("再玩一局", True, WHITE)
    menutext = myfont.render('主菜单', True, WHITE)


    # 初始化
    init()

    while running:
       
        screen.blit(bg_image, (0, 0))

        # 绘制游戏菜单
        if not is_choise:
            screen.blit(zz_image, (0, 0))  #遮罩层
            screen.blit(txtplayerandplayer, txtplayerandplayer_rect)
            screen.blit(txtplayerandcomputer, txtplayerandcomputer_rect)
            if not is_play_sound:
                screen.blit(txtclosesound, txtclosesound_rect)
            else:
                screen.blit(txtplaysound, txtplaysound_rect)

        # 绘制棋盘
        if is_choise:
            if chesses:
                for i in chesses:
                    screen.blit(i.image, i.image_rect())

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == MOUSEBUTTONDOWN:   #人下棋
                if event.button == 1:
                    if is_choise:
                        pos = pygame.mouse.get_pos()
                        # 判断是否是人下棋时间
                        if is_player  and not is_finish:
                            me = piece.Piece(pos,'pieces_white.png') 
                            if not isempty(me.pointtrans()):
                                white_chesses.append(me)
                                white_positions.append(me.pointtrans())
                                chesses.append(me)
                                chess_map[str(me.pointtrans()[0]) + ',' + str(me.pointtrans()[1])] = 1
                                is_player = False
                                piece_sound.play()
                            else:
                                del (me)

                    else:
                        pos = pygame.mouse.get_pos()
                        if txtplayerandplayer_rect.left <= pos[0] <= txtplayerandplayer_rect.left + 170 and \
                                txtplayerandplayer_rect.top + 100 <= pos[1] <= txtplayerandplayer_rect.top + 130:
                            is_choise = True
                            is_computer = True
                        if txtplayerandplayer_rect.left <= pos[0] <= txtplayerandplayer_rect.left + 160 and \
                                txtplayerandplayer_rect.top + 200 <= pos[1] <= txtplayerandplayer_rect.top + 230:
                            is_play_sound = not is_play_sound
                            if not is_play_sound:
                                pygame.mixer.stop()
                                pygame.mixer.music.stop()
                            else:
                                pygame.mixer.music.play()

                    if is_finish :
                        pos = pygame.mouse.get_pos()
                        if successtext_rect.left < pos[0] < successtext_rect.right - 50 and \
                                successtext_rect.top < pos[1] < successtext_rect.top + 30:
                            if is_computer:
                                is_playagain = True
                                is_player = True
                                is_finish = False
                                init()

                        if successtext_rect.left < pos[0] < successtext_rect.right and \
                                successtext_rect.top + 50 < pos[1] < successtext_rect.top + 120:
                            is_people = False
                            main()

        # 电脑落子
        if is_computer and not is_player:
            pass
            
            # 判断输赢

        if black_win and is_finish :
            screen.blit(zz_image, (0, 0))  #遮罩层
            screen.blit(failuretext, (successtext_rect.left, successtext_rect.top - 80))
            screen.blit(playagaintext, successtext_rect)
            screen.blit(menutext, (successtext_rect.left, successtext_rect.top + 80))

        if white_win and is_finish :
            screen.blit(zz_image, (0, 0))  #遮罩层
            screen.blit(successtext, (successtext_rect.left, successtext_rect.top - 80))
            screen.blit(playagaintext, successtext_rect)
            screen.blit(menutext, (successtext_rect.left, successtext_rect.top + 80))

        if is_playagain:
            init()
            white_chesses.clear()
            black_chesses.clear()
            white_positions.clear()
            black_positions.clear()
            chesses.clear()
            is_finish = False
            black_win = False
            white_win = False
            is_playagain = False

        pygame.display.flip()

        clock.tick(60)


if __name__ == '__main__':
    main()

在这里有个遮罩层,干啥的?主要是显示的时候那些菜单文字或许受到棋盘的影响,加上这个遮罩层,就好看点。有前端页面编程经历的人应该容易理解。

现在只是框架搭建起来了。真正的血和肉----电脑应手和判断输赢,待续。。。

python+pygame实现五子棋人机对战之三

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值