HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Beginner grid-based game movement engine

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enginegridmovementbeginnergamebased

Problem

Tell me how I can make it more efficient, shorter. How I can make it adhere more to convention? Is there some stuff I'm doing that you would do in a better way?

The main gist is that I create and populate a 2d-array with objects, and use PyGame to display it graphically. We have a Hero, who is a Character object, that can move around the grid. The hero, internally, keeps track of his coordinates.

The update function scans the grid and checks for disagreements between the hero's internal coordinates and his place on the map (as a result of the move function). If there is a disagreement, it destroys the hero and resurrects him in the new location that agrees with his internal coordinates.

```
import random as random
import pygame as pygame

pygame.init() #start up dat pygame
clock = pygame.time.Clock() #for framerate or something? still not very sure
Screen = pygame.display.set_mode([650, 650]) #making the window
Done = False #variable to keep track if window is open
MapSize = 25 #how many tiles in either direction of grid

TileWidth = 20 #pixel sizes for grid squares
TileHeight = 20
TileMargin = 4

BLACK = (0, 0, 0) #some color definitions
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff.
def __init__(self, Name, Column, Row):
self.Name = Name
self.Column = Column
self.Row = Row

class Character(object): #Characters can move around and do cool stuff
def __init__(self, Name, HP, Column, Row):
self.Name = Name
self.HP = HP
self.Column = Column
self.Row = Row

def Move(self, Direction): #This function is how a character m

Solution

Styling

Python has its own official style guide (written by the author of Python) called PEP 8. It has some things to say about your code. By the way, you can check your code against PEP 8 by installing the PyPi package or by trying it online.

Naming

It's great to see that you have constants instead of using those numbers manually. I am also happy to see that your constant names are ALLCAPS. I do notice, however, that some of your constants do not have that. For example, TileWidth is in PascalCase. I can see why you might consider it different: colors always have the same rgb values, but the tile width could change; but the important thing is that it doesn't change within the program. It starts as 20 and is always 20.

Many of your variables are in PascalCase, but not quite all of them (Map.update(), for example). Above all, be consistent. Okay, not above all; PEP 8 does mention that A Foolish Consistency is the Hobgoblin of Little Minds. It also recommends snake_case for method names and instance variables. That means, pretty much everything except constants and classes. Constants, as I mentioned before, are ALLCAPS. Classes are actually supposed to be how you have them: PascalCase.

Importing

When you import random, you are importing a module called random.py that is somewhere in your Python path. What is done with that module? It is called random. If you want to give a different name, you can do import random as rand, for example. You don't need to do import random as random. Your imports are still not how PEP 8 recommends:


Imports should be grouped in the following order:



  • standard library imports



  • related third party imports



  • local application/library specific imports





You should put a blank line between each group of imports.

(Emphasis mine.)

Comparisons to booleans

All that an if block needs for a condition is something that can be interpred as Truthy or Falsey. It doesn't necessarily need to be the actual boolean values True and False. In fact, a common way to see if a list is empty uses that:

if mylist:
    print("It is populated!")
else:
    print("Nothing in here.")


You see, the ==, >, <, etc. don't need to be in it. When something returns a boolean value, you don't need to see if it is equal to True. Just check if it is Truthy. That means, use if ...: instead of if ... == True:, and use if not ...: instead of if ... == False:.

Comments

I would recommend that you read the PEP 8 section on comments. Well, I recommend that you read the whole PEP, but read this one especially. The inline comments are helpful, but a little too much. For example, one of your comments is:

#for framerate or something? still not very sure


If you aren't sure, don't bother to write the comment. In fact, anyone reading your code should look up the PyGame documention if he doesn't understand it. Your script is not a tutorial on third-party modules. You should have comments for the logic of your code, not for the third-party syntax.

There are also some comments that aren't needed because the code itself is obvious. For example, we all know that black, white, green, red, and blue are colors. We also know what an assignment looks like, so we don't need a comment that says:

#some color definitions


Don't feel obligated to write a comment for everything. Your goal should be to write code that is clear enough that it doesn't need comments. Of course, that can be hard to attain. If a comment is required, by all means include it. Don't skimp on comments, but don't wear out your keyboard.

PEP 8 also mentions that a comment should have a space between the hash sign and the first character of the comment. After all, the hash sign is not part of the first word, so it should have its own space.

It also mentions that inline comments should be used sparingly. It can get a little out of hand if your comments make your line 130 lines long, and then you look at the code in something that has wordwrap, so it looks all messed up. Then again, a text editor that doesn't wrap could be annoying. You might not like needing to scroll horizontally back and forth to see the comment then the code. It is often better to put the comment above the line it is commenting on.

Whitespace

I actually took my own advice and installed the PEP 8 package. Running your code through it brought to my attention some whitespace oddities. It noted some whitespace that was added to the end of some lines, and it also mentioned "too many blank lines" in a couple places. The PEP 8 package, of course, got its information from PEP 8 itself. You can find PEP 8's opinion here. I don't see it anywhere mention using three lines. In a couple places, you use even four lines, but PEP 8 recommends methods of a class to be separated by one blank line, and class and function definitions by two lines.

One more thing that it caught: your `C

Code Snippets

if mylist:
    print("It is populated!")
else:
    print("Nothing in here.")
#for framerate or something? still not very sure
#some color definitions
def move(self, direction):
    if self.collision_check(direction):
        return False

    # UP should be a global constant
    if direction == UP and self.row > 0:
        self.row -= 1
    ...
pygame.draw.rect(screen, color, [
   (tile_margin + tile_width) * column + tile_margin,
   (tile_margin + tile_height) * row + tile_margin,
    tile_width, tile_height
])

Context

StackExchange Code Review Q#139102, answer score: 9

Revisions (0)

No revisions yet.