1
0

gomoku_game.py 3.8 KB

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