Star Dodger Pygame !

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.

Star Dodger Pygame !

Postby ChristianCareaga » Sat Jun 22, 2013 10:06 am

Hey guys i recently created my first full pygame !!

its called star dodger its nothing to special but its pretty fun

you can download it here https://github.com/C-Dubb/StarDodgerV2

if you take the time to download it please star it so i can see if anyone downloaded it!

also i will attach it so you can download it that way too
StarDodger!.zip
(177.48 KiB) Downloaded 155 times





Thank you so much!!
ChristianCareaga
 
Posts: 52
Joined: Sat Jun 22, 2013 9:54 am

Re: Star Dodger Pygame !

Postby Mekire » Sun Jun 23, 2013 5:10 pm

Nice first game and great to see you using functions and classes.

Firstly (at least in your attached zip), there is a line in your class __init__ that is incorrectly indented, stopping your program from running. Also you didn't include that highscores data file.

On to the code. As I said, it is nice to see you using a class to contain your code but you have missed part of the point of OO programming. You have 4 sprites in this game (the three stars and the force field) that essentially act the exact same way. This is a prime opportunity to use a class. You shouldn't need to retype the same code multiple times if they have the exact same functionality.

Other things: You should refrain from using:
Code: Select all
from pygame.locals import *
You shouldn't reload resources (images, fonts, etc) every time you use them. You should also look into how to make images have transparent backgrounds.

If you are interested, take a look the following rewrite (it may not emulate your game perfectly and it could certainly still be cleaned up more):
Code: Select all
import os,sys,random
import pygame as pg

class Player(object):
    def __init__(self):
        self.image = GAME_GFX["mouse"]
        self.rect = self.image.get_rect()
        self.force_image = GAME_GFX["force_img"]
        self.force_field = 0
        self.force_rect = self.force_image.get_rect()
    def update(self,Surf):
        self.rect.center = pg.mouse.get_pos()
        self.force_rect.center = self.rect.center
        if self.force_field:
            Surf.blit(self.force_image,self.force_rect)
        Surf.blit(self.image,self.rect)

class Star(object):
    def __init__(self,name,speed,domain):
        self.image = GAME_GFX[name]
        self.rect = self.image.get_rect()
        self.speed = speed
        self.domain = domain
        self.get_new()
    def update(self,Surf):
        if self.rect.y > 640:
            self.get_new()
        self.rect.y += self.speed
        Surf.blit(self.image,self.rect)
    def get_new(self):
        self.rect.y = 0
        self.rect.x = random.randint(*self.domain)

class State(object):
    def __init__(self):
        self.done = False
        self.next = None

class Game(State):
    def __init__(self):
        State.__init__(self)
        self.next = "GAMEOVER"
        self.Font = pg.font.SysFont("impact", 20)
        self.prev_highscore = self.get_highscore()

        self.MyPlayer = Player()
        self.ForceField = Star("force_img",5,(10,310))
        self.Stars = [Star("star1",7,(5,110)),
                      Star("star2",6,(100,200)),
                      Star("star3",8,(190,315))]

        self.round = 0
        self.random_ev = 1
        self.start_time = None
        self.current_time = None
        self.score = 1

    def update(self,Surf):
        if self.start_time == None:
            self.start_time = pg.time.get_ticks()
            self.current_time = pg.time.get_ticks()
        Surf.blit(SCREEN_GFX["bg"],(0,0))
        self.time_pass(Surf)
        self.draw_actors(Surf)
        self.collisions(Surf)
        self.display_stats(Surf)

    def draw_actors(self,Surf):
        for Actor in [self.MyPlayer]+self.Stars:
            Actor.update(Surf)

    def collisions(self,Surf):
        for AStar in self.Stars:
            if self.MyPlayer.rect.colliderect(AStar.rect):
                explode_rect = GAME_GFX["explosion"].get_rect(center=self.MyPlayer.rect.center)
                Surf.blit(GAME_GFX["explosion"],explode_rect)
                if self.MyPlayer.force_field:
                    self.MyPlayer.force_field = max(self.MyPlayer.force_field-1,0)
                else:
                    self.save_high_score()
                    self.done = True
                break

    def random_event(self,Surf):
        self.ForceField.update(Surf)
        if self.MyPlayer.rect.colliderect(self.ForceField.rect):
            self.MyPlayer.force_field = 10
            self.random_ev += 2
            self.ForceField.get_new()
        elif self.ForceField.rect.y >= 640:
            self.random_ev += 2
            self.ForceField.get_new()

    def display_stats(self,Surf):
        self.score = int(self.current_time-self.start_time)//5
        score = "Score: {}".format(self.score)
        label = self.Font.render(score, 1, (255,255,0))
        Surf.blit(label,(0,0))
        previous = "Highscore: {}".format(self.prev_highscore)
        score_label = self.Font.render(previous,1,(0,0,255))
        Surf.blit(score_label,(140,0))

    def time_pass(self,Surf):
        self.current_time = pg.time.get_ticks()
        if self.current_time-self.start_time >= 10000*self.round:
            self.round += 1
            for Star in self.Stars:
                Star.speed += 2
        if self.current_time-self.start_time >= 10000*self.random_ev:
            self.random_event(Surf)

    def save_high_score(self):
        if self.score > self.prev_highscore:
            with open('highscores.dat','w') as myfile:
                myfile.write(str(self.score))
    def get_highscore(self):
        try:
            with open('highscores.dat') as myfile:
                return int(myfile.read())
        except (IOError,ValueError):
            return 0

class MainMenu(State):
    def __init__(self):
        State.__init__(self)
        self.next = "GAME"
        self.bg = SCREEN_GFX["main"]
        self.play_text =  SCREEN_GFX["play"]
        self.play_rect = self.play_text.get_rect(topleft = (100,400))
        self.player = GAME_GFX["mouse"]
    def update(self,Surf):
        Surf.blit(self.bg,(0,0))
        Surf.blit(self.play_text,self.play_rect)
        Surf.blit(self.player,pg.mouse.get_pos())
        if pg.mouse.get_pressed()[0]:
            if self.play_rect.collidepoint(pg.mouse.get_pos()):
                self.done = True

class GameOver(State):
    def __init__(self):
        State.__init__(self)
        self.next = "MENU"
        self.bg = SCREEN_GFX["game_over"]
    def update(self,Surf):
        keys = pg.key.get_pressed()
        Surf.blit(self.bg,(0,0))
        if (keys[pg.K_RETURN]):
            self.done = True

class Control(object):
    def __init__(self):
        self.done = False
        self.Screen = pg.display.get_surface()
        self.Clock = pg.time.Clock()
        self.state_dict = {"MENU"     : MainMenu(),
                           "GAME"     : Game(),
                           "GAMEOVER" : GameOver()}
        self.State = self.state_dict["MENU"]
    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
    def main(self):
        while not self.done:
            self.Screen.fill(0)
            self.event_loop()
            self.State.update(self.Screen)
            if self.State.done:
                self.State.__init__()
                self.State = self.state_dict[self.State.next]
            self.Clock.tick(50)
            pg.display.update()

###
def load_gfx(directory):
    graph_dict = {}
    for image in os.listdir(directory):
        name,extension = os.path.splitext(image)
        if extension in (".png",".bmp",".jpg"):
            graph_dict[name] = pg.image.load(os.path.join(directory,image)).convert()
            graph_dict[name].set_colorkey((0,0,0))
    return graph_dict

def main():
    global GAME_GFX,SCREEN_GFX
    os.environ["SDL_VIDEO_CENTERED"] = '1'
    pg.init()
    pg.display.set_mode((320, 640))
    pg.display.set_caption('Mouse Dodge')
    pg.mouse.set_visible(0)

    GAME_GFX = load_gfx(os.path.join("resources","game"))
    SCREEN_GFX = load_gfx(os.path.join("resources","screen"))
    Run = Control()
    Run.main()
    pg.quit();sys.exit()

###
if __name__ == "__main__":
    main()

Anyway, very nice work for your first game. I look forwardto seeing more from you,
-Mek
User avatar
Mekire
 
Posts: 988
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Star Dodger Pygame !

Postby ChristianCareaga » Sun Jun 23, 2013 5:32 pm

Mekire wrote:Nice first game and great to see you using functions and classes.

Firstly (at least in your attached zip), there is a line in your class __init__ that is incorrectly indented, stopping your program from running. Also you didn't include that highscores data file.

On to the code. As I said, it is nice to see you using a class to contain your code but you have missed part of the point of OO programming. You have 4 sprites in this game (the three stars and the force field) that essentially act the exact same way. This is a prime opportunity to use a class. You shouldn't need to retype the same code multiple times if they have the exact same functionality.

Other things: You should refrain from using:
Code: Select all
from pygame.locals import *
You shouldn't reload resources (images, fonts, etc) every time you use them. You should also look into how to make images have transparent backgrounds.

If you are interested, take a look the following rewrite (it may not emulate your game perfectly and it could certainly still be cleaned up more):
Code: Select all
import os,sys,random
import pygame as pg

class Player(object):
    def __init__(self):
        self.image = GAME_GFX["mouse"]
        self.rect = self.image.get_rect()
        self.force_image = GAME_GFX["force_img"]
        self.force_field = 0
        self.force_rect = self.force_image.get_rect()
    def update(self,Surf):
        self.rect.center = pg.mouse.get_pos()
        self.force_rect.center = self.rect.center
        if self.force_field:
            Surf.blit(self.force_image,self.force_rect)
        Surf.blit(self.image,self.rect)

class Star(object):
    def __init__(self,name,speed,domain):
        self.image = GAME_GFX[name]
        self.rect = self.image.get_rect()
        self.speed = speed
        self.domain = domain
        self.get_new()
    def update(self,Surf):
        if self.rect.y > 640:
            self.get_new()
        self.rect.y += self.speed
        Surf.blit(self.image,self.rect)
    def get_new(self):
        self.rect.y = 0
        self.rect.x = random.randint(*self.domain)

class State(object):
    def __init__(self):
        self.done = False
        self.next = None

class Game(State):
    def __init__(self):
        State.__init__(self)
        self.next = "GAMEOVER"
        self.Font = pg.font.SysFont("impact", 20)
        self.prev_highscore = self.get_highscore()

        self.MyPlayer = Player()
        self.ForceField = Star("force_img",5,(10,310))
        self.Stars = [Star("star1",7,(5,110)),
                      Star("star2",6,(100,200)),
                      Star("star3",8,(190,315))]

        self.round = 0
        self.random_ev = 1
        self.start_time = None
        self.current_time = None
        self.score = 1

    def update(self,Surf):
        if self.start_time == None:
            self.start_time = pg.time.get_ticks()
            self.current_time = pg.time.get_ticks()
        Surf.blit(SCREEN_GFX["bg"],(0,0))
        self.time_pass(Surf)
        self.draw_actors(Surf)
        self.collisions(Surf)
        self.display_stats(Surf)

    def draw_actors(self,Surf):
        for Actor in [self.MyPlayer]+self.Stars:
            Actor.update(Surf)

    def collisions(self,Surf):
        for AStar in self.Stars:
            if self.MyPlayer.rect.colliderect(AStar.rect):
                explode_rect = GAME_GFX["explosion"].get_rect(center=self.MyPlayer.rect.center)
                Surf.blit(GAME_GFX["explosion"],explode_rect)
                if self.MyPlayer.force_field:
                    self.MyPlayer.force_field = max(self.MyPlayer.force_field-1,0)
                else:
                    self.save_high_score()
                    self.done = True
                break

    def random_event(self,Surf):
        self.ForceField.update(Surf)
        if self.MyPlayer.rect.colliderect(self.ForceField.rect):
            self.MyPlayer.force_field = 10
            self.random_ev += 2
            self.ForceField.get_new()
        elif self.ForceField.rect.y >= 640:
            self.random_ev += 2
            self.ForceField.get_new()

    def display_stats(self,Surf):
        self.score = int(self.current_time-self.start_time)//5
        score = "Score: {}".format(self.score)
        label = self.Font.render(score, 1, (255,255,0))
        Surf.blit(label,(0,0))
        previous = "Highscore: {}".format(self.prev_highscore)
        score_label = self.Font.render(previous,1,(0,0,255))
        Surf.blit(score_label,(140,0))

    def time_pass(self,Surf):
        self.current_time = pg.time.get_ticks()
        if self.current_time-self.start_time >= 10000*self.round:
            self.round += 1
            for Star in self.Stars:
                Star.speed += 2
        if self.current_time-self.start_time >= 10000*self.random_ev:
            self.random_event(Surf)

    def save_high_score(self):
        if self.score > self.prev_highscore:
            with open('highscores.dat','w') as myfile:
                myfile.write(str(self.score))
    def get_highscore(self):
        try:
            with open('highscores.dat') as myfile:
                return int(myfile.read())
        except (IOError,ValueError):
            return 0

class MainMenu(State):
    def __init__(self):
        State.__init__(self)
        self.next = "GAME"
        self.bg = SCREEN_GFX["main"]
        self.play_text =  SCREEN_GFX["play"]
        self.play_rect = self.play_text.get_rect(topleft = (100,400))
        self.player = GAME_GFX["mouse"]
    def update(self,Surf):
        Surf.blit(self.bg,(0,0))
        Surf.blit(self.play_text,self.play_rect)
        Surf.blit(self.player,pg.mouse.get_pos())
        if pg.mouse.get_pressed()[0]:
            if self.play_rect.collidepoint(pg.mouse.get_pos()):
                self.done = True

class GameOver(State):
    def __init__(self):
        State.__init__(self)
        self.next = "MENU"
        self.bg = SCREEN_GFX["game_over"]
    def update(self,Surf):
        keys = pg.key.get_pressed()
        Surf.blit(self.bg,(0,0))
        if (keys[pg.K_RETURN]):
            self.done = True

class Control(object):
    def __init__(self):
        self.done = False
        self.Screen = pg.display.get_surface()
        self.Clock = pg.time.Clock()
        self.state_dict = {"MENU"     : MainMenu(),
                           "GAME"     : Game(),
                           "GAMEOVER" : GameOver()}
        self.State = self.state_dict["MENU"]
    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
    def main(self):
        while not self.done:
            self.Screen.fill(0)
            self.event_loop()
            self.State.update(self.Screen)
            if self.State.done:
                self.State.__init__()
                self.State = self.state_dict[self.State.next]
            self.Clock.tick(50)
            pg.display.update()

###
def load_gfx(directory):
    graph_dict = {}
    for image in os.listdir(directory):
        name,extension = os.path.splitext(image)
        if extension in (".png",".bmp",".jpg"):
            graph_dict[name] = pg.image.load(os.path.join(directory,image)).convert()
            graph_dict[name].set_colorkey((0,0,0))
    return graph_dict

def main():
    global GAME_GFX,SCREEN_GFX
    os.environ["SDL_VIDEO_CENTERED"] = '1'
    pg.init()
    pg.display.set_mode((320, 640))
    pg.display.set_caption('Mouse Dodge')
    pg.mouse.set_visible(0)

    GAME_GFX = load_gfx(os.path.join("resources","game"))
    SCREEN_GFX = load_gfx(os.path.join("resources","screen"))
    Run = Control()
    Run.main()
    pg.quit();sys.exit()

###
if __name__ == "__main__":
    main()

Anyway, very nice work for your first game. I look forwardto seeing more from you,
-Mek



Yes i fixed the download file you must have downloaded it before i changed it

and Wow! i cant believe you took the time to rewrite it that's crazy but its alot better than the way i wrote it ive only been programming for about 2 months so im still learning everyday and the rewrite will be a huge learning tool

thanks so much for the feedback and pointers!
ChristianCareaga
 
Posts: 52
Joined: Sat Jun 22, 2013 9:54 am

Re: Star Dodger Pygame !

Postby metulburr » Sun Jun 23, 2013 5:47 pm

lol, i got to about 17 thousand before i thought i was going to have a seizure

nice
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1473
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Star Dodger Pygame !

Postby ChristianCareaga » Sun Jun 23, 2013 5:52 pm

metulburr wrote:lol, i got to about 17 thousand before i thought i was going to have a seizure

nice


hahaha i feel the same after awhile i get overwhelmed haha
ChristianCareaga
 
Posts: 52
Joined: Sat Jun 22, 2013 9:54 am

Re: Star Dodger Pygame !

Postby XndrK » Fri Jul 19, 2013 2:31 am

Great! Noob question time: How do I open it? :oops:
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 172
Joined: Sat Jun 15, 2013 7:57 pm

Re: Star Dodger Pygame !

Postby ChristianCareaga » Sat Jul 20, 2013 5:42 am

XndrK wrote:Great! Noob question time: How do I open it? :oops:

hahah you need to extract the files then run the main py script!
ChristianCareaga
 
Posts: 52
Joined: Sat Jun 22, 2013 9:54 am

Re: Star Dodger Pygame !

Postby XndrK » Fri Jul 26, 2013 7:23 pm

ChristianCareaga wrote:
XndrK wrote:Great! Noob question time: How do I open it? :oops:

hahah you need to extract the files then run the main py script!


I did that. If this is Python 3 I'm in big trouble.
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 172
Joined: Sat Jun 15, 2013 7:57 pm

Re: Star Dodger Pygame !

Postby ChristianCareaga » Sun Jul 28, 2013 8:14 am

XndrK wrote:
ChristianCareaga wrote:
XndrK wrote:Great! Noob question time: How do I open it? :oops:

hahah you need to extract the files then run the main py script!


I did that. If this is Python 3 I'm in big trouble.


its 2.7 and windows
ChristianCareaga
 
Posts: 52
Joined: Sat Jun 22, 2013 9:54 am

Re: Star Dodger Pygame !

Postby XndrK » Mon Aug 12, 2013 12:20 am

Then something strange is going on...
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 172
Joined: Sat Jun 15, 2013 7:57 pm

Re: Star Dodger Pygame !

Postby XndrK » Mon Sep 02, 2013 7:47 pm

Figured it out. I don't have Pygame installed. Oops.
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 172
Joined: Sat Jun 15, 2013 7:57 pm

Re: Star Dodger Pygame !

Postby hansn » Sun Sep 08, 2013 8:46 pm

I gotta tell you, I've been coding for more than a year now and your code looks much better than mine. Keep it up!
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: Star Dodger Pygame !

Postby ChristianCareaga » Mon Sep 23, 2013 4:18 am

hansn wrote:I gotta tell you, I've been coding for more than a year now and your code looks much better than mine. Keep it up!

Wow! thanks so much! when i wrote this i had only been coding for 4 months! glad to get some good feedback for once Thank you!
ChristianCareaga
 
Posts: 52
Joined: Sat Jun 22, 2013 9:54 am


Return to Completed Scripts

Who is online

Users browsing this forum: No registered users and 1 guest