├── .env.dist ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── Procfile ├── README.md ├── client.go ├── client ├── .babelrc ├── .eslintignore ├── .eslintrc.js ├── Dockerfile ├── jest.config.js ├── package.json ├── public │ ├── favicon.ico │ └── index.html ├── src │ ├── App.css │ ├── App.tsx │ ├── __tests__ │ │ └── App.test.tsx │ ├── assets │ │ ├── diamond.svg │ │ ├── game_over.gif │ │ ├── oval.svg │ │ └── squiggle.svg │ ├── components │ │ ├── Board.tsx │ │ ├── Card.tsx │ │ ├── Diamond.tsx │ │ ├── Join.tsx │ │ ├── Oval.tsx │ │ └── Squiggle.tsx │ ├── constants.ts │ ├── declaration.d.ts │ ├── index.tsx │ └── types.ts ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── context.go ├── docker-compose.yml ├── game ├── card.go ├── deck.go ├── game.go ├── helpers.go ├── move.go └── player.go ├── go.mod ├── go.sum ├── handlers.go ├── main.go ├── message └── message.go ├── package.json └── ptr └── ptr.go /.env.dist: -------------------------------------------------------------------------------- 1 | PORT=8002 2 | env=development 3 | REACT_APP_API_URL=ws://localhost:8002 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | gin-bin 2 | .env 3 | set 4 | /client/node_modules 5 | /client/build 6 | /client/coverage 7 | .DS_Store 8 | .vscode 9 | 10 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.14 2 | 3 | WORKDIR /go/src/github.com/peterzernia/set 4 | 5 | COPY go.mod /go/src/github.com/peterzernia/set 6 | COPY go.sum /go/src/github.com/peterzernia/set 7 | 8 | RUN go mod download 9 | 10 | COPY . /go/src/github.com/peterzernia/set 11 | 12 | RUN curl -SL https://github.com/maxcnunes/gaper/releases/download/v1.0.3/gaper_1.0.3_linux_amd64.tar.gz | tar -xvzf - -C "${GOPATH}/bin" 13 | 14 | EXPOSE 8002 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Peter Zernia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | docker-compose build 3 | .PHONY: build 4 | 5 | up: 6 | docker-compose up 7 | .PHONY: up 8 | 9 | client: 10 | docker-compose run --rm client yarn build 11 | .PHONY: client 12 | 13 | set: 14 | docker-compose run --rm set go build 15 | .PHONY: set 16 | 17 | clean: 18 | docker-compose stop 19 | docker-compose rm -fv 20 | .PHONY: clean 21 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: ./bin/set 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # set 2 | Set is a recreation of the card game [Set](https://en.wikipedia.org/wiki/Set_(card_game)), built with Go and Typescript React 3 | 4 | ## Development 5 | `make build` builds the docker containers 6 | `make up` runs the backend server + frontend development server 7 | `make set` builds the go binary 8 | `make client` builds the frontend javascript 9 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "net/http" 7 | "time" 8 | 9 | "github.com/gorilla/websocket" 10 | "github.com/peterzernia/set/message" 11 | ) 12 | 13 | const ( 14 | // Time allowed to write a message to the peer. 15 | writeWait = 10 * time.Second 16 | 17 | // Time allowed to read the next pong message from the peer. 18 | pongWait = 60 * time.Second 19 | 20 | // Send pings to peer with this period. Must be less than pongWait. 21 | pingPeriod = (pongWait * 9) / 10 22 | 23 | // Maximum message size allowed from peer. 24 | maxMessageSize = 512 25 | ) 26 | 27 | var ( 28 | newline = []byte{'\n'} 29 | space = []byte{' '} 30 | ) 31 | 32 | var upgrader = websocket.Upgrader{ 33 | ReadBufferSize: 1024, 34 | WriteBufferSize: 1024, 35 | } 36 | 37 | // Client is a middleman between the websocket connection and the hub. 38 | type Client struct { 39 | context *Context 40 | 41 | // The websocket connection. 42 | conn *websocket.Conn 43 | 44 | // Buffered channel of outbound messages. 45 | send chan []byte 46 | } 47 | 48 | func (c *Client) read() { 49 | defer func() { 50 | c.context.unregister <- c 51 | c.conn.Close() 52 | }() 53 | 54 | c.conn.SetReadLimit(maxMessageSize) 55 | c.conn.SetReadDeadline(time.Now().Add(pongWait)) 56 | c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) 57 | 58 | for { 59 | message := message.Message{} 60 | 61 | _, msg, err := c.conn.ReadMessage() 62 | if err != nil { 63 | if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { 64 | log.Printf("error: %v", err) 65 | } 66 | break 67 | } 68 | 69 | err = json.Unmarshal(msg, &message) 70 | if err != nil { 71 | log.Printf("Websocket error: %s", err) 72 | } 73 | 74 | var res []byte 75 | switch message.Type { 76 | case "join": 77 | c.context.handleJoin(message, c.conn) 78 | res, _ = json.Marshal(c.context.Game) 79 | case "move": 80 | c.context.handleMove(message, c.conn) 81 | res, _ = json.Marshal(c.context.Game) 82 | case "request": 83 | c.context.handleRequest(c.conn) 84 | res, _ = json.Marshal(c.context.Game) 85 | case "new": 86 | c.context.handleNew() 87 | res, _ = json.Marshal(c.context.Game) 88 | default: 89 | res = []byte("Unrecognized message type" + message.Type) 90 | log.Println("Unrecognized message type" + message.Type) 91 | } 92 | 93 | c.context.broadcast <- res 94 | } 95 | } 96 | 97 | func (c *Client) write() { 98 | ticker := time.NewTicker(pingPeriod) 99 | defer func() { 100 | ticker.Stop() 101 | c.conn.Close() 102 | }() 103 | for { 104 | select { 105 | case message, ok := <-c.send: 106 | c.conn.SetWriteDeadline(time.Now().Add(writeWait)) 107 | if !ok { 108 | // The hub closed the channel. 109 | c.conn.WriteMessage(websocket.CloseMessage, []byte{}) 110 | return 111 | } 112 | 113 | w, err := c.conn.NextWriter(websocket.TextMessage) 114 | if err != nil { 115 | return 116 | } 117 | w.Write(message) 118 | 119 | // Add queued chat messages to the current websocket message. 120 | n := len(c.send) 121 | for i := 0; i < n; i++ { 122 | w.Write(newline) 123 | w.Write(<-c.send) 124 | } 125 | 126 | if err := w.Close(); err != nil { 127 | return 128 | } 129 | case <-ticker.C: 130 | c.conn.SetWriteDeadline(time.Now().Add(writeWait)) 131 | if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { 132 | return 133 | } 134 | } 135 | } 136 | } 137 | 138 | // serveWs handles websocket requests from the peer. 139 | func serveWs(context *Context, w http.ResponseWriter, r *http.Request) { 140 | upgrader.CheckOrigin = func(r *http.Request) bool { return true } 141 | conn, err := upgrader.Upgrade(w, r, nil) 142 | if err != nil { 143 | log.Println(err) 144 | return 145 | } 146 | client := &Client{context: context, conn: conn, send: make(chan []byte, 256)} 147 | client.context.register <- client 148 | 149 | // Allow collection of memory referenced by the caller by doing all work in 150 | // new goroutines. 151 | go client.write() 152 | go client.read() 153 | } 154 | -------------------------------------------------------------------------------- /client/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-typescript", 4 | "@babel/preset-env", 5 | "@babel/preset-react" 6 | ], 7 | "plugins": [ 8 | [ 9 | "module-resolver", 10 | { 11 | "extensions": [".js", ".jsx", ".ts", ".tsx"], 12 | "root": ["./src"] 13 | } 14 | ] 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /client/.eslintignore: -------------------------------------------------------------------------------- 1 | /build 2 | webpack.config.js 3 | -------------------------------------------------------------------------------- /client/.eslintrc.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | module.exports = { 4 | env: { 5 | browser: true, 6 | es6: true, 7 | jest: true, 8 | }, 9 | extends: [ 10 | 'airbnb', 11 | 'plugin:@typescript-eslint/recommended' 12 | ], 13 | globals: { 14 | Atomics: 'readonly', 15 | SharedArrayBuffer: 'readonly', 16 | }, 17 | parser: '@typescript-eslint/parser', 18 | parserOptions: { 19 | ecmaFeatures: { 20 | jsx: true, 21 | tsx: true, 22 | }, 23 | ecmaVersion: 2018, 24 | sourceType: 'module', 25 | }, 26 | plugins: [ 27 | 'react', 28 | '@typescript-eslint', 29 | 'react-hooks', 30 | ], 31 | rules: { 32 | "semi": ['error', 'never', { 'beforeStatementContinuationChars': 'always'}], 33 | "react-hooks/rules-of-hooks": "error", 34 | "react-hooks/exhaustive-deps": "warn", 35 | "react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx", ".ts", ".tsx"] }], 36 | "@typescript-eslint/camelcase": 0, 37 | }, 38 | settings: { 39 | 'import/resolver': { 40 | node: { 41 | extensions: [".js", ".ts", ".tsx"], 42 | paths: "src", 43 | } 44 | } 45 | }, 46 | }; 47 | -------------------------------------------------------------------------------- /client/Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM node:12.9.1-alpine 3 | 4 | RUN mkdir -p /usr/src/app 5 | 6 | WORKDIR /usr/src/app/ 7 | 8 | COPY package.json /usr/src/app/ 9 | COPY yarn.lock /usr/src/app/ 10 | 11 | RUN yarn install 12 | 13 | COPY . /usr/src/app/ 14 | 15 | EXPOSE 3000 16 | -------------------------------------------------------------------------------- /client/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: [ 3 | '/src', 4 | ], 5 | transform: { 6 | '^.+\\.tsx?$': 'ts-jest', 7 | }, 8 | moduleNameMapper: { 9 | '\\.css$': 'identity-obj-proxy', 10 | '^ky$': require.resolve('ky').replace('index.js', 'umd.js'), 11 | }, 12 | moduleDirectories: [ 13 | 'node_modules', 14 | 'src', 15 | ], 16 | } 17 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "1.0.0", 4 | "author": "peterzernia", 5 | "main": "index.js", 6 | "license": "MIT", 7 | "scripts": { 8 | "test": "./node_modules/.bin/jest --coverage", 9 | "start": "webpack-dev-server --mode development --hot --inline --port 3000 --history-api-fallback --host 0.0.0.0 --env.REACT_APP_API_URL=$REACT_APP_API_URL", 10 | "build": "webpack --mode=production --env.REACT_APP_API_URL=$REACT_APP_API_URL", 11 | "lint": "./node_modules/.bin/eslint --fix './**/*.{ts,tsx,js}'" 12 | }, 13 | "dependencies": { 14 | "@types/react": "^16.9.2", 15 | "@types/react-dom": "^16.9.0", 16 | "core-js": "^3.4.2", 17 | "react": "^16.11.0", 18 | "react-dom": "^16.11.0", 19 | "regenerator-runtime": "^0.13.3" 20 | }, 21 | "devDependencies": { 22 | "@babel/core": "^7.6.0", 23 | "@babel/preset-env": "^7.6.0", 24 | "@babel/preset-react": "^7.0.0", 25 | "@babel/preset-typescript": "^7.6.0", 26 | "@svgr/webpack": "^5.3.0", 27 | "@types/jest": "^24.0.18", 28 | "@typescript-eslint/eslint-plugin": "^2.8.0", 29 | "@typescript-eslint/parser": "^2.2.0", 30 | "babel-loader": "^8.0.6", 31 | "babel-plugin-module-resolver": "^3.2.0", 32 | "copy-webpack-plugin": "^5.1.1", 33 | "css-loader": "^3.2.0", 34 | "eslint": "^6.3.0", 35 | "eslint-config-airbnb": "^18.0.1", 36 | "eslint-plugin-import": "^2.18.2", 37 | "eslint-plugin-jest": "^22.17.0", 38 | "eslint-plugin-jsx-a11y": "^6.2.3", 39 | "eslint-plugin-react": "^7.14.3", 40 | "eslint-plugin-react-hooks": "^1.7.0", 41 | "html-webpack-plugin": "^3.2.0", 42 | "identity-obj-proxy": "^3.0.0", 43 | "jest": "^24.9.0", 44 | "style-loader": "^1.0.0", 45 | "ts-jest": "^24.1.0", 46 | "typescript": "^3.6.3", 47 | "url-loader": "^4.0.0", 48 | "webpack": "^4.41.2", 49 | "webpack-cli": "^3.3.8", 50 | "webpack-dev-server": "^3.8.0" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterzernia/set/2512ba587154adb40a6759bc1a6157aca5f60f32/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Set 10 | 11 | 12 | 13 |
14 | 15 | 16 | -------------------------------------------------------------------------------- /client/src/App.css: -------------------------------------------------------------------------------- 1 | body { 2 | width: 100%; 3 | max-width: 100% !important; 4 | margin: 0px !important; 5 | } 6 | 7 | .app { 8 | display: flex; 9 | margin: auto; 10 | margin: 16px 0px; 11 | } 12 | 13 | .join { 14 | margin: auto; 15 | } 16 | 17 | input:focus { 18 | outline: none; 19 | } 20 | 21 | .game-over { 22 | margin: auto; 23 | text-align: center; 24 | } 25 | 26 | .board { 27 | display: inline-block; 28 | margin: auto; 29 | } 30 | 31 | .last-set { 32 | display: flex; 33 | line-height: 53px; 34 | } 35 | 36 | .row { 37 | display: flex; 38 | } 39 | 40 | .thumbnail { 41 | max-width: 30px !important; 42 | max-height: 45px !important; 43 | cursor: default !important; 44 | padding: 6px 0px !important; 45 | border-radius: 4px !important; 46 | } 47 | 48 | .card { 49 | box-sizing: border-box; 50 | max-width: 100px; 51 | width: 22vw; 52 | height: calc(22vw * 1.5); 53 | max-height: 150px; 54 | border: 1px solid black; 55 | box-shadow: 3px 3px 3px lightgray; 56 | cursor: pointer; 57 | margin: 4px; 58 | padding: 24px 0px; 59 | border-radius: 8px; 60 | display: flex; 61 | flex-direction: column; 62 | justify-content: space-around; 63 | align-items: center; 64 | } 65 | 66 | .selected { 67 | box-shadow: 0px 0px 3px 3px lightblue; 68 | } 69 | 70 | .card:focus { 71 | outline: none; 72 | } 73 | 74 | .hidden { 75 | visibility: hidden; 76 | } 77 | 78 | svg { 79 | z-index: -1000; 80 | stroke-width: 6; 81 | width: 75%; 82 | max-width: 300px; 83 | max-height: 100px; 84 | margin: -30px; 85 | } 86 | 87 | .red-solid { 88 | stroke: red; 89 | fill: red; 90 | } 91 | 92 | .red-outlined { 93 | stroke: red; 94 | fill: none; 95 | } 96 | 97 | .red-striped { 98 | stroke: red; 99 | fill: red; 100 | fill-opacity: 0.3; 101 | } 102 | 103 | .purple-solid { 104 | stroke: purple; 105 | fill: purple; 106 | } 107 | 108 | .purple-outlined { 109 | stroke: purple; 110 | fill: none; 111 | } 112 | 113 | .purple-striped { 114 | stroke: purple; 115 | fill: purple; 116 | fill-opacity: 0.3; 117 | } 118 | 119 | .green-solid { 120 | stroke: green; 121 | fill: green; 122 | } 123 | 124 | .green-outlined { 125 | stroke: green; 126 | fill: none; 127 | } 128 | 129 | .green-striped { 130 | stroke: green; 131 | fill: green; 132 | fill-opacity: 0.3; 133 | } -------------------------------------------------------------------------------- /client/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import { 3 | Card, 4 | Data, 5 | Move, 6 | Player, 7 | } from 'types' 8 | import Board from 'components/Board' 9 | import Join from 'components/Join' 10 | import GameOver from 'assets/game_over.gif' 11 | import './App.css' 12 | 13 | 14 | const ws = new WebSocket(`${process.env.REACT_APP_API_URL}/ws`) 15 | 16 | export default function App(): React.ReactElement { 17 | const [selected, setSelected] = React.useState([]) 18 | const [data, setData] = React.useState({} as Data) 19 | 20 | // Custom hook to keep track of the previous state of Data 21 | const usePrevious = (value: Data): React.MutableRefObject['current'] => { 22 | const ref = React.useRef({} as Data) 23 | React.useEffect(() => { 24 | ref.current = value 25 | }) 26 | return ref.current 27 | } 28 | 29 | const prevState = usePrevious(data) // prevState of Data 30 | 31 | React.useEffect(() => { 32 | ws.onopen = (): void => {} 33 | 34 | ws.onmessage = (msg): void => { 35 | const currentState = JSON.parse(msg.data) 36 | setData(currentState) 37 | 38 | // If the in_play cards have changed, deselect any cards for the client 39 | if (JSON.stringify(prevState.in_play) !== JSON.stringify(currentState.in_play)) { 40 | setSelected([]) 41 | } 42 | } 43 | 44 | ws.onclose = (): void => { 45 | alert('Disconnected from server') // eslint-disable-line 46 | window.location.reload() 47 | } 48 | }, [data, prevState.in_play]) 49 | 50 | const handleJoin = (name: string): void => { 51 | ws.send(JSON.stringify({ 52 | type: 'join', 53 | payload: { 54 | name, 55 | }, 56 | })) 57 | } 58 | 59 | const handleMove = (cards: Card[]): void => { 60 | const move: Move = { cards } 61 | ws.send(JSON.stringify({ 62 | type: 'move', 63 | payload: move, 64 | })) 65 | } 66 | 67 | const handleRequest = (): void => { 68 | ws.send(JSON.stringify({ 69 | type: 'request', 70 | })) 71 | } 72 | 73 | const handleNew = (): void => { 74 | ws.send(JSON.stringify({ 75 | type: 'new', 76 | })) 77 | } 78 | 79 | if (data && data.game_over) { 80 | const highScore = Math.max(...data.players.map((p: Player) => p.score)) 81 | const winners = data.players.filter( 82 | (p: Player) => p.score === highScore, 83 | ).map((p: Player) => p.name) 84 | 85 | return ( 86 |
87 |
88 | game-over 89 |
{`Winner: ${winners.join('& ')}`}
90 | 91 |
92 |
93 | ) 94 | } 95 | 96 | return ( 97 |
98 | { data.in_play 99 | ? ( 100 | 107 | ) : } 108 |
109 | ) 110 | } 111 | -------------------------------------------------------------------------------- /client/src/__tests__/App.test.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import * as ReactDOM from 'react-dom' 3 | import App from '../App' 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div') 7 | ReactDOM.render(, div) 8 | ReactDOM.unmountComponentAtNode(div) 9 | }) 10 | -------------------------------------------------------------------------------- /client/src/assets/diamond.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 26 | 27 | 46 | 48 | 49 | 51 | image/svg+xml 52 | 54 | 55 | 56 | 57 | 58 | 62 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /client/src/assets/game_over.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterzernia/set/2512ba587154adb40a6759bc1a6157aca5f60f32/client/src/assets/game_over.gif -------------------------------------------------------------------------------- /client/src/assets/oval.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 26 | 27 | 46 | 48 | 49 | 51 | image/svg+xml 52 | 54 | 55 | 56 | 57 | 58 | 62 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /client/src/assets/squiggle.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 24 | 29 | 34 | 45 | 50 | 57 | 62 | 67 | 72 | 73 | 92 | 94 | 95 | 97 | image/svg+xml 98 | 100 | 101 | 102 | 103 | 104 | 108 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /client/src/components/Board.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import { Data, Card as CardType, Player } from 'types' 3 | import Card from './Card' 4 | 5 | type Props = { 6 | data: Data; 7 | handleMove: (cards: CardType[]) => void; 8 | handleRequest: () => void; 9 | selected: CardType[]; 10 | setSelected: React.Dispatch>; 11 | } 12 | 13 | /* eslint react/no-array-index-key:0 */ 14 | export default function Board(props: Props): React.ReactElement { 15 | const { 16 | data, 17 | handleMove, 18 | handleRequest, 19 | selected, 20 | setSelected, 21 | } = props 22 | 23 | const { 24 | in_play, 25 | last_player, 26 | last_set, 27 | players, 28 | remaining, 29 | } = data 30 | 31 | const handleClick = (card: CardType): void => { 32 | const i = selected.indexOf(card) 33 | if (i === -1) { 34 | const slctd = [...selected, card] 35 | if (slctd.length === 3) { 36 | handleMove(slctd) 37 | setSelected([]) 38 | } else { 39 | setSelected(slctd) 40 | } 41 | } else { 42 | setSelected(selected.filter((c) => c !== card)) 43 | } 44 | } 45 | 46 | return ( 47 |
48 | {in_play.map((cards: CardType[], i: number) => ( 49 |
50 | { 51 | cards.map((card: CardType, j: number) => ( 52 | handleClick(card)} 56 | card={card} 57 | hidden={card.color === null} 58 | /> 59 | )) 60 | } 61 |
62 | ))} 63 |
64 | { last_player && `${last_player} found a set: `} 65 | {last_set && last_set.map((card: CardType) => ( 66 |
74 | 81 |
{`Remaining cards: ${remaining}`}
82 | {players.map((player: Player) => ( 83 |
84 | {`${player.name}: ${player.score} ${player.request ? 'Requested more cards' : ''}`} 85 |
86 | ))} 87 |
88 | ) 89 | } 90 | -------------------------------------------------------------------------------- /client/src/components/Card.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import { Card as CardType } from 'types' 3 | import { COLORS, SHAPES, SHADINGS } from '../constants' 4 | import Diamond from './Diamond' 5 | import Oval from './Oval' 6 | import Squiggle from './Squiggle' 7 | 8 | type Props = { 9 | card: CardType; 10 | hidden: boolean; 11 | onClick?: () => void; 12 | selected: boolean; 13 | } 14 | 15 | export default function Card(props: Props): React.ReactElement { 16 | const { 17 | card, 18 | hidden, 19 | onClick, 20 | selected, 21 | } = props 22 | 23 | const { 24 | color, 25 | shape, 26 | number, 27 | shading, 28 | } = card 29 | 30 | if (hidden) return
31 | 32 | let element: React.ReactElement 33 | switch (shape) { 34 | case SHAPES.DIAMOND: 35 | element = 36 | break 37 | case SHAPES.OVAL: 38 | element = 39 | break 40 | case SHAPES.SQUIGGLE: 41 | element = 42 | break 43 | default: 44 | throw new Error('Undefined shape') 45 | } 46 | const elements = [...Array(number + 1).keys()].map(() => element) 47 | 48 | return ( 49 |
56 | {elements} 57 |
58 | ) 59 | } 60 | -------------------------------------------------------------------------------- /client/src/components/Diamond.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Icon from 'assets/diamond.svg' 3 | 4 | type Props = { 5 | shading: string; 6 | color: string; 7 | } 8 | 9 | export default function Diamond(props: Props): React.ReactElement { 10 | const { color, shading } = props 11 | 12 | return ( 13 | 14 | ) 15 | } 16 | -------------------------------------------------------------------------------- /client/src/components/Join.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | 3 | type Props = { 4 | handleJoin: (name: string) => void; 5 | } 6 | 7 | export default function Join(props: Props): React.ReactElement { 8 | const [value, setValue] = React.useState('') 9 | const { handleJoin } = props 10 | 11 | return ( 12 |
13 | setValue(e.target.value)} 15 | value={value} 16 | placeholder="Enter a username" 17 | required 18 | /> 19 | 31 |
32 | ) 33 | } 34 | -------------------------------------------------------------------------------- /client/src/components/Oval.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Icon from 'assets/oval.svg' 3 | 4 | type Props = { 5 | shading: string; 6 | color: string; 7 | } 8 | 9 | export default function Oval(props: Props): React.ReactElement { 10 | const { shading, color } = props 11 | 12 | return ( 13 | 14 | ) 15 | } 16 | -------------------------------------------------------------------------------- /client/src/components/Squiggle.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Icon from 'assets/squiggle.svg' 3 | 4 | type Props = { 5 | shading: string; 6 | color: string; 7 | } 8 | 9 | export default function Squiggle(props: Props): React.ReactElement { 10 | const { shading, color } = props 11 | 12 | return ( 13 | 14 | ) 15 | } 16 | -------------------------------------------------------------------------------- /client/src/constants.ts: -------------------------------------------------------------------------------- 1 | export const COLORS: { [key: number]: string } = { 2 | 0: 'red', 3 | 1: 'purple', 4 | 2: 'green', 5 | } as const 6 | 7 | export const SHAPES = { 8 | DIAMOND: 0, 9 | OVAL: 1, 10 | SQUIGGLE: 2, 11 | } 12 | 13 | export const SHADINGS: { [key: number]: string } = { 14 | 0: 'outlined', 15 | 1: 'striped', 16 | 2: 'solid', 17 | } as const 18 | -------------------------------------------------------------------------------- /client/src/declaration.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.svg' 2 | declare module '*.gif' 3 | -------------------------------------------------------------------------------- /client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import 'core-js/stable' 2 | import 'regenerator-runtime/runtime' 3 | import * as React from 'react' 4 | import * as ReactDOM from 'react-dom' 5 | import App from 'App' 6 | 7 | ReactDOM.render(, document.getElementById('root')) 8 | -------------------------------------------------------------------------------- /client/src/types.ts: -------------------------------------------------------------------------------- 1 | export type Player = { 2 | id: number; 3 | name: string; 4 | request: boolean; 5 | score: number; 6 | } 7 | 8 | export type Card = { 9 | color: number; 10 | shape: number; 11 | number: number; 12 | shading: number; 13 | } 14 | 15 | export type Data = { 16 | game_over?: boolean; 17 | in_play: Card[][]; 18 | last_player: string; 19 | last_set?: Card[]; 20 | players: Player[]; 21 | remaining: number; 22 | } 23 | 24 | export type Move = { 25 | cards: Card[]; 26 | } 27 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "sourceMap": true, 4 | "strict": true, 5 | "module": "commonjs", 6 | "target": "es6", 7 | "lib": ["es2015", "es2017", "dom"], 8 | "removeComments": true, 9 | "allowSyntheticDefaultImports": true, 10 | "jsx": "react", 11 | "allowJs": true, 12 | "baseUrl": ".", 13 | "paths": { 14 | "*": ["src/*"] 15 | } 16 | }, 17 | "include": ["src/**/*"], 18 | "exclude": ["node_modules", "**/*.test.tsx"] 19 | } 20 | -------------------------------------------------------------------------------- /client/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const webpack = require('webpack') 3 | const CopyPlugin = require('copy-webpack-plugin') 4 | const HtmlWebpackPlugin = require('html-webpack-plugin') 5 | 6 | module.exports = (env) => ({ 7 | entry: './src/index.tsx', 8 | resolve: { 9 | extensions: ['.ts', '.tsx', '.js', '.json'], 10 | }, 11 | output: { 12 | path: path.join(__dirname, '/build'), 13 | filename: 'bundle.min.js', 14 | }, 15 | module: { 16 | rules: [ 17 | { 18 | test: /\.(js|jsx|ts|tsx)$/, 19 | exclude: /node_modules/, 20 | use: { 21 | loader: 'babel-loader', 22 | }, 23 | }, 24 | { 25 | test: /\.css$/, 26 | use: [ 27 | 'style-loader', 28 | 'css-loader', 29 | ], 30 | }, 31 | { 32 | test: /\.svg$/, 33 | use: ['@svgr/webpack'], 34 | }, 35 | { 36 | test: /\.gif$/, 37 | use: ['url-loader'], 38 | }, 39 | ], 40 | }, 41 | plugins: [ 42 | new CopyPlugin([ 43 | { from: './public/favicon.ico', to: '.' }, 44 | ]), 45 | new HtmlWebpackPlugin({ 46 | template: './public/index.html', 47 | }), 48 | new webpack.DefinePlugin({ 49 | 'process.env': JSON.stringify(env), 50 | }), 51 | ], 52 | }) 53 | -------------------------------------------------------------------------------- /context.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/peterzernia/set/game" 4 | 5 | // Context keeps tracks of the game, registered connections, and the message queue. 6 | type Context struct { 7 | // Registered clients. 8 | clients map[*Client]bool 9 | 10 | // Inbound messages from the clients. 11 | broadcast chan []byte 12 | 13 | // Register requests from the clients. 14 | register chan *Client 15 | 16 | // Unregister requests from clients. 17 | unregister chan *Client 18 | 19 | // The game of set 20 | Game *game.Game 21 | } 22 | 23 | func newContext() *Context { 24 | return &Context{ 25 | broadcast: make(chan []byte), 26 | register: make(chan *Client), 27 | unregister: make(chan *Client), 28 | clients: make(map[*Client]bool), 29 | } 30 | } 31 | 32 | func (c *Context) run() { 33 | // Initialize game 34 | if c.Game == nil { 35 | c.Game = game.New() 36 | } 37 | 38 | for { 39 | select { 40 | case client := <-c.register: 41 | c.clients[client] = true 42 | case client := <-c.unregister: 43 | if _, ok := c.clients[client]; ok { 44 | delete(c.clients, client) 45 | close(client.send) 46 | 47 | // remove player from game 48 | for i, v := range c.Game.Players { 49 | if v.Conn == client.conn { 50 | c.Game.Players = append(c.Game.Players[:i], c.Game.Players[i+1:]...) 51 | } 52 | } 53 | 54 | if len(c.Game.Players) == 0 { 55 | c.Game = game.New() 56 | } 57 | } 58 | case message := <-c.broadcast: 59 | for client := range c.clients { 60 | 61 | // only send mesages to clients that have 62 | // joined the game with a username 63 | isPlaying := false 64 | for _, player := range c.Game.Players { 65 | if client.conn == player.Conn { 66 | isPlaying = true 67 | } 68 | } 69 | 70 | if isPlaying { 71 | select { 72 | case client.send <- message: 73 | default: 74 | close(client.send) 75 | delete(c.clients, client) 76 | 77 | // remove player from game 78 | for i, v := range c.Game.Players { 79 | if v.Conn == client.conn { 80 | c.Game.Players = append(c.Game.Players[:i], c.Game.Players[i+1:]...) 81 | } 82 | } 83 | 84 | if len(c.Game.Players) == 0 { 85 | c.Game = game.New() 86 | } 87 | } 88 | } 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | 3 | services: 4 | set: 5 | build: . 6 | command: gaper --ignore ./client 7 | env_file: .env 8 | environment: 9 | CGO_ENABLED: 0 10 | volumes: 11 | - .:/go/src/github.com/peterzernia/set 12 | ports: 13 | - "8002:8002" 14 | client: 15 | build: ./client 16 | command: yarn start 17 | env_file: .env 18 | ports: 19 | - "3000:3000" 20 | volumes: 21 | - ./client:/usr/src/app 22 | - node_modules:/usr/src/app/node_modules 23 | volumes: 24 | node_modules: 25 | -------------------------------------------------------------------------------- /game/card.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | // Constants for colors 4 | const ( 5 | RED int64 = iota 6 | PURPLE 7 | GREEN 8 | ) 9 | 10 | // Constants for shapes 11 | const ( 12 | DIAMOND int64 = iota 13 | OVAL 14 | SQUIGGLE 15 | ) 16 | 17 | // Constants for numbers 18 | const ( 19 | ONE int64 = iota 20 | TWO 21 | THREE 22 | ) 23 | 24 | // Constants for shading 25 | const ( 26 | OUTLINED int64 = iota 27 | STRIPED 28 | SOLID 29 | ) 30 | 31 | // Global variables representing default colors, shapes and numbers 32 | // for the cards in a Set deck 33 | var ( 34 | COLORS = []int64{RED, PURPLE, GREEN} 35 | SHAPES = []int64{DIAMOND, OVAL, SQUIGGLE} 36 | NUMBERS = []int64{ONE, TWO, THREE} 37 | SHADINGS = []int64{OUTLINED, STRIPED, SOLID} 38 | ) 39 | 40 | // Card represents a card in Set 41 | type Card struct { 42 | Color *int64 `json:"color"` 43 | Shape *int64 `json:"shape"` 44 | Number *int64 `json:"number"` 45 | Shading *int64 `json:"shading"` 46 | } 47 | 48 | // Copy copies a card 49 | func (c *Card) Copy() *Card { 50 | return &Card{ 51 | Color: c.Color, 52 | Shape: c.Shape, 53 | Number: c.Number, 54 | Shading: c.Shading, 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /game/deck.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | import ( 4 | "math/rand" 5 | "time" 6 | 7 | "github.com/peterzernia/set/ptr" 8 | ) 9 | 10 | // Deck represents a deck in Set 11 | type Deck struct { 12 | Cards []Card `json:"cards"` 13 | } 14 | 15 | // newDeck creates a new deck 16 | func newDeck() *Deck { 17 | rand.Seed(time.Now().UnixNano()) 18 | 19 | deck := Deck{} 20 | cards := []Card{} 21 | 22 | for _, color := range COLORS { 23 | for _, shape := range SHAPES { 24 | for _, number := range NUMBERS { 25 | for _, shading := range SHADINGS { 26 | card := Card{ 27 | Color: ptr.Int64(color), 28 | Shape: ptr.Int64(shape), 29 | Number: ptr.Int64(number), 30 | Shading: ptr.Int64(shading), 31 | } 32 | cards = append(cards, card) 33 | } 34 | } 35 | } 36 | } 37 | 38 | deck.Cards = cards 39 | deck.Shuffle() 40 | return &deck 41 | } 42 | 43 | // Shuffle uses Knuth shuffle algo to randomize the deck in O(n) time 44 | // sourced from https://gist.github.com/quux00/8258425 45 | func (d *Deck) Shuffle() { 46 | n := len(d.Cards) 47 | for i := 0; i < n; i++ { 48 | r := i + rand.Intn(n-i) 49 | d.Cards[r], d.Cards[i] = d.Cards[i], d.Cards[r] 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /game/game.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/gorilla/websocket" 7 | "github.com/peterzernia/set/ptr" 8 | ) 9 | 10 | // Game represents a Set game 11 | type Game struct { 12 | Deck *Deck `json:"-"` 13 | GameOver *bool `json:"game_over,omitempty"` 14 | InPlay [][]Card `json:"in_play,omitempty"` 15 | LastPlayer *string `json:"last_player,omitempty"` 16 | LastSet []Card `json:"last_set,omitempty"` 17 | Players []Player `json:"players,omitempty"` 18 | Remaining *int64 `json:"remaining,omitempty"` 19 | } 20 | 21 | // New initializes a game 22 | func New() *Game { 23 | game := Game{} 24 | game.Players = []Player{} 25 | game.Deck = newDeck() 26 | game.Deal() 27 | return &game 28 | } 29 | 30 | // Deal deals the initial 12 cards 31 | func (g *Game) Deal() { 32 | inPlay := [][]Card{[]Card{}, []Card{}, []Card{}} 33 | 34 | for i := 0; i < 4; i++ { 35 | for j := 0; j < 3; j++ { 36 | inPlay[j] = append(inPlay[j], *g.Deck.Cards[j].Copy()) 37 | } 38 | g.Deck.Cards = g.Deck.Cards[3:] 39 | } 40 | 41 | g.InPlay = inPlay 42 | g.Remaining = ptr.Int64(int64(len(g.Deck.Cards))) 43 | return 44 | } 45 | 46 | // Play plays a play 47 | func (g *Game) Play(move *Move, conn *websocket.Conn) (bool, error) { 48 | valid, err := g.CheckSet(move.Cards) 49 | if !valid || err != nil { 50 | g.UpdateScore(conn, -1) 51 | return false, errors.New("Invalid set") 52 | } 53 | 54 | // Find the location of the 3 cards in the cards in play matrix 55 | indices := [][]int{} 56 | for _, v := range move.Cards { 57 | i := findIndex(g.InPlay, v) 58 | indices = append(indices, i) 59 | } 60 | 61 | // -1 index signifies that the card is not in play 62 | for _, v := range indices { 63 | if v[0] == -1 || v[1] == -1 { 64 | return false, errors.New("Invalid cards") 65 | } 66 | } 67 | 68 | // Sum the cards in play, ignoring the placeholder ones 69 | inPlay := 0 70 | for _, row := range g.InPlay { 71 | for _, card := range row { 72 | if card.Color != nil { 73 | inPlay++ 74 | } 75 | } 76 | } 77 | 78 | // Replace the found set with new cards if there aren't 79 | // 12 (+3 about to be removed) cards already in play 80 | for _, v := range indices { 81 | if len(g.Deck.Cards) > 0 && inPlay < 15 { 82 | g.InPlay[v[0]][v[1]] = *g.Deck.Cards[0].Copy() 83 | g.Deck.Cards = g.Deck.Cards[1:] 84 | } else { 85 | g.InPlay[v[0]][v[1]] = Card{} // Placeholder card 86 | } 87 | } 88 | 89 | // Give the player a point 90 | g.UpdateScore(conn, 1) 91 | g.Remaining = ptr.Int64(int64(len(g.Deck.Cards))) 92 | 93 | var lastPlayer *string 94 | for _, player := range g.Players { 95 | if conn == player.Conn { 96 | lastPlayer = player.Name 97 | } 98 | } 99 | g.LastPlayer = lastPlayer 100 | g.LastSet = move.Cards 101 | 102 | // If there are no cards left, check if there are any 103 | // remaining sets on the board, if not the game is over 104 | if len(g.Deck.Cards) == 0 { 105 | end := g.CheckRemainingSets() 106 | 107 | return end, nil 108 | } 109 | 110 | return false, nil 111 | } 112 | 113 | // CheckSet checks if 3 cards are a valid set. For each attribute, 114 | // there are 3 options. If one of the attribute's options has a count of 115 | // 2 that means the 3 cards are not a set, e.g. if there are two red cards 116 | // the 3 cards are not a set. 117 | func (g *Game) CheckSet(cards []Card) (bool, error) { 118 | if len(cards) != 3 { 119 | return false, errors.New("Sets must contain 3 cards") 120 | } 121 | 122 | colors := make(map[int64]int64) 123 | shapes := make(map[int64]int64) 124 | numbers := make(map[int64]int64) 125 | shadings := make(map[int64]int64) 126 | 127 | for _, card := range cards { 128 | colors[*card.Color]++ 129 | shapes[*card.Shape]++ 130 | numbers[*card.Number]++ 131 | shadings[*card.Shading]++ 132 | } 133 | 134 | for _, v := range colors { 135 | if v == 2 { 136 | return false, nil 137 | } 138 | } 139 | 140 | for _, v := range shapes { 141 | if v == 2 { 142 | return false, nil 143 | } 144 | } 145 | 146 | for _, v := range numbers { 147 | if v == 2 { 148 | return false, nil 149 | } 150 | } 151 | 152 | for _, v := range shadings { 153 | if v == 2 { 154 | return false, nil 155 | } 156 | } 157 | 158 | return true, nil 159 | } 160 | 161 | // CheckRemainingSets checks if there is still 162 | // at least on set in the InPlay cards 163 | func (g *Game) CheckRemainingSets() bool { 164 | cards := []Card{} 165 | for _, row := range g.InPlay { 166 | for _, card := range row { 167 | if card.Color != nil { 168 | cards = append(cards, *card.Copy()) 169 | } 170 | } 171 | } 172 | 173 | end := true 174 | for i, x := range cards { 175 | for j, y := range cards { 176 | for k, z := range cards { 177 | if i != j && i != k && j != k { 178 | valid, _ := g.CheckSet([]Card{x, y, z}) 179 | if valid { 180 | end = false 181 | } 182 | } 183 | } 184 | } 185 | } 186 | 187 | return end 188 | } 189 | 190 | // AddCards adds another 3 cards onto the game board 191 | func (g *Game) AddCards() { 192 | cards := g.Deck.Cards[0:3] 193 | g.Deck.Cards = g.Deck.Cards[3:] 194 | 195 | // Fill in the spaces 196 | for i, row := range g.InPlay { 197 | for j, v := range row { 198 | if len(cards) > 0 { 199 | if v.Color == nil { 200 | g.InPlay[i][j] = cards[0] 201 | cards = cards[1:] 202 | } 203 | } 204 | } 205 | } 206 | 207 | // Start a new column if there are no more spaces 208 | if len(cards) > 0 { 209 | g.InPlay[0] = append(g.InPlay[0], *cards[0].Copy()) 210 | g.InPlay[1] = append(g.InPlay[1], *cards[1].Copy()) 211 | g.InPlay[2] = append(g.InPlay[2], *cards[2].Copy()) 212 | } 213 | 214 | g.Remaining = ptr.Int64(int64(len(g.Deck.Cards))) 215 | } 216 | 217 | // UpdateScore updates a players score. The player is found by their websocket 218 | // connection 219 | func (g *Game) UpdateScore(conn *websocket.Conn, value int64) { 220 | var index int 221 | for i, player := range g.Players { 222 | if player.Conn == conn { 223 | index = i 224 | } 225 | } 226 | 227 | if *g.Players[index].Score == 0 && value < 0 { 228 | return 229 | } 230 | 231 | g.Players[index].Score = ptr.Int64(*g.Players[index].Score + value) 232 | } 233 | -------------------------------------------------------------------------------- /game/helpers.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | // findIndex is a helper function to find the index of a card 4 | func findIndex(cardss [][]Card, card Card) []int { 5 | for i, cards := range cardss { 6 | for j, v := range cards { 7 | if v.Color != nil && *v.Color == *card.Color && 8 | *v.Shape == *card.Shape && 9 | *v.Number == *card.Number && 10 | *v.Shading == *card.Shading { 11 | return []int{i, j} 12 | } 13 | } 14 | } 15 | return []int{-1, -1} 16 | } 17 | -------------------------------------------------------------------------------- /game/move.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | // Move represents a play made by a player 4 | type Move struct { 5 | PlayerID *int64 `json:"player_id"` 6 | Cards []Card `json:"cards"` 7 | } 8 | -------------------------------------------------------------------------------- /game/player.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | import "github.com/gorilla/websocket" 4 | 5 | // Player represents a player 6 | type Player struct { 7 | ID *int64 `json:"id,omitempty"` 8 | Conn *websocket.Conn `json:"-"` 9 | Name *string `json:"name,omitempty"` 10 | Score *int64 `json:"score,omitempty"` 11 | Request *bool `json:"request,omitempty"` 12 | } 13 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/peterzernia/set 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/fatih/color v1.9.0 // indirect 7 | github.com/gorilla/websocket v1.4.2 8 | github.com/mattn/go-shellwords v1.0.10 // indirect 9 | github.com/mattn/go-zglob v0.0.1 // indirect 10 | github.com/maxcnunes/gaper v1.0.3 // indirect 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= 2 | github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= 3 | github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= 4 | github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 5 | github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= 6 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 7 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 8 | github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= 9 | github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= 10 | github.com/mattn/go-shellwords v1.0.10 h1:Y7Xqm8piKOO3v10Thp7Z36h4FYFjt5xB//6XvOrs2Gw= 11 | github.com/mattn/go-shellwords v1.0.10/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= 12 | github.com/mattn/go-zglob v0.0.1 h1:xsEx/XUoVlI6yXjqBK062zYhRTZltCNmYPx6v+8DNaY= 13 | github.com/mattn/go-zglob v0.0.1/go.mod h1:9fxibJccNxU2cnpIKLRRFA7zX7qhkJIQWBb449FYHOo= 14 | github.com/maxcnunes/gaper v1.0.3 h1:yhkY5r7v0iAJbRtJMYfkW2wMzbNUfSVvHm9FUHySq6w= 15 | github.com/maxcnunes/gaper v1.0.3/go.mod h1:nxPpNLpJywH+Nfjs1x8gO3cC2UvHeboOMrlKjVex65g= 16 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 17 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= 18 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 19 | -------------------------------------------------------------------------------- /handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | 7 | "github.com/gorilla/websocket" 8 | "github.com/peterzernia/set/game" 9 | "github.com/peterzernia/set/message" 10 | "github.com/peterzernia/set/ptr" 11 | ) 12 | 13 | func (c *Context) handleJoin(message message.Message, conn *websocket.Conn) *int64 { 14 | if c.Game == nil || c.Game.GameOver != nil && *c.Game.GameOver { 15 | c.Game = game.New() 16 | } 17 | 18 | player := game.Player{} 19 | player.ID = ptr.Int64(int64(len(c.Game.Players)) + 1) 20 | player.Conn = conn 21 | player.Request = ptr.Bool(false) 22 | player.Score = ptr.Int64(0) 23 | 24 | if name, ok := message.Payload["name"].(string); ok { 25 | player.Name = &name 26 | } 27 | 28 | c.Game.Players = append(c.Game.Players, player) 29 | return player.ID 30 | } 31 | 32 | func (c *Context) handleMove(message message.Message, conn *websocket.Conn) error { 33 | move := game.Move{} 34 | j, _ := json.Marshal(message.Payload) 35 | json.Unmarshal(j, &move) 36 | 37 | end, err := c.Game.Play(&move, conn) 38 | if err != nil { 39 | fmt.Println(err.Error()) 40 | return err 41 | } 42 | 43 | if end { 44 | c.Game.GameOver = ptr.Bool(true) 45 | } 46 | 47 | // Reset request for new cards when a set is successful 48 | for i := range c.Game.Players { 49 | c.Game.Players[i].Request = ptr.Bool(false) 50 | } 51 | 52 | return nil 53 | } 54 | 55 | func (c *Context) handleRequest(conn *websocket.Conn) { 56 | for i, v := range c.Game.Players { 57 | if v.Conn == conn { 58 | c.Game.Players[i].Request = ptr.Bool(true) 59 | } 60 | } 61 | 62 | request := true 63 | for _, v := range c.Game.Players { 64 | if !*v.Request { 65 | request = false 66 | } 67 | } 68 | 69 | if request && c.Game.Deck.Cards != nil && len(c.Game.Deck.Cards) > 0 { 70 | c.Game.AddCards() 71 | for i := range c.Game.Players { 72 | c.Game.Players[i].Request = ptr.Bool(false) 73 | } 74 | } 75 | } 76 | 77 | func (c *Context) handleNew() { 78 | players := c.Game.Players 79 | 80 | for i := range players { 81 | players[i].Score = ptr.Int64(0) 82 | } 83 | 84 | c.Game = game.New() 85 | c.Game.Players = players 86 | } 87 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | context := newContext() 11 | 12 | go context.run() 13 | 14 | http.Handle("/", http.FileServer(http.Dir("./client/build"))) 15 | 16 | http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { 17 | serveWs(context, w, r) 18 | }) 19 | 20 | port := ":" + os.Getenv("PORT") 21 | log.Fatal(http.ListenAndServe(port, nil)) 22 | } 23 | -------------------------------------------------------------------------------- /message/message.go: -------------------------------------------------------------------------------- 1 | package message 2 | 3 | // Message represents a message sent on the websocket server 4 | type Message struct { 5 | Type string `json:"type"` 6 | Payload map[string]interface{} `json:"payload"` 7 | } 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "scripts": { 4 | "heroku-prebuild": "cd client/ && npm install && npm run build" 5 | }, 6 | "engines": { 7 | "node": "12.9.1", 8 | "npm": "6.10.3", 9 | "yarn": "1.18.0" 10 | }, 11 | "cacheDirectories": [ 12 | "client/node_modules" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /ptr/ptr.go: -------------------------------------------------------------------------------- 1 | package ptr 2 | 3 | // Int64 turns an int64 into a *int64 4 | func Int64(i int64) *int64 { 5 | p := i 6 | return &p 7 | } 8 | 9 | // Bool turns an bool into a *bool 10 | func Bool(i bool) *bool { 11 | p := i 12 | return &p 13 | } 14 | --------------------------------------------------------------------------------