Jump to content

  • Log In with Google      Sign In   
  • Create Account


DavitosanX

Member Since 05 Jul 2012
Offline Last Active Jul 14 2014 08:52 AM
-----

#5166019 Hexagonal grid - Code review request

Posted by DavitosanX on 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!




#5159621 java or javascript?

Posted by DavitosanX on 10 June 2014 - 04:24 PM

Well, I meant to say things like:

 

- How do statements end (semicolon or no semicolon)

- How to write if's, for's and while's

- Operators

- Class and function definition

 

These are some differences between Python and C++

 

Python:

#Statements need no semicolon

print("Hello world!") #Function call. Arguments go inside parentheses. Strings go between quotes.

x = 0 # Assignment operator

#Structure of an IF

if x == 0:              # Comparison operators
    print("True")    # Forced indentation for scope, no brackets.
else:                    # Colon after if, elif, else
    print("False")

list = [1,2,3,4]

# Structure of a for loop

for item in list:
    print(item)

# Structure of a while loop

while list[0] != 1:
    print("Looping...")

# Function definition

def foo(arg1, arg2):                  #keyword def, arguments between parentheses, colon
     -- code to run --                   # Forced indentation

# Class definition

class Foo:
      def __init__(self):
            -- contructor code --
      -- define more attributes methods --

C++

// Needs main function
#include <iostream>

using namespace std; // Statements need semicolons

int main()
{
cout << "Hello World!" << endl;     // Bitwise shift operator
return 0;                           // Indentation is optional, brackets are necessary to indicate scope
}

int x = 0; // Assignment operator (strong-typed language, not syntax related, though)

// Structure of an IF

if (x == 0)
{
   cout << "True" << endl;
}
else
{
    cout << "False" << endl;
}

// For loop

for (int i = 0; i < 10; i++)
{
    // some code
}

// While loop

while (variable == value)
{
     // some code
}

// Function definition

void Foo(int arg1, bool arg2)     // starts with type, arguments between parentheses, also with type
{
    // some code
}

// Class definition

class Foo
{
      int privateAttribute;                               // Attribute

     public:

           Foo()                                                 // Constructor
           {
                  privateAttribute = 0;
           }
}

The examples might not be 100% accurate, but my point is that if you know what you're doing, syntax shouldn't be too much of a problem. How long did it take you to see the differences between the two blocks of code? And notice how syntax is consistent across the language, so the differences between a language and another tend to be consistent also.

 

A different thing is the actual use and logic of each language which can be extremely different, and it can take weeks or months to make the switch from one language to another.




#5159593 java or javascript?

Posted by DavitosanX on 10 June 2014 - 02:39 PM

The truth is both languages can be easy or hard, depending on what you wish to do. For scripting purposes, once you learn the syntax of the language (a one or two hour endeavor, tops) there would be little differences between them. You should concentrate on learning how to translate your ideas into instructions for the computer. You can do that in any language you want.

 

If you can use C# in Unity, go with that. It's strong-typed, which I think is important when starting out. It uses a syntax similar to Java, if I'm not mistaken, and the programming concepts you learn with it can be used in javascript, or in any other language.




#5158503 Tile-Based Movement Algorithm

Posted by DavitosanX on 05 June 2014 - 02:18 PM

What framework are you working on? I don't think you have to do any collision detection. Let's say your tile's side is 30 pixels. When the players presses the left arrow key, for example, you'll tell the program to move the player spirte 30 px to the left at a rate of x pixels per frame, probably animating the sprite. You do need to raise a flag that the sprite is moving, so that other key presses are ignored.

 

This is my version of the solution, although I'm a terrible programmer, and it might be a little convoluted:

import pygame
from pygame.locals import *

pygame.init()

clock = pygame.time.Clock()
screen = pygame.display.set_mode((800,600))
image = pygame.image.load('logo.png')
imagePos = [330,250]

running = True
movement = False
direction = ''
initialPos = imagePos[0]

def moveImageRight(movement,initialPos):
    if movement == True:
        if imagePos[0] != initialPos + 30:
            imagePos[0] += 3
            return True
    initialPos = imagePos[0]
    return False

def moveImageLeft(movement,initialPos):
    if movement == True:
        if imagePos[0] != initialPos - 30:
            imagePos[0] -= 3
            return True
    initialPos = imagePos[0]
    return False

while running:

    clock.tick(60)

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

    key = pygame.key.get_pressed()

    if key[K_RIGHT]:
        if movement == False:
            movement = True
            direction = 'right'
            initialPos = imagePos[0]

    if key[K_LEFT]:
        if movement == False:
            movement = True
            direction = 'left'
            initialPos = imagePos[0]

    if direction == 'right' and movement:
        movement = moveImageRight(movement,initialPos)

    if direction == 'left' and movement:
        movement = moveImageLeft(movement,initialPos)

    screen.fill((200,200,200))
    for i in range(30):
        pygame.draw.line(screen,(0,0,0),(30*i,0),(30*i,600),2)
        
    screen.blit(image,tuple(imagePos))
    pygame.display.flip()

pygame.quit()

I drew the lines just to check that the sprite won't move other than 30 pixels to either direction.




#5157645 RPG Maker - Free weekend on Steam

Posted by DavitosanX on 02 June 2014 - 02:55 PM

They also have a bunch of DLC on the Weekly Humble Bundle.  Must be a thing...

 

https://www.humblebundle.com/weekly

 

If I'm not mistaken, the actual RPG Maker software is included as well. I've always thought that RPG Maker was too restricted for my taste, but maybe time has come to give it a try. God, I love Humble Bundle.




#5157637 Advise for a beginner needed

Posted by DavitosanX on 02 June 2014 - 02:40 PM

Give the Unreal Engine a try. It's free to download and use, and is great for FPS games. It's not programming, but you could learn a lot about game design and get good visual results very fast.

 

As Sunsharior said, your first games really have to be something far more simpler. That way you learn every aspect of programming step by step. I just finished a 'Guess the number' game in python, and it was challenging! Through this little 'game' I learned about exceptions and file I/O, two aspects of programming I didn't undertand before. If you want to look at the code, follow the link in my signature.




#5022363 Beginning to code in C++, some rookie questions.

Posted by DavitosanX on 16 January 2013 - 05:47 PM

I would personally recommend against using code that you find on the web if you have no idea what it does. When something goes wrong (and it often does in programming) you'll have no idea what might be the problem, where is it, or how to fix it. Work through tutorials, books and references, and find it what each lines means. At the very least, get a general idea.

 

I also second the suggestion to start with python.




#4960485 Complete beginner

Posted by DavitosanX on 18 July 2012 - 08:27 AM

I would suggest trying different languages out, but I suppose that sounds a little daunting to a complete beginner. In my experience (which isn't much), Python is a fairly aproachable language, and is currently used by lots of developers. I'd say it's a good place to start.

Check this out: http://docs.python.org/tutorial/


#4960262 Regarding what library/langauge to use

Posted by DavitosanX on 17 July 2012 - 06:10 PM

I appreciate you encouraging people to learn C++ as first language. I also heard about this language called DarkBASIC, that might be a great starting point for several beginners


Well, I didn't mean to encourage its use, because it might not be a good first step for everybody. My emphasis is on trying it out and experiencing it as a language if you're interested. If it turns out it's too hard, or the concepts too abstract, you can rest assured there are friendlier lanuages out there.


#4960121 Regarding what library/langauge to use

Posted by DavitosanX on 17 July 2012 - 01:02 PM

There are a lot of threads in this forum, started by beginners such as myself, that ask which language to use, which one is easier, which one is more powerful. Same goes for game developing libraries or programs. I thought it would be constructive to present my experience as a beginner in this topic.

I've had an interest in programming since I took a QBasic course in middle school, although I didn't try to learn to program in earnest until a year ago. I started out with python, which was presented to me as a very simple and powerful language, also welcoming for beginners. I had just gotten my feet wet with python, when I started reading comments on how innefficient it was when it came to game programming. (Important note: Start taking forum comments as opinions, sometimes based on valuable experienced, but nothing more. You have to develop your own criteria through experience)

So I switched from python to C++, and continued learning, mostly through online tutorials and helpful individuals. It was a difficult, but enlightening at the same time. For example, the concept of functions was clearer to me when I used them in C++ than when I tried to use them in python. (In retrospective, it was the use of functions per se that cleared the concept, not the way the any of the languages present them.) It's curious how the simplicity and efficiency of working with python only became clear after I had worked with C++.

Even though I was overwhelmed by certain aspects of C++ (namely, pointers, templates and headers) I liked its strictness regarding syntax, which felt to me a lot more organized than python's. (Forced indentation vs curly brackets? Give me brackets any day!) I continued learning and eventually introduced myself to SDL, and subsequently to SFML. Finally, I could see some graphics on the screen! I wasn't making games yet, but at least I was moving sprites around, and that felt great by itself.

After using SFML for some time, I got interested in XNA, and figured that the jump from C++ to C# wouldn't be much problem. Turns out that I was misusing C++. Instead of programming in an object oriented paradigm, I was actually doing C/C++ halfbreed programs. I'm still getting the hang of object-oriented programming, but the point is that working with a fully OO Language (C#) was what made it evident.

While I had used classes in C++, I didn't grasp their concept until I programmed in C#. And with C#/XNA I learned valuable lessons regarding how to distribute jobs between classes, giving different parts of the program very specific instructions to carry out. As a result, when I returned to C++/SFML, I felt encouraged to work with multiple files and headers. No more gigantic main.cpp files. Instead, I created directories with main,cpp, input.cpp, gameloops.cpp, mouse.cpp, graphics.cpp, and so on.

Most importantly, all of this time I had been programming.

I learned to read g++'s compiler errors and Visual Studio's errors and warnings. I learned the value of an IDE after working with gedit (which I still use, and is great), and I learned that newbies have nothing to do messing with vi(m) or emacs (maybe I'll try again when I'm a proficient programmer). Every switch I made, from language to language, library to library, taught me something new.

In conclusion, I want to make it evident that you shouldn't be asking which language you should use, or which library. You should try it out for yourself. You'll learn a lot in the process. You'll learn that there are so many choices out there because each one serve different purposes. Experiment, and you'll find which one is right for you and your project. I've been going at this for a year (granted, I got a day job which keeps me busy) and I still consider myself a beginner.

I guess most of the content of this post was already said elsewhere (especially Tom Sloper's site, which is an excellent source of advice and information), but since the question regarding which language to learn and which library to use pops up so often, it might as well be said again.


#4956045 C++ not initilizing

Posted by DavitosanX on 05 July 2012 - 11:59 AM

Just as a side note, you would benefit greatly by learning about classes. Try the tutorials at cplusplus.com: http://www.cplusplus.com/doc/tutorial/ , I learned a lot about C++ there.

Also, I believe the right term for your problem is "the following code won't compile". I don't think there's such thing as C++ initialization.


PARTNERS