The Available Games Component
OK, time to create a component that will show all games waiting for an opponent. Any time any other player creates a game, we want it to immediately show up in this list for all players sitting in the Lobby.
First, a component needs a component file. Create AvailableGames.jsx inside your templates/components/lobby directory and fill it with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import React from 'react' class AvailableGames extends React.Component { constructor(props) { super(props) this.state = { game_list: this.props.game_list } this.renderGameList = this.renderGameList.bind(this); } componentWillReceiveProps(newProp) { this.setState({ game_list: newProp.game_list }) } renderGameList() { // clear out games owned by this player let player_removed = this.props.game_list.filter(function(game) { return game.creator.id !== this.props.player.id }, this); if (player_removed.length > 0) { return player_removed.map(function (game) { return <li key={game.id} className="list-group-item"> <span className="badge pull-left">{game.id}</span> <span>{game.creator.username} vs???</span> <a className="btn btn-sm btn-primary pull-right" href={"/game/"+game.id+"/"}>Play</a> </li> }, this) } else { return ("No Available Games") } } render() { return ( <div> <div className="panel panel-primary"> <div className="panel-heading"> <span>Available Games</span> </div> <div className="panel-body"> <div> <ul className="list-group games-list"> {this.renderGameList() } </ul> </div> </div> </div> </div> ) } } AvailableGames.defaultProps = { }; AvailableGames.propTypes = { game_list: React.PropTypes.array, player: React.PropTypes.object }; export default AvailableGames |
This is pretty similar to what we’ve seen before. It’s a straight-forward React component that just renders a list of games from an array passed to it in the props as “game_list“. The componentWillReceiveProps will listen for any props changes from the parent LobbyBase component and update them if that changes.
Let’s add this in to be rendered now. Make the highlighted changes to your LobbyBase.jsx now (or copy-paste this code):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import React from 'react'; import ReactDOM from 'react-dom'; import Websocket from 'react-websocket' import $ from 'jquery' import PlayerGames from './PlayerGames' import AvailableGames from './AvailableGames' class LobbyBase extends React.Component { constructor(props) { super(props); this.state = { player_game_list: [], available_game_list: [] } // bind button click this.sendSocketMessage = this.sendSocketMessage.bind(this); } getPlayerGames(){ this.serverRequest = $.get('http://localhost:8080/player-games/?format=json', function (result) { this.setState({ player_game_list: result, }) }.bind(this)) } getAvailableGames(){ this.serverRequest = $.get('http://localhost:8080/available-games/?format=json', function (result) { this.setState({ available_game_list: result }) }.bind(this)) } componentDidMount() { this.getPlayerGames() this.getAvailableGames() } componentWillUnmount() { this.serverRequest.abort(); } handleData(data) { //receives messages from the connected websocket let result = JSON.parse(data) // new games, so get an updated list of this player's game this.getPlayerGames() // we've received an updated list of available games this.setState({available_game_list: result}) } sendSocketMessage(message){ // sends message to channels back-end const socket = this.refs.socket socket.state.ws.send(JSON.stringify(message)) } render() { return ( <div className="row"> <Websocket ref="socket" url={this.props.socket} onMessage={this.handleData.bind(this)} reconnect={true}/> <div className="col-lg-4"> <PlayerGames player={this.props.current_user} game_list={this.state.player_game_list} sendSocketMessage={this.sendSocketMessage} /> </div> <div className="col-lg-4"> <AvailableGames player={this.props.current_user} game_list={this.state.available_game_list} sendSocketMessage={this.sendSocketMessage} /> </div> </div> ) } } LobbyBase.propTypes = { socket: React.PropTypes.string }; export default LobbyBase; |
What changed:
- Line 6: Importing our new component
- Lines 29-35: Makes a server call to get the latest available games list
- Line 39: When the component mounts for the first time, it will make a call to the getAvailableGames() function so it can have Available Games as soon as it’s loaded.
- Lines 72-75: Adding the component to the render() method so it will actually be rendered to the screen.
All of that is great, but if we were to run the site with this code we’ll have the same issue as we did before with the Player Games – we don’t have a /available-games/ api endpoint that is called on Line 30. Let’s add that now.
In your urls.py file add this highlighted line under our player-games router:
23 24 25 26 |
router = DefaultRouter() router.register(r'player-games', PlayerGameViewSet, 'player_games') router.register(r'available-games', AvailableGameViewSet, 'available_games') |
And then add the ViewSet being called by that line to the end of your api_views.py file:
37 38 39 40 41 42 43 44 45 |
class AvailableGameViewSet(viewsets.ViewSet): """ API endpoint for available/open games """ def list(self, request): queryset = Game.get_available_games() serializer = GameSerializer(queryset, many=True) return Response(serializer.data) |
OK, great. With that we now should see a Lobby with two lists: Player Games and Available Games. If you’re still logged in as the same player that you created some test games with, you may not see any Available Games. So to see this in action, open up two browser screens, with one being in “Incognito” or “Private” mode. Hit your development site and log in on each browser with a different user (or register a new player if you only have one).
Now when you click “Start New Game” you should see it immediately show in the list under “Your Games” on that screen…and on the other, you’ll see that same game appear under “Available Games” for the second player.
Joining a game
Now we’re going to add functionality that will allow a player to join an available game. We already are rendering a “Play” button in the AvailableGames.jsx component next to each game. We want it so that when that button is clicked, it assigns the current player as the game’s opponent and then sends the user to that game to play.
Looking at the code that renders the button (Line 30 in AvailableGames.jsx) it simply just sends the user to a /game/ url with a game.id parameter. We’ll wire that up first. Add the highlighted line to your urls.py file:
6 7 8 9 10 11 12 13 14 15 |
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/', CreateUserView.as_view()), url(r'^login/$', login, {'template_name': 'login.html'}), url(r'^logout/$', logout, {'next_page': '/'}), url(r'^lobby/$', LobbyView.as_view()), url(r'^game/(?P<game_id>\d+)/$', GameView.as_view()), url(r'^$', HomeView.as_view()) |
And now the GameView referenced in that line at the bottom of your game/views/views.py file:
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
class GameView(TemplateView): template_name = 'components/game/game.html' game = None @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): # get the game by the id self.game = Game.get_by_id(kwargs['game_id']) user = get_user(request) # check to see if the game is open and available for this user # if this player is the creator, just return if self.game.creator == user or self.game.opponent == user: return super(GameView, self).dispatch(request, *args, **kwargs) # if there is no opponent and the game is not yet completed, # set the opponent as this user if not self.game.opponent and not self.game.completed: self.game.opponent = user self.game.save() return super(GameView, self).dispatch(request, *args, **kwargs) else: messages.add_message(request, messages.ERROR, 'Sorry, the selected game is not available.') return redirect('/lobby/') def get_context_data(self, **kwargs): context = super(GameView, self).get_context_data(**kwargs) context['game'] = self.game return context |
Also add these import at the top of your views.py:
1 2 |
from django.contrib.auth import get_user from django.contrib import messages |
Importing messages will allow us to send error or success messages using Django’s messaging framework.
We also import get_user, which is a simple, standard Django view. But we’re doing a little something in the dispatch() method to handle the game. If you look over that code you’ll see that we:
- Get the game object
- Get the user from the request
- If the game already has this user as the creator or the opponent, show the game screen
- If it doesn’t, and the game is still “live” and not complete, set the user as the game opponent and send them to the game.
hello,
when I run your code, but the web don’t show the game, what’s happend?
Are you going through the tutorial? Or are you running the example project from github?
Do you have a similar project but with channels 2.0? Do you plan to update this one?
Yes, I’m actually working on one now. Hopefully I’ll have it ready in October, but my free time is tight right now.
I am getting an error, “ImportError: cannot import name ‘Group'”, while trying to import Group from channels in models.py. I am using channels 2.0.2. Please help.
Yeah, this tutorial is based on a very early version of channels – 0.17, I believe. Version 2.0.2 has quite of few changes from that old version, including requiring Python3. Here is an issue on the official github that deals with the error you’re seeing: https://github.com/django/channels/issues/989
I will try to get the tutorial updated to Django 2.0, Python 3, and the latest channels version soon.
Hey,
I’m trying to follow your tutorial, but I keep running into the following error:
OSError at /lobby/
Error reading [PATH]\webpack-stats.json. Are you sure webpack has generated the file and the path is correct?
Any idea how to fix it?
Sorry, I didn’t reply sooner. If the file is being generated, check your STATS_FILE setting under WEBPACK_LOADER in settings.py. It’s possible that it isn’t pointing to the correct location for the file.
If the file isn’t being generated, webpack may not be running properly. Are you seeing errors when you run wepback?
That is very good, I was making similar stuff as a video on my language and this sharing is very useful.
Power of sharing, thanks again.
When will the index.jsx be called ?
The index.jsx files are bundled with webpack (set on lines 8 and 9 in webpack.config.js). Those are the bundles that are loaded with the Django Webpack Loader and rendered on the related html pages (lobby.html and game.html).
I got a few questions to make the game a little bit more complex
Is it possible to allow to the user give a name for the room?
Is it possible to allow more than 2 players? (obviously adding the correct img stuff)
If the answer from above is yes, can the user choose a “limit” for ppl to connect before starting the game?
Cheers!
Yes, each of those suggestions would work just fine:
Thanks for this django/react tutorial. It is awesome helping me get my head around React and putting all the pieces together!!
Great to hear! I’m glad you found it useful. Thanks for letting me know.
Thank you so much for writing this tutorial!
From your description, it seems like moves and player messages should update automatically, however when I run it, they only update after a manual refresh of the page. Am I misunderstanding how the website works?
Thanks
The log should update when new chat messages are created or moves are made. I would check to make sure the game.send_game_update() method is being called at the appropriate times. Also, check the browser console for any errors on the client-side. That may give you more of a clue to the issue as well.
Thanks for writing this tutorial! However, some things that may be confusing to a beginner:
startapp game
is going to create a game/views.py by default, and anyone that forgets to move views.py is going to have a package conflict. Also,from views import *
inside __init__.py should befrom .views import *
just to avoid any namespace mismatches. I recommend you keep the default views.py.Thanks for your comments, Daniel. Yes, I thought that splitting the views could be confusing, but it’s something I like to do to organize views of different types. So here, I didn’t want to combine the DRF API views with the “standard” Django views. Also, the tutorial wasn’t exactly intended for beginners, but maybe I can clarify the views split a little more in the post. Also, thanks for catching the import fix. I had already updated the imports in the git project, but missed it in the post.
Hello! Great tutorial! I have a question, I want to use foundation-sites in my project. I am following you tutorial and instead of using bootstrap precompiled css I would like to install foundation with bower maybe? I know how to use the “foundation new” command to create a new project but I would like not to create a new project but integrate foundation sites with mine!
Hey David, sorry I haven’t worked with Foundation yet. But it looks like you can just use the CSS itself and avoid the CLI site generation: http://foundation.zurb.com/sites/download/
You could just include this as you would any other CSS, and my guess is that if you install the full Foundation package with NPM, you could just reference the CSS there as well.
not sure if it’s a django versioning thing or what, but on page 1 of this tutorial you are no longer allowed to specify views with strings and they must be callable, suggested edit follows:
original:
from django.conf.urls import url
from django.contrib import admin
from game.views import *
urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(r’^register/’, CreateUserView.as_view()),
url(r’^login/$’, ‘django.contrib.auth.views.login’, {‘template_name’: ‘login.html’}),
url(r’^logout/$’, ‘django.contrib.auth.views.logout’, {‘next_page’: ‘/’}),
url(r’^$’, HomeView.as_view())
]
edit:
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import login, logout
from game.views import *
urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(r’^register/’, CreateUserView.as_view()),
url(r’^login/$’, login, {‘template_name’: ‘login.html’}),
url(r’^logout/$’, logout, {‘next_page’: ‘/’}),
url(r’^$’, HomeView.as_view())
]
Yep – you’re right, thanks for letting me know! I’ve updated the urls.py code.
Thank you so much, one of the most complete tutorials I have seen. Not all persons are willing to teach this things together, and the complexity of the scenario gives us good bases. This types of tutorials (even paid) are hard to find. Again, thank you.
Thank you for the nice comments! I’m glad you found the tutorial helpful.
Can you please show one example on how I can make api post call from react to django drf?
Is there any reason why all “post” calls are done via sockets not api in this tutorial?
You can see a few examples of calls from React to the DRF backend in my post. For example, take a look at the getGame() method on the GameBoard.jsx component. That method calls the DRF SingleGameViewSet endpoint to get game details.
And as I mentioned in the post, I tried to mix up different ways of getting data from the Django backend to the React frontend. I wanted to show different ways of achieving the same thing: sending data through the standard Django response via context, DRF calls to the backend, and Django Channels websocket calls. In reality, this isn’t how I would structure a production app, but I was hoping it would be informative. Hopefully not confusing at the same time.
Wow! Thanks again for sharing this tutorial. I am amazed by your generosity. The tutorial is intense.
Let me give some suggesting for how you can improve it. I found that very often the flow of tutorial is going from big concepts (code snippets) to a smaller ones. For example several times you are first putting together some views, react components or api_views and then go to show some serializers, consumers, routers, urls and so on. This can be sometimes confusing, since a student can receive error messages that those small parts are not yet existed. I think going from small concepts to bigger would be more easily to understand. Also, please check your github code. I think it does not work if you just download it and want to use. Several imports are configured improperly (signal in apps.py, for instance)
Thank you again!
Thanks for suggestions. Yes this was my first large tutorial so it definitely could be optimized and improved. I did the GitHub project well before the post, but it worked for me when I last tried it. It could be a python2/python3 import issue. I’ll update that tonight and get it working.
not sure if the instruction on page 8 is correct
class ClaimSquareView(APIView):
def get_object(self, pk):
try:
return Game.objects.get(pk=pk)
except Game.DoesNotExist:
raise Http404
def put(self, request, pk):
game = self.get_object(pk)
# update the owner
print(game)
return Response(serializer.errors)
– no import for Http404
– serializer is not defined
You’re right! That view isn’t even needed… I think I started going that direction to claim a square, but moved it to a Channels call using the consumer instead. I’ve removed that reference and the url reference.
Thank you very much for your suggestions and bug reports! I’ve added you to the “Thank you” section at the bottom of the post.
on page 7 views.py also should import
from django.contrib import messages
Added it, thank you.
Also, in my setup in view/__init__.py instead of
from views import *
from api_views import *
I need to enter
from .views import *
from .api_views import *
Yes this is probably because you’re on Python 3 and implicit relative imports like that won’t work. I’m on 2.7 and they work with it. Thanks for pointing that out. I’ll update the post to note this.
on the page 2, it is very important to highlights this setting in the settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, “static”),
]
it is not something that is added by default if start project with django-admin tools
Thanks, yes when I first talk about the settings file, I recommended overwriting all of the default code with what I show in the post. I’ll make sure that it’s more clear.
Thanks, confirm MIDDLEWARE_CLASSES fixed the issue with ‘AsgiRequest’ object has no attribute ‘session’
after following all instruction on the page 4, cannot login, getting this error
AttributeError at /login/
‘AsgiRequest’ object has no attribute ‘session’
Request Method: POST
Request URL: http://127.0.0.1:8080/login/
Django Version: 1.9.12
Exception Type: AttributeError
Exception Value:
‘AsgiRequest’ object has no attribute ‘session’
Exception Location: /home/gideon/virtualenvs/vEnv_my_obstruct_game/lib/python3.4/site-packages/django/contrib/auth/__init__.py in login, line 101
Python Executable: /home/gideon/virtualenvs/vEnv_my_obstruct_game/bin/python
Python Version: 3.4.3
Python Path:
[‘/home/gideon/PycharmProjects/my_obstruct_game’,
‘/home/gideon/virtualenvs/vEnv_my_obstruct_game/lib/python3.4/site-packages/setuptools-18.1-py3.4.egg’,
‘/home/gideon/virtualenvs/vEnv_my_obstruct_game/lib/python3.4/site-packages/pip-7.1.0-py3.4.egg’,
‘/home/gideon/PycharmProjects/my_obstruct_game’,
‘/usr/lib/python3.4’,
‘/usr/lib/python3.4/plat-x86_64-linux-gnu’,
‘/usr/lib/python3.4/lib-dynload’,
‘/home/gideon/virtualenvs/vEnv_my_obstruct_game/lib/python3.4/site-packages’]
Server time: Mon, 6 Feb 2017 15:53:42 +0000
Traceback Switch to copy-and-paste view
/home/gideon/virtualenvs/vEnv_my_obstruct_game/lib/python3.4/site-packages/django/core/handlers/base.py in get_response
response = self.process_exception_by_middleware(e, request) …
▶ Local vars
/home/gideon/virtualenvs/vEnv_my_obstruct_game/lib/python3.4/site-packages/channels/handler.py in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
One thing that could cause this with Django 1.9+ is if you have MIDDLEWARE instead of MIDDLEWARE_CLASSES in your settings.py file. Can you check that?
It seems there is an error in this instruction
npm install –save-dev react react-dom webpack webpack-bundle-tracker babel-core babel babel-loadernpm babel-preset-es2015 react-websocket babel-preset-es2015 babel-preset-react jquery
“babel-loadernpm” should read “babel-loader”
Yep, you’re right – a little copy-paste issue on my part. It’s fixed now. Thanks for letting me know!
I have not yet finished your tutorial, but for what I see I can tell you huge THANK YOU!
Thank you, I hope it you find it useful. Please let me know if you have any issues!