Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


DavitosanX

Member Since 05 Jul 2012
Offline Last Active Oct 30 2014 01:36 PM

Topics I've Started

Hexagonal grid - Code review request

10 July 2014 - 08:28 AM

Hello! I'm not sure if this belongs here, or in the beginners' section, so excuse me if this code is too bad, or too basic.

 

I had set a short term goal for myself as an amateur programmer: To implement a hexagonal grid, similar to the one found in the original Fallout. You should be able to move your mouse around and the hexagon that contains the mouse pointer should be highlighted. I thought it would be a good exercise, because unlike a square grid, determining which hexagon contains the mouse pointer is trickier.

 

I did finish the program, and it does exactly what I want, but I do tend to overcomplicate things and I would appreciate it if people with more  experienced took a look at it and gave me any tips. This was coded in python with pygame.

import pygame
import math

INITIAL_HEXAGON_VERTICES = ((-40,-40),(40,-40),(45,0),(40,40),(-40,40),(-45,0))
GRID_HEIGHT = 10
GRID_WIDTH = 10
VERTEX_COUNT = 6
X_ELEMENT = 0
Y_ELEMENT = 1
FIXED_ANGLE = 0.122 #7 degrees in radians
NOT_MOVING = (0,0)




def calculate_angle(fixed_point,var_point):

    opposite = math.fabs(fixed_point[X_ELEMENT] - var_point[X_ELEMENT])
    adjacent = math.fabs(fixed_point[Y_ELEMENT] - var_point[Y_ELEMENT])
    if adjacent == 0:
        adjacent = 0.1

    angle = math.atan((opposite/adjacent))

    return angle


class Hexagon:

    def __init__(self,num,ver):

        self.number = num
        self.vertices = ver



class InputManager:

    def check_events(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game.running = False



    def mouse_in_grid(self,mouse_pos,hexagons):

        result = 0

        for counter,hexagon in enumerate(hexagons):

            if (mouse_pos[X_ELEMENT] > hexagon.vertices[5][X_ELEMENT]
                and mouse_pos[X_ELEMENT] < hexagon.vertices[2][X_ELEMENT]
                and mouse_pos[Y_ELEMENT] >= hexagon.vertices[0][Y_ELEMENT]
                and mouse_pos[Y_ELEMENT] < hexagon.vertices[3][Y_ELEMENT]):

                    result = hexagon.number

                    if (mouse_pos[X_ELEMENT] < hexagon.vertices[0][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] < hexagon.vertices[5][Y_ELEMENT]):
                            
                            angle = calculate_angle(hexagon.vertices[0],mouse_pos)
                            
                            if angle < FIXED_ANGLE:
                                result = hexagon.number
  
                    if (mouse_pos[X_ELEMENT] > hexagon.vertices[1][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] < hexagon.vertices[2][Y_ELEMENT]):
                                
                            angle = calculate_angle(hexagon.vertices[1],mouse_pos)
                                
                            if angle < FIXED_ANGLE:
                                result = hexagon.number

                    if (mouse_pos[X_ELEMENT] > hexagon.vertices[3][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] > hexagon.vertices[2][Y_ELEMENT]):
                               
                            angle = calculate_angle(hexagon.vertices[3],mouse_pos)
                                
                            if angle < FIXED_ANGLE:
                                result = hexagon.number

                    if (mouse_pos[X_ELEMENT] < hexagon.vertices[4][X_ELEMENT]
                        and mouse_pos[Y_ELEMENT] > hexagon.vertices[5][Y_ELEMENT]):
                                
                            angle = calculate_angle(hexagon.vertices[4],mouse_pos)
                                
                            if angle < FIXED_ANGLE:
                                result = hexagon.number

        return result




class Game:



    def __init__(self,resolution,caption):

        self.screen = pygame.display.set_mode(resolution)
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.running = True
        self.gray = (220,220,220)
        self.green = (50,240,50)
        self.black = (0,0,0)
        self.hexagons = []
        self.current_hexagon = 0



    def draw_screen(self):
        self.screen.fill(self.gray)

        if pygame.mouse.get_rel() != NOT_MOVING:
            self.current_hexagon = input_manager.mouse_in_grid(pygame.mouse.get_pos(),self.hexagons)

        pygame.draw.polygon(self.screen,self.green,self.hexagons[self.current_hexagon].vertices,3)

        pygame.display.flip()



    def calculate_grid_points(self):

        number = 0

        for column in range(GRID_WIDTH):

            for row in range(GRID_HEIGHT):

                points = []
                lift_hexagon = 0

                if column % 2 != 0:
                    lift_hexagon = 40

                for point in range(VERTEX_COUNT):

                    points.append(  ((INITIAL_HEXAGON_VERTICES[point][X_ELEMENT] + (85 * column)),
                                    ((INITIAL_HEXAGON_VERTICES[point][Y_ELEMENT] + (80 * row))-lift_hexagon)  ) )

                new_hexagon = Hexagon(number,points)
                self.hexagons.append(new_hexagon)
                number += 1
                



    def main_loop(self,framerate):

        self.calculate_grid_points()

        while self.running:

            self.clock.tick(framerate)
            input_manager.check_events()

            self.draw_screen()

        pygame.quit()





input_manager = InputManager()
game = Game((800,600),"Game")
game.main_loop(60)

Thanks in advance!


Code review for Object Orientation

05 June 2014 - 10:16 PM

I have never truly grasped the concept of object orientation. I tend to make classes that don't make much sense, or I fail to encapsulate correctly. I think I'm getting better at it, but I'm open to suggestions. In the following code, do you think I'm being correctly object oriented? I really appreciate any help.

import pygame
from pygame.locals import *



class Ball:

    def __init__(self,imageFile,position_arg):
        self.image = pygame.image.load(imageFile)
        self.position = (position_arg)



class AssetManager:

    def load_ball(self,imageFile,position):
        return Ball(imageFile,position)



class Game:

    def __init__(self,resolution,caption):

        self.screen = pygame.display.set_mode(resolution)
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()
        self.running = True
        self.gray = (220,220,220)

    def check_events(self):

        for event in pygame.event.get():
            if event.type == QUIT:
                self.running = False

    def draw_screen(self,ball):
        self.screen.fill(self.gray)
        self.screen.blit(ball.image,ball.position)
        pygame.display.flip()

    def main_loop(self,framerate,assets):

        ball = assets.load_ball('ball.png',(350,250))

        while self.running:

            self.clock.tick(framerate)
            self.check_events()

            self.draw_screen(ball)

        pygame.quit()



assets = AssetManager()
game = Game((800,600),"Game")
game.main_loop(60,assets)

New Game Dev blog - Beginner level

23 May 2014 - 10:12 AM

Hello! I wanted to promote my new blog, called 'My Own Game Journey'. In it I'm going to log my attempt to make a video game. Since me schedule is rather busy, it's really more of an exercise in programming and blogging, but I'm sure it could be useful to any beginners who want to learn how to code. I'm using python and pygame, and starting from console programs and working my way up from there.

 

Right now I've started a 'Guess the number' series of posts, adding new features and complexity to the code with each one.

 

Drop by if you're interested!

 

Here's the link: http://myowngamejourney.blogspot.mx/


Video Game Music Countdown

12 September 2013 - 10:08 AM

Hello everybody! For a while now I've wanted to share with the internet some of my favorite video game tracks, through a Youtube video. I know nobody likes blatant 'watch my video!' threads or comments, but a video which isn't announced just doesn't get watched. In any case, I'd love to hear your opinion on this countdown.

 

The topic is: Video game songs that stayed with you, that you hum occasionally while driving, or waiting in line. Tunes that aren't necessarily great, but manage to be unforgettable.

 

This is my own list:

 

10 - Yearnings of wind - Chrono Trigger (it's the 600 AD theme)

9 - Green Green - Kirby's Epic Yarn (I actually heard it for the first time on Kirby's Dreamland, but the Wii version is just amazing)

8 - Dr. Wily's Castle - Mega Man 2

7- Opening Theme - Silent Hill (PS1)

6 - Dance of the Holy Man - Super Castlevania IV (First Stage)

5 - Hyrule Castle - Zelda: LttP

4 - Overworld Theme - Final Fantasy IV

3 - Sim Broadway - SimCity 3000

2 - Call of Magic - Morrowind

1 - Scars of Time - Chrono Cross

 

Here's the video link: https://www.youtube.com/watch?v=vx54q7j


Any suggestions for better code? Python "Guess the number"

15 January 2013 - 02:23 PM

Hello everyone! I haven't been able to spend time programming for some months now, so I decided to brush up my very few skills by writing simple programs. I opted for "Guess the number" since it's pretty basic stuff (or so i thought). My main trouble was that I wanted to let the player quit by typing "quit", instead of asking for a number, for example "0". 

 

If any other newbie has tried out this program, the problem is when the user tries to input anything other than a number. Python (not without reason) doesn't type-cast it into anything with int(), so the program crashes. The following is my solution to this problem, but it doesn't look very elegant at all.

 

I would appreciate any suggestions on making the code better. Thanks!

 

 

 
 
from random import *
 
print("\n* * * Welcome! * * *\n\nGo ahead and try to guess a number from 1 to 10. If you feel like quitting, type QUIT\n")
 
seed()
playing = True
validating = True
number = randint(1,10)
 
while playing:
 
    while validating:
        guess = input("Your guess? ")
        try:
            int(guess)
            break
        except:
            if str.upper(guess) == "QUIT":
                print ("Goodbye!")
                validating = False
                playing = False
            else:
                print("\nI don't think that was a number\n")
 
    if playing == False:
        break
    
    if int(guess) == 0:
        print ("Goodbye!")
        playing = False
    elif int(guess) < number:
        print("\nA little higher...\n")
    elif int(guess) > number:
        print("\nA little lower...\n")
    else:
        print("\nYou got it!\n")
        playing = False
 
 

 


PARTNERS