【发布时间】:2019-09-22 12:54:55
【问题描述】:
我已经制作了一个井字游戏/tac/toe 游戏,但我想创建一个控制“O”而用户控制“X”的计算机播放器。
对于我代码中的clicked 函数,我试图返回一个布尔值,但我不确定我是否做得对。如果用户的点击操作成功,该函数返回True。如果用户点击了已经在棋盘区域之外的位置,则移动无效,然后该函数应返回False。我的代码:
import turtle
import time
import random
pieces = ["_", "_", "_", "_", "_", "_", "_", "_", "_"]
turn = "X"
def drawgame(brd):
# draw board
turtle.setup(600, 600)
turtle.bgcolor("silver")
turtle.color("white")
turtle.hideturtle()
turtle.speed('fastest')
turtle.width(10)
turtle.up()
# Horizontal bars
turtle.goto(-300, 100)
turtle.down()
turtle.forward(600)
turtle.up()
turtle.goto(-300, -100)
turtle.down()
turtle.forward(600)
turtle.up()
# Vertical bars
turtle.goto(-100, 300)
turtle.setheading(-90)
turtle.down()
turtle.forward(600)
turtle.up()
turtle.goto(100, 300)
turtle.down()
turtle.forward(600)
turtle.up()
turtle.color("blue")
x, y = -300, 300
for pos in pieces:
if pos == "X":
# Draw X
turtle.up()
turtle.goto(x + 20, y - 20)
turtle.setheading(-45)
turtle.down()
turtle.forward(226)
turtle.up()
turtle.goto(x + 180, y - 20)
turtle.setheading(-135)
turtle.down()
turtle.forward(226)
turtle.up()
elif pos == "O":
#Draw O
turtle.up()
turtle.goto(x + 100, y - 180)
turtle.setheading(0)
turtle.down()
turtle.circle(80)
turtle.up()
x += 200
if x > 100:
x = -300
y -= 200
def clicked(board, x, y):
#sig: list(str), int, int -> NoneType
global turn, pieces
turtle.onscreenclick(None) # disabling handler when inside handler
column = (x + 300) // 200
row = (y - 300) // -200
square = int(row * 3 + column)
print("User clicked ", x, ",", y, " at square ", square)
if pieces[square] == "_":
pieces[square] = turn
if turn == "X":
turn = "O"
else:
turn = "X"
drawgame(pieces)
else:
print("That square is already taken")
turtle.onscreenclick(clicked)
def computer_AI(board):
#sig: list(str) -> NoneType
def gameover(board):
#sig: list(str) -> bool
#checks gameover on board if there is a three in a row pattern or not
def handler(x, y):
#sig: int, int -> NoneType
if clicked(the_board, x, y):
drawgame(the_board)
if not gameover(pieces):
computer_AI(pieces)
drawgame(pieces)
gameover(pieces)
def main():
#Runs the game
turtle.tracer(0,0)
turtle.hideturtle()
turtle.onscreenclick(handler)
drawgame(pieces)
turtle.mainloop()
main()
感谢任何帮助。
【问题讨论】:
标签: python python-3.x turtle-graphics tic-tac-toe