所以我有这个代码到游戏的主循环中,除了转弯以外,一切似乎都按预期进行,我不确定我被困在这2天中的问题是什么,无法弄清楚如果有人想检查我在函数本身https://github.com/AmrBinBashir/Tic-Tac-Toe-Pygame中是否做错了什么,这里是完整脚本的链接:
run = True
while run:
draw_board_onetime(board_boxes, win)
make_board(board_boxes)
board = [" "] * 10
game_on = True
while game_on:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
for box in board_boxes:
if box.is_hover(pos):
box.hovered = True
box.draw(win)
else:
box.hovered = False
box.draw(win)
turn = "player1"
if turn == "player1":
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for i in range(1, 10):
if board_boxes[i].is_hover(pos):
board_boxes[i].text = x_marker
board[i] = x_marker
print(board)
if check_win(board, x_marker):
game_on = False # WIN
else:
if full_board_check(board):
game_on = False # TIE
else:
turn = "player2"
else:
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for i in range(1, 10):
if board_boxes[i].is_hover(pos):
board_boxes[i].text = o_marker
board[i] = o_marker
print(board)
if check_win(board, o_marker):
game_on = False # WIN
else:
if full_board_check(board):
game_on = False # TIE
else:
turn = "player1"
pygame.display.update()
sys.exit()
sys.exit()
答案 0 :(得分:2)
我不确定您的代码(我自己没有执行过代码),但是我很确定可以重写
turn = "player1"
#will always slip into:
if turn == "player1":
将设置“ player1”移动到代码中的其他位置,例如用于测试的全局变量。现在看来,即使将其设置为“ player2”,在下一次运行中它仍然会被覆盖。
一点点额外的建议:字符串不能作为比较器。除非您喜欢阅读,否则请考虑使用布尔值或至少整数。稍后您将学习它们如何变得更加通用并且不易出错(例如简单的错字或意外大写)。
例如,布尔值可以很容易地翻转
player = not player
(在P1的True
和P2的False
之间来回切换)。
整数可以很容易地像player_id += 1
那样递增(对于具有3个或更多玩家的棋盘游戏,它开始变得很方便)。
答案 1 :(得分:0)
如果有人在功能中看到此问题的解决方案,只需将turn变量移到game_on循环之外,以使它不能在每个循环中都被覆盖
run = True
while run:
draw_board_onetime(board_boxes, win)
make_board(board_boxes)
board = [" "] * 10
game_on = True
turn = 'player1'
while game_on:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
for box in board_boxes:
if box.is_hover(pos):
box.hovered = True
box.draw(win)
else:
box.hovered = False
box.draw(win)
if turn == "player1":
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for i in range(1, 10):
if board_boxes[i].is_hover(pos):
board_boxes[i].text = x_marker
board[i] = x_marker
print(board)
if check_win(board, x_marker):
game_on = False # WIN
else:
if full_board_check(board):
game_on = False # TIE
else:
turn = "player2"
else:
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for i in range(1, 10):
if board_boxes[i].is_hover(pos):
board_boxes[i].text = o_marker
board[i] = o_marker
print(board)
if check_win(board, o_marker):
game_on = False # WIN
else:
if full_board_check(board):
game_on = False # TIE
else:
turn = "player1"
pygame.display.update()
sys.exit()
sys.exit()