0

I'm making my first attempt at programming a game. It's going to be a simple adventure game played in a web browser, I'll use django to display stuff in html and python to work in the background. I'm having troubles in defining the map class, namely operating on coordinates.

My maps need to have a spawn location and walls (for now). So for spawn I could do...

spawnx=models.IntegerField()
spawny=models.IntegerField()

...but it feels like an ugly workaround. I've never used lists before, and I also remember there's this dictionary thingy in python. Do they have any specific advantages? Keep in mind that spawn locations won't be changed, they just need to store coordinates in which players spawn. Does anyone have an idea?

My second problem are walls: I really need to use a list of some kind here. But again, I can't figure out how they work, especially in Django.

So to summarise my biggest problem is figuring out how lists work in Django - like, which field they use and how they can be accessed.

Thanks!

Dunno
  • 3,632
  • 3
  • 28
  • 43
  • If you need to store just lists, maybe redis can be more usefull than Django Models... http://redis.io/commands#list – joaoricardo000 Aug 12 '13 at 17:29
  • @JRicardo000 I'm using Django because I want to store the map in a database. – Dunno Aug 12 '13 at 17:37
  • @dm03514 I know that, but I couldn't find anything about my problem - which is using lists in Django models. – Dunno Aug 12 '13 at 17:39

1 Answers1

1

Out of the box, Django has no support for storing a list in a field. The only way to store multiple data against a single field is a ManyToMany relationship to another table... however, this seems a little overkill when all you're really wanting to store is a list of two-integer tuples.

Have a look at the top answer on this question. It's an implementation of a ListField for Django, that allows storing of basic Python types - i.e, a list of tuples.

This is an example of how that code may work (untested, adapting their 'taking it for a spin example in that question'):

>>> from foo.models import Map, ListField
>>> map = Map()
>>> map.spawn_locations
[]
>>> map.spawn_locations = [(1, 1), (-1, 12), (24, 52)]
>>> map.spawn_locations
[(1, 1), (-1, 12), (24, 52)]
>>> f = ListField()
>>> f.get_prep_value(map.spawn_locations)
u'[(1, 1), (-1, 12), (24, 52)]'

Then, to choose a random place to spawn:

>>> import random
>>> random.choice(map.spawn_locations)
(24, 52)
>>> random.choice(map.spawn_locations)
(1, 1)
Community
  • 1
  • 1
Ben
  • 6,687
  • 2
  • 33
  • 46