1
0

gomoku_game.py 4.0 KB

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