首页 > 编程语言 >python益智游戏五子棋的二次创新

python益智游戏五子棋的二次创新

时间:2024-03-04 22:02:03浏览次数:37  
标签:益智 python 五子棋 CELL player pygame SIZE col row

五子棋是一种源自中国的传统棋类游戏,起源可以追溯到古代。它是一种两人对弈的游戏,使用棋盘和棋子进行。棋盘通常是一个 15×15 的网格,棋子分为黑白两色,双方轮流在棋盘上落子。游戏的目标是通过在棋盘上落子,使自己的五个棋子在横向、纵向或斜向形成连续的线路,从而获胜。

五子棋被认为是一种智力游戏,它要求玩家在竞技中思考对手的走法并制定自己的策略。由于规则简单、易于上手,五子棋在中国以及世界各地都很受欢迎,并且有许多不同的变种和玩法。笔者选择了一个最原始最简易的一个简易五子棋的程序,采用文本界面操作。

主要源代码展示
`

# 检查水平方向
count = 0
for i in range(max(0, col - 4), min(15, col + 5)):
    if board[row][i] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

# 检查垂直方向
count = 0
for i in range(max(0, row - 4), min(15, row + 5)):
    if board[i][col] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

# 检查斜向(\)方向
count = 0
for i in range(-4, 5):
    r = row + i
    c = col + i
    if r < 0 or r >= 15 or c < 0 or c >= 15:
        continue
    if board[r][c] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

# 检查斜向(/)方向
count = 0
for i in range(-4, 5):
    r = row + i
    c = col - i
    if r < 0 or r >= 15 or c < 0 or c >= 15:
        continue
    if board[r][c] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

return False


board = [["." for _ in range(15)] for _ in range(15)]
players = ["X", "O"]
current_player = 0
print_board(board)

while True:
    print(f"Player {players[current_player]}'s turn:")
    try:
        row = int(input("Enter row (0-14): "))
        col = int(input("Enter col (0-14): "))
        if row < 0 or row >= 15 or col < 0 or col >= 15 or board[row][col] != ".":
            raise ValueError
    except ValueError:
        print("Invalid input. Try again.")
        continue

    board[row][col] = players[current_player]
    print_board(board)
    if check_win(board, row, col, players[current_player]):
        print(f"Player {players[current_player]} wins!")
        break

    current_player = (current_player + 1) % 2

通过改进,新增了可使用鼠标交互的效果,相比较于原始的代码,大大提高了游戏体验性,并且使游戏界面更加易于操作,在游戏体验上大大增加也玩性。
原始代码
`import pygame
import sys

游戏设置

CELL_SIZE = 40
BOARD_SIZE = 15
WINDOW_WIDTH = CELL_SIZE * BOARD_SIZE
WINDOW_HEIGHT = CELL_SIZE * BOARD_SIZE
LINE_COLOR = (0, 0, 0)
BG_COLOR = (139, 69, 19) # 棕色背景

初始化游戏

pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("五子棋")
clock = pygame.time.Clock()
board = [[' ' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = 'X'
game_over = False

def draw_board():
screen.fill(BG_COLOR)
for i in range(BOARD_SIZE):
pygame.draw.line(screen, LINE_COLOR, (CELL_SIZE // 2, CELL_SIZE // 2 + i * CELL_SIZE),
(WINDOW_WIDTH - CELL_SIZE // 2, CELL_SIZE // 2 + i * CELL_SIZE))
pygame.draw.line(screen, LINE_COLOR, (CELL_SIZE // 2 + i * CELL_SIZE, CELL_SIZE // 2),
(CELL_SIZE // 2 + i * CELL_SIZE, WINDOW_HEIGHT - CELL_SIZE // 2))

def draw_piece(row, col, player):
x = col * CELL_SIZE + CELL_SIZE // 2
y = row * CELL_SIZE + CELL_SIZE // 2
if player == 'X':
pygame.draw.circle(screen, (0, 0, 0), (x, y), CELL_SIZE // 3)
else:
pygame.draw.circle(screen, (255, 255, 255), (x, y), CELL_SIZE // 3)

def check_win(row, col):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for d in directions:
count = 1
for i in range(1, 5):
if 0 <= row + i * d[0] < BOARD_SIZE and 0 <= col + i * d[1] < BOARD_SIZE and
board[row + i * d[0]][col + i * d[1]] == current_player:
count += 1
else:
break
for i in range(1, 5):
if 0 <= row - i * d[0] < BOARD_SIZE and 0 <= col - i * d[1] < BOARD_SIZE and
board[row - i * d[0]][col - i * d[1]] == current_player:
count += 1
else:
break
if count >= 5:
return True
return False

def display_winner(player):
font = pygame.font.Font(None, 36)
if player == 'X':
text = font.render("Black wins!", True, (255, 0, 0))
else:
text = font.render("White wins!", True, (255, 0, 0))
text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
screen.blit(text, text_rect)

游戏循环

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
x, y = event.pos
col = x // CELL_SIZE
row = y // CELL_SIZE
if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE and board[row][col] == ' ':
board[row][col] = current_player
draw_piece(row, col, current_player)
if check_win(row, col):

         print(f"Player {current_player} wins!")
                game_over = True
            current_player = 'O' if current_player == 'X' else 'X'

draw_board()
for row in range(BOARD_SIZE):
    for col in range(BOARD_SIZE):
        if board[row][col] != ' ':
            draw_piece(row, col, board[row][col])

if game_over:
    display_winner(current_player)

pygame.display.flip()
clock.tick(30)

`import pygame
import sys

游戏设置

CELL_SIZE = 40
BOARD_SIZE = 15
WINDOW_WIDTH = CELL_SIZE * BOARD_SIZE
WINDOW_HEIGHT = CELL_SIZE * BOARD_SIZE
LINE_COLOR = (0, 0, 0)
BG_COLOR = (139, 69, 19) # 棕色背景

初始化游戏

pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("五子棋")
clock = pygame.time.Clock()
board = [[' ' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = 'X'
game_over = False

def draw_board():
screen.fill(BG_COLOR)
for i in range(BOARD_SIZE):
pygame.draw.line(screen, LINE_COLOR, (CELL_SIZE // 2, CELL_SIZE // 2 + i * CELL_SIZE),
(WINDOW_WIDTH - CELL_SIZE // 2, CELL_SIZE // 2 + i * CELL_SIZE))
pygame.draw.line(screen, LINE_COLOR, (CELL_SIZE // 2 + i * CELL_SIZE, CELL_SIZE // 2),
(CELL_SIZE // 2 + i * CELL_SIZE, WINDOW_HEIGHT - CELL_SIZE // 2))

def draw_piece(row, col, player):
x = col * CELL_SIZE + CELL_SIZE // 2
y = row * CELL_SIZE + CELL_SIZE // 2
if player == 'X':
pygame.draw.circle(screen, (0, 0, 0), (x, y), CELL_SIZE // 3)
else:
pygame.draw.circle(screen, (255, 255, 255), (x, y), CELL_SIZE // 3)

def check_win(row, col):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for d in directions:
count = 1
for i in range(1, 5):
if 0 <= row + i * d[0] < BOARD_SIZE and 0 <= col + i * d[1] < BOARD_SIZE and
board[row + i * d[0]][col + i * d[1]] == current_player:
count += 1
else:
break
for i in range(1, 5):
if 0 <= row - i * d[0] < BOARD_SIZE and 0 <= col - i * d[1] < BOARD_SIZE and
board[row - i * d[0]][col - i * d[1]] == current_player:
count += 1
else:
break
if count >= 5:
return True
return False

def display_winner(player):
font = pygame.font.Font(None, 36)
if player == 'X':
text = font.render("Black wins!", True, (255, 0, 0))
else:
text = font.render("White wins!", True, (255, 0, 0))
text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
screen.blit(text, text_rect)

游戏循环

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
x, y = event.pos
col = x // CELL_SIZE
row = y // CELL_SIZE
if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE and board[row][col] == ' ':
board[row][col] = current_player
draw_piece(row, col, current_player)
if check_win(row, col):
print(f"Player {current_player} wins!")
game_over = True
current_player = 'O' if current_player == 'X' else 'X'

draw_board()
for row in range(BOARD_SIZE):
    for col in range(BOARD_SIZE):
        if board[row][col] != ' ':
            draw_piece(row, col, board[row][col])

if game_over:
    display_winner(current_player)

pygame.display.flip()
clock.tick(30)



结语:
它通过简洁明了的语法和逻辑结构,提高了代码的可读性和可维护性。通过引入交互性更强的用户输入方式,使得玩家可以更直观地参与游戏,增强了游戏的可玩性和用户体验。总的来说,这段 Python 在保持游戏逻辑不变的情况下,提升了代码的质量和可玩性,为开发者和玩家带来了更好的体验。

标签:益智,python,五子棋,CELL,player,pygame,SIZE,col,row
From: https://www.cnblogs.com/woyaoxieyihui/p/18052817

相关文章

  • WSGI介绍:Python 首先了解
    1.1什么是WSGI首先介绍几个关于WSGI相关的概念WSGI:全称是WebServerGatewayInterface,WSGI不是服务器,python模块,框架,API或者任何软件,只是一种规范,描述webserver如何与webapplication通信的规范。server和application的规范在PEP3333中有具体描述。要实现WSGI协议,必须同时实......
  • python-pip更改下载路径,解决超时问题
    有时pip安装包时,会提示pip._vendor.urllib3.exceptions.ReadTimeoutError:HTTPSConnectionPool(host='files.pythonhosted.org',port=443):Readtimedout.原因跟解决方式PyPI镜像:考虑使用PyPI的镜像站点。中国用户经常遇到与files.pythonhosted.org的连接问题,因此他们经常......
  • python内置方法(重点)
    方法作用示例输出upper全部大写"hello".upper()"HELLO"lower全部小写"Hello".lower()"hello"startswith()是否以a开头"Yuan".startswith("Yu")Trueendswith()是否以a结尾"Yuan".endswith("a&qu......
  • python运算符
    【1】算数运算符运算符说明实例结果+加1+12-减1-10*乘1*33/除法(和数学中的规则一样)4/22//整除(只保留商的整数部分)7//23%取余,即返回除法的余数7%21**幂运算/次方运算,即返回x的y次方2**416,即24【2】赋值运算符......
  • python数据类型与字符串常用方法
    int-py2中有:int/long;py3中有int。-强制转换:int(''76"")-除法:py2(多加一行代码)和py3(正常)boolTrue/False(其他语言:true/false)特殊为False的其他类型:0和""str独有功能upper/lowerreplacestrip/lstrip/rstripisdigitsplit/r......
  • python基础语法
    (1)注释注释就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性。一般情况下,合理的代码注释应该占源代码的1/3左右。注释只是为了提高公认阅读,不会被解释器执行。Python......
  • python变量命名规范
    简单地理解,标识符就是一个名字,就好像我们每个人都有属于自己的名字,它的主要作用就是作为变量、函数、类、模块以及其他对象的名称。Python中标识符的命名不是随意的,而是要遵守一定的命令规则标识符是由字符(A~Z和a~z)、下划线和数字组成,但第一个字符不能是数字。标识符不能和......
  • python-数据类型-运算符补充-in and not
    运算符补充点击查看代码in点击查看代码value="我是中国人"#判断‘中国’是否在value所代指的字符串中。“中国”是否是value所代指的字符串的子序列。v1="中国"invalue#示例content=input('请输入内容:')if"退钱"incontent:print('包含敏感字符')#示例......
  • Python-集合
    集合python中的集合(set)是由一些唯一的、不可变的对象组成的无序集合体,集合支持与数学集合中相对应的操作,一个元素在集合中只能出现一次,无论它被添加了多少次。集合是可迭代对象(iterable),可以按需增长或缩短,并且可以包含多种对象类型,集合很像一个有键无值的字典,但由于集合是无......
  • python3.6.8 安装解决ssl问题
    https://www.cnblogs.com/mqxs/p/9103031.html#!/bin/bashecho"正在安装相关组件"yuminstall-yopenssl-develbzip2-develexpat-develgdbm-develreadline-develsqlite-develgcc-c++gccopenssl-develecho"下载安装包"wgethttps://www.python.org/ft......