博客:Hzy的博客 | Hzy Bloghzeyuan.cn一些学习python的小项目,小游戏。python小项目github.com
话不多说,今天尝试用turtle库来写一个井字棋游戏。1.首先需要画一个井字的棋盘
2.需要圈圈和叉叉两名玩家,通过点击棋盘来O和×
3.判断条件,当满足获胜条件后,游戏结束。
1.我们先来定义棋盘的大小,600*600这样分成9宫格,每一个格子就是200*200
我选取每个格子的中心点为坐标
# 所有格子的中心位置
position = {(-200, 200): 0, (0, 200): 0, (200, 200): 0
, (-200, 0): 0, (0, 0): 0, (200, 0): 0
, (-200, -200): 0, (0, -200): 0, (200, -200): 0}这是一个键为坐标,值为O或者x的字典,当为0时,则认为这个格子还没有人使用。定义屏幕大小
turtle.setup(width, height)
2.画井字棋盘
# 画线
def draw_line(x, y, direction=None):
if direction:
turtle.seth(direction)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(width)
# 井棋盘
def tic_tac_toe():
draw_line(-300, 100)
draw_line(-300, -100)
draw_line(-100, 300, 270)
draw_line(100, 300, 270)
turtle.update()
3.监听点击事件,当点击的坐标在格子里,则在格子中画一个O或X通过判断中心点,点击点之间的距离是否小于格子的半径,来判断点击的是哪一个格子
同时,还要判断格子里是否已经被使用了,使用过的不能使用。
游戏开始时,画的是O,然后是×,交替,直到游戏结束。
# 在点击的位置画圆,画着画x
def draw_flag(x, y):
global last_person
in_pos = None
can_write = False
for p in position.keys():
if (p[0] - x) ** 2 + (p[1] - y) ** 2 < 10000:
in_pos = p
if position.get(in_pos, None) == 0:
can_write = True
break
# 该位置可以画圈或x
if can_write:
# 画x还是画O,当True时,我们画圈,当False时,我们画x
if len(circle_list) > len(x_list):
circle_x = False
position[in_pos] = 'x'
last_person = 'x'
x_list.append(in_pos)
else:
circle_x = True
circle_list.append(in_pos)
position[in_pos] = 'o'
last_person = 'o'
# 画圈圈
if circle_x:
turtle.color("red")
turtle.seth(270)
turtle.penup()
turtle.goto(in_pos[0] - 100, in_pos[1])
turtle.pendown()
turtle.circle(100)
# 画x
else:
turtle.color("black")
for i in range(4):
turtle.penup()
turtle.goto(in_pos[0], in_pos[1])
turtle.pendown()
turtle.seth(45 + i * 90)
turtle.forward(sqrt(20000))
turtle.update()
who_win()
4. 判断获胜的条件,在每一次点击过后。
# 判断赢家
def who_win():
v = list(position.values())
# 胜利的情况,一条横线,一条竖线,斜线
win_1 = v[0] == v[1] == v[2] != 0 or v[3] == v[4] == v[5] != 0 or v[6] == v[7] == v[8] != 0
win_2 = v[0] == v[3] == v[6] != 0 or v[1] == v[4] == v[7] != 0 or v[2] == v[5] == v[8] != 0
win_3 = v[0] == v[4] == v[8] != 0 or v[2] == v[4] == v[6] != 0
if win_1 or win_2 or win_3:
turtle.goto(-120, 0)
turtle.write("game over,{} is winner".format(last_person), font=("Arial", 25, "normal"))
turtle.onscreenclick(None)
最后一个简单的井字棋游戏就写好了!!如果你也在学python,也想做一些有意思的事情,不妨关注下我,嘻嘻。