本文主要是介绍python制作井字棋程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
井字棋的九个格子可以用二进制表示,整个运算过程用位运算。
三个相同标记连续在一条直线,事先准备好样本,如果样本与使用and运算相同,就判断三个标记是一起的。
代码如下
import random
goal=[
0b111000000,0b000111000,0b000000111,0b100100100,
0b010010010,0b001001001,0b100010001,0b001010100
]
def check(player):
for mask in goal:
if player & mask ==mask:
return True
return False
def play(p1,p2):
if check(p2):
print([bin(p1),bin(p2)])
return
board=p1 | p2
if board==0b111111111:
print([bin(p1), bin(p2)])
return
w=[i for i in range(9) if(board & (1<<i))==0]
r=random.choice(w)
play(p2,p1| 1<<r)
play(0,0)
这篇关于python制作井字棋程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!