gomoku_game.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import time
  2. from pywebio import session, start_server
  3. from pywebio.output import *
  4. goboard_size = 15
  5. # -1 -> none, 0 -> black, 1 -> white
  6. goboard = [
  7. [-1] * goboard_size
  8. for _ in range(goboard_size)
  9. ]
  10. def winner(): # return winner piece, return None if no winner
  11. for x in range(2, goboard_size - 2):
  12. for y in range(2, goboard_size - 2):
  13. # check if (x,y) is the win center
  14. if goboard[x][y] != -1 and any([
  15. all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y), (x - 1, y), (x + 1, y), (x + 2, y)]),
  16. all(goboard[x][y] == goboard[m][n] for m, n in [(x, y - 2), (x, y - 1), (x, y + 1), (x, y + 2)]),
  17. all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y - 2), (x - 1, y - 1), (x + 1, y + 1), (x + 2, y + 2)]),
  18. all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y + 2), (x - 1, y + 1), (x + 1, y - 1), (x + 2, y - 2)]),
  19. ]):
  20. return ['⚫', '⚪'][goboard[x][y]]
  21. session_id = 0 # auto incremented id for each session
  22. current_turn = 0 # 0 for black, 1 for white
  23. player_count = [0, 0] # count of player for two roles
  24. def main():
  25. """Online Shared Gomoku Game
  26. A web based Gomoku (AKA GoBang, Five in a Row) game made with PyWebIO under 100 lines of Python code."""
  27. global session_id, current_turn, goboard
  28. if winner(): # The current game is over, reset game
  29. goboard = [[-1] * goboard_size for _ in range(goboard_size)]
  30. current_turn = 0
  31. my_turn = session_id % 2
  32. my_chess = ['⚫', '⚪'][my_turn]
  33. session_id += 1
  34. player_count[my_turn] += 1
  35. @session.defer_call
  36. def player_exit():
  37. player_count[my_turn] -= 1
  38. session.set_env(output_animation=False)
  39. put_html("""<style> table th, table td { padding: 0px !important;} button {padding: .75rem!important; margin:0!important} </style>""") # Custom styles to make the board more beautiful
  40. put_markdown(f"""# Online Shared Gomoku Game
  41. All online players are assigned to two groups (black and white) and share this game. You can open this page in multiple tabs of your browser to simulate multiple users. This application uses less than 100 lines of code, the source code is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/gomoku_game.py)
  42. Currently online player: {player_count[0]} for ⚫, {player_count[1]} for ⚪. Your role is {my_chess}.
  43. """)
  44. def set_stone(pos):
  45. global current_turn
  46. if current_turn != my_turn:
  47. toast("It's not your turn!!", color='error')
  48. return
  49. x, y = pos
  50. goboard[x][y] = my_turn
  51. current_turn = (current_turn + 1) % 2
  52. @use_scope('goboard', clear=True)
  53. def show_goboard():
  54. table = [
  55. [
  56. put_buttons([dict(label=' ', value=(x, y), color='light')], onclick=set_stone) if cell == -1 else [' ⚫', ' ⚪'][cell]
  57. for y, cell in enumerate(row)
  58. ]
  59. for x, row in enumerate(goboard)
  60. ]
  61. put_table(table)
  62. show_goboard()
  63. while not winner():
  64. with use_scope('msg', clear=True):
  65. current_turn_copy = current_turn
  66. if current_turn_copy == my_turn:
  67. put_text("It's your turn!")
  68. else:
  69. put_row([put_text("Your opponent's turn, waiting... "), put_loading().style('width:1.5em; height:1.5em')], size='auto 1fr')
  70. while current_turn == current_turn_copy and not session.get_current_session().closed(): # wait for next move
  71. time.sleep(0.2)
  72. show_goboard()
  73. with use_scope('msg', clear=True):
  74. put_text('Game over. The winner is %s!\nRefresh page to start a new round.' % winner())
  75. if __name__ == '__main__':
  76. start_server(main, debug=True, port=8080)