Author Topic: My physics game  (Read 22973 times)

0 Members and 1 Guest are viewing this topic.

Offline squidgetx

  • Food.
  • CoT Emeritus
  • LV10 31337 u53r (Next: 2000)
  • *
  • Posts: 1881
  • Rating: +503/-17
  • rawr.
    • View Profile
Re: My physics game
« Reply #45 on: February 03, 2011, 07:31:35 pm »
That's the beauty; you don't have to. Keeping track of the velocities by themselves like that is all you have to do :)

Offline ruler501

  • Meep
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2475
  • Rating: +66/-9
  • Crazy Programmer
    • View Profile
Re: My physics game
« Reply #46 on: February 03, 2011, 07:35:01 pm »
That definitely helps time for me to start writing. I should have the next part done by the end of tomorrow yet another day with no school. I have so much free time approximately 16 hours a day(I have to sleep)
I currently don't do much, but I am a developer for a game you should totally try out called AssaultCube Reloaded download here https://assaultcuber.codeplex.com/
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCM/CS/M/S d- s++: a---- C++ UL++ P+ L++ E---- W++ N o? K- w-- o? !M V?
PS+ PE+ Y+ PGP++ t 5? X R tv-- b+++ DI+ D+ G++ e- h! !r y

Offline squidgetx

  • Food.
  • CoT Emeritus
  • LV10 31337 u53r (Next: 2000)
  • *
  • Posts: 1881
  • Rating: +503/-17
  • rawr.
    • View Profile
Re: My physics game
« Reply #47 on: February 03, 2011, 07:39:30 pm »
Glad you understand it. Just make sure to initialize the x and y speeds correctly ;)

Offline ruler501

  • Meep
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2475
  • Rating: +66/-9
  • Crazy Programmer
    • View Profile
Re: My physics game
« Reply #48 on: February 03, 2011, 07:56:27 pm »
Right now I'm experimenting with different values for them and the starting angle
I currently don't do much, but I am a developer for a game you should totally try out called AssaultCube Reloaded download here https://assaultcuber.codeplex.com/
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCM/CS/M/S d- s++: a---- C++ UL++ P+ L++ E---- W++ N o? K- w-- o? !M V?
PS+ PE+ Y+ PGP++ t 5? X R tv-- b+++ DI+ D+ G++ e- h! !r y

Offline ruler501

  • Meep
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2475
  • Rating: +66/-9
  • Crazy Programmer
    • View Profile
Re: My physics game
« Reply #49 on: February 03, 2011, 10:08:50 pm »
Wouldn't the angle fired be decided by the arctangent of yvel/xvel. And won't this just make it go up forever and never turn around. At least this is whats happening with my code

EDIT: Sorry for the double post. and it also only does that when I don't count gravity. Is this not counting air resistance because that is fine for now I guess my post was completely unwarranted and pointless. sorry

EDIT2: Now I have a point to this why would this error po up when I try to display text using pygame
Code: [Select]
Traceback (most recent call last):
  File "C:\Python26\physics.py", line 293, in <module>
    main()
  File "C:\Python26\physics.py", line 260, in main
    play_game()
  File "C:\Python26\physics.py", line 212, in play_game
    for event in pygame.event.get():
error: video system not initialized

EDIT 3: Heres my code so you can check it I'm still working on Projectile so you can temporarily ignore it it does nothing currently
Code: [Select]
#import modules
import pygame, math, random, os
from pygame.locals import *

#Check to see if pygame is working right
#check font
if not pygame.font:
    print 'Warning, fonts disabled'
#check sound
if not pygame.mixer:
    print 'Warning, sound disabled'
   
#Create a function to load images for sprites.
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    #If an error exit
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

#create a function to load sound
def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    #if an error exit
    except pygame.error, message:
        print 'Cannot load sound:', fullname
        raise SystemExit, message
    return sound

class Projectile(pygame.sprite.Sprite):
    #moves a clenched fist on the screen, following the mouse
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = load_image('projectile.bmp')
        #define class variables
        self.area=screen.get_rect()
        self.downforce=0
        self.launch=0
        self.xvel=3.3282
        self.yvel=6.6564

    def update(self):
        #if shot and still on screen
        if self.launch==1:
            #apply gravity
            self.gravity()
            #move sprite to new loocation
            newpos=self.rect.move((xvel,self.downforce-yvel))
            self.rect=newpos
        #if not being shot make sure its off the screen
        else:
            self.rect.topleft= 1, self.area.bottom+15

    #start it being shot
    def shoot(self):
        #set it as being shot
        self.launch=1
        #start by the player
        self.rect.topleft=player.rect.right+8, player.rect.top
        #start with no gravity applied
        self.downforce=0
       

    def gravity(self):
        #if off of screen
        if self.rect.bottom>self.area.bottom+15:
            #no force from gravity
            self.downforce=0
            #not being shot anymore
            self.launch=0
        #if on screen increase gravities velocity downwards
        else:
            self.downforce+=1/15.0
           
    def turn(self):
        center = self.rect.center
        rotation = 5#yet to be determined official value
        rotate = pygame.transform.rotate
        self.image = rotate(self.original, rotation)
        self.rect = self.image.get_rect(center=center)

       

class Platform(pygame.sprite.Sprite):
    #moves a clenched fist on the screen, following the mouse
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = load_image('platform.bmp')
        self.area=screen.get_rect()
        self.downforce=0
        self.dead=1

    def update(self):
        #move the player based on direction chosen
        if self.dead==0:
            self.gravity()
            newpos=self.rect.move((0,self.downforce))
            self.rect=newpos

    def gravity(self):
        if self.rect.bottom>615:
            self.downforce=0
            self.dead=1
        else:
            self.downforce+=1/15.0
   
    def alive(self):
        self.dead=0
        initial=random.randint(0,750)
        self.rect.topleft=initial, 1
       


#classes for our game objects
class Player(pygame.sprite.Sprite):
    #moves a clenched fist on the screen, following the mouse
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = load_image('sprite.bmp')
        self.rect.topleft=1, 558
        self.direction=0
        self.downforce=0
        self.jump=0
        self.change=0

    def update(self):
        #move the player based on direction chosen
        self.gravity()
        if self.direction == 0:
            newpos = self.rect.move((0, self.downforce))
        elif self.direction == 1:
            if self.jump==0 or self.rect.bottom>=599:
                self.jump=1
                self.downforce-=3.0
            newpos = self.rect.move((0, self.downforce))
        elif self.direction == 3:
            if self.rect.left<=1:
                newpos = self.rect.move((0, self.downforce))
            else:
                newpos = self.rect.move((-4, self.downforce))
        elif self.direction == 4:
            if self.rect.right>=899:
                newpos = self.rect.move((0, self.downforce))
            else:
                newpos = self.rect.move((4, self.downforce))
        elif self.direction == 5:
            newpos = self.rect.move((-2, -2))
        elif self.direction == 6:
            newpos = self.rect.move((2, -2))
        self.rect = newpos

    def gravity(self):
        #need a collision detector here
        if self.rect.bottom>=599:
            self.downforce=0
            self.jump=0
            self.change=0
            self.rect.bottom=599
        else:
            self.downforce+=1/15.0

    def up(self):
        if self.jump==0:
            self.direction=1

    def left(self):
        self.direction=3

    def right(self):
        self.direction=4

    def still(self):
        self.direction=0

    def upleft(self):
        self.direction=5

    def upright(self):
        self.direction=6

    def death(self):
        if pygame.font:
            font = pygame.font.Font(None, 36)
            text = font.render("You have lost", 1, (10, 10, 10))
            textpos = text.get_rect(centerx=background.get_width()/2)
            screen.blit(background, (0, 0))
            pygame.display.flip()
            pygame.time.delay(1500)
            pygame.quit()
       

#function to load the game engine
def game_engine():
    rand=random.randint(1,250)
    if rand==20 and platforma.dead==1:
        platforma.alive()
    if rand==10 and platformb.dead==1:
        platformb.alive()
    if rand==30 and platformc.dead==1:
        platformc.alive()
    if rand==40 and platformd.dead==1:
        platformd.alive()
    if rand==75 and platforme.dead==1:
        platforme.alive()
    done = collide_check()
    return done

#function for playing the game
def play_game():
    done=False
    #Main Loop
    while done==False :
        clock.tick(25)

        #run the game engine
        game_engine()

        #Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                pygame.quit()
                return
            if event.type == MOUSEBUTTONDOWN:
                if projectilea.launch == 0:
                    projectilea.shoot()
                elif projectileb.launch == 0:
                    projectileb.shoot()
                elif projectilec.launch == 0:
                    projectilec.shoot()
            if event.type == KEYDOWN and event.key == K_UP and event.key == K_LEFT:
                player.upleft()
            elif event.type == KEYDOWN and event.key == K_UP and event.key == K_RIGHT:
                player.upright()
            elif event.type == KEYDOWN and event.key == K_UP:
                player.up()
            elif event.type == KEYDOWN and event.key == K_LEFT:
                player.left()
            elif event.type == KEYDOWN and event.key == K_RIGHT:
                player.right()
            else:
                player.still()

        allsprites.update()

    #Draw Everything
        screen.blit(background, (0, 0))
        allsprites.draw(screen)
        pygame.display.flip()

def collide_check():
    if player.rect.top==1+platforma.rect.bottom:
        if player.rect.left>=platforma.rect.left and player.rect.right<=platforma.rect.right:
            player.death()
    elif player.rect.top==1+platformb.rect.bottom:
        if player.rect.left>=platformb.rect.left and player.rect.right<=platformb.rect.right:
            player.death()
    elif player.rect.top==1+platformc.rect.bottom:
        if player.rect.left>=platformc.rect.left and player.rect.right<=platformc.rect.right:
            player.death()
    elif player.rect.top==1+platformd.rect.bottom:
        if player.rect.left>=platformd.rect.left and player.rect.right<=platformd.rect.right:
            player.death()
    elif player.rect.top==1+platforme.rect.bottom:
        if player.rect.left>=platforme.rect.left and player.rect.right<=platforme.rect.right:
            player.death()

def main():
    #define needed local variables here
   
    #start game
    play_game()

#Initialize Everything
pygame.init()
screen = pygame.display.set_mode((900, 600))
pygame.display.set_caption('Physics!')
pygame.mouse.set_visible(1)
turn = 0
win = False
lose = False
achievements = 0

    #Create The Backgound
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))

    #Display The Background
screen.blit(background, (0, 0))
pygame.display.flip()

    #Prepare Game Objects
clock = pygame.time.Clock()
player = Player()
platforma = Platform()
platformb = Platform()
platformc = Platform()
platformd = Platform()
platforme = Platform()
projectilea = Projectile()
projectileb = Projectile()
projectilec = Projectile()
playersprites = (player,projectilea, projectileb, projectilec)
objectsprites = (platforma, platformb, platformc, platformd, platforme)
allsprites = pygame.sprite.RenderPlain(playersprites, objectsprites)

   
if __name__ == '__main__':
    main()
Not that its relative now but I just wanted to say the cos(30) and sin(30) really don't do much It looks much the same if you just put in your own values

EDIT 4: I reset the code up there to what I currently have and here is the video please help me with problems and optimization. It is a little choppier in the video than real life.
http://s1202.photobucket.com/albums/bb364/ruler501/?action=view&current=Test.mp4
« Last Edit: February 04, 2011, 12:21:11 am by ruler501 »
I currently don't do much, but I am a developer for a game you should totally try out called AssaultCube Reloaded download here https://assaultcuber.codeplex.com/
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCM/CS/M/S d- s++: a---- C++ UL++ P+ L++ E---- W++ N o? K- w-- o? !M V?
PS+ PE+ Y+ PGP++ t 5? X R tv-- b+++ DI+ D+ G++ e- h! !r y

Offline ruler501

  • Meep
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2475
  • Rating: +66/-9
  • Crazy Programmer
    • View Profile
Re: My physics game
« Reply #50 on: February 04, 2011, 05:23:35 pm »
I am trying to launch a projectile up using the mouse position for magnitude and direction. I am a very glitchy results. could someone please look and tell me what I've done wrong. Here is a video of the strange results http://s1202.photobucket.com/albums/bb364/ruler501/?action=view&current=Test2.mp4
Here is the entire program I highlighted the area that should get the angle and velocity.
Code: [Select]
#import modules
import pygame, math, random, os
from pygame.locals import *

#Check to see if pygame is working right
#check font
if not pygame.font:
    print 'Warning, fonts disabled'
#check sound
if not pygame.mixer:
    print 'Warning, sound disabled'
   
#Create a function to load images for sprites.
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    #If an error exit
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

#create a function to load sound
def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    #if an error exit
    except pygame.error, message:
        print 'Cannot load sound:', fullname
        raise SystemExit, message
    return sound

class Projectile(pygame.sprite.Sprite):
    #moves a clenched fist on the screen, following the mouse
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = load_image('projectile.bmp')
        #define class variables
        self.area=screen.get_rect()
        self.downforce=0
        self.launch=0
        self.xvel=0
        self.yvel=0

    def update(self):
        #if shot and still on screen
        if self.launch==1:
            #apply gravity
            self.gravity()
            #move sprite to new loocation
            newpos=self.rect.move((self.xvel,self.downforce-self.yvel))
            self.rect=newpos
        #if not being shot make sure its off the screen
        else:
            self.rect.topleft= 1, self.area.bottom+15

[color=red]    #start it being shot
    def shoot(self):
        #set it as being shot
        self.launch=1
        #start by the player
        self.rect.topleft=player.rect.right+8, player.rect.top
        #figure out how fast to go
        magnitude=pygame.mouse.get_pos()
        vel=math.floor(math.hypot(magnitude[0]-player.rect.right, magnitude[1]-player.rect.top)/25)
   #     print vel
        angle=math.atan2(magnitude[0]-player.rect.right, player.rect.top-magnitude[1])
        print math.degrees(angle)
        angleb=math.atan2(player.rect.right-magnitude[0], player.rect.top-magnitude[1])
        print math.degrees(angleb)
        self.xvel=math.cos(angle)*vel
        self.yvel=math.sin(angle)*vel
        #start with no gravity applied
        self.downforce=0[/color]
       
       

    def gravity(self):
        #if off of screen
        if self.rect.bottom>self.area.bottom+15:
            #no force from gravity
            self.downforce=0
            #not being shot anymore
            self.launch=0
        #if on screen increase gravities velocity downwards
        elif self.launch == 1:
            self.downforce+=1/15.0
           
    def turn(self):
        center = self.rect.center
        rotation = 5#yet to be determined official value
        rotate = pygame.transform.rotate
        self.image = rotate(self.original, rotation)
        self.rect = self.image.get_rect(center=center)

       

class Platform(pygame.sprite.Sprite):
    #moves a clenched fist on the screen, following the mouse
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = load_image('platform.bmp')
        self.area=screen.get_rect()
        self.downforce=0
        self.dead=1

    def update(self):
        #move the player based on direction chosen
        if self.dead==0:
            self.gravity()
            newpos=self.rect.move((0,self.downforce))
            self.rect=newpos

    def gravity(self):
        if self.rect.bottom>self.area.bottom+15:
            self.downforce=0
            self.dead=1
        else:
            self.downforce+=1/15.0
   
    def alive(self):
        self.dead=0
        initial=random.randint(0,750)
        self.rect.topleft=initial, 1

    def death(self):
        self.dead=1
        self.rect.topleft = 1, self.area.bottom+16
       


#classes for our game objects
class Player(pygame.sprite.Sprite):
    #moves a clenched fist on the screen, following the mouse
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = load_image('sprite.bmp')
        self.rect.topleft=1, 558
        self.alive=1
        self.direction=0
        self.downforce=0
        self.jump=0
        self.change=0

    def update(self):
        #move the player based on direction chosen
        self.gravity()
        if self.direction == 0:
            newpos = self.rect.move((0, self.downforce))
        elif self.direction == 1:
            if self.jump==0 or self.rect.bottom>=599:
                self.jump=1
                self.downforce-=3.0
            newpos = self.rect.move((0, self.downforce))
        elif self.direction == 3:
            if self.rect.left<=1:
                newpos = self.rect.move((0, self.downforce))
            else:
                newpos = self.rect.move((-4, self.downforce))
        elif self.direction == 4:
            if self.rect.right>=899:
                newpos = self.rect.move((0, self.downforce))
            else:
                newpos = self.rect.move((4, self.downforce))
        elif self.direction == 5:
            newpos = self.rect.move((-2, -2))
        elif self.direction == 6:
            newpos = self.rect.move((2, -2))
        self.rect = newpos

    def gravity(self):
        #need a collision detector here
        if self.rect.bottom>=599:
            self.downforce=0
            self.jump=0
            self.change=0
            self.rect.bottom=599
        else:
            self.downforce+=1/15.0

    def up(self):
        if self.jump==0:
            self.direction=1

    def left(self):
        self.direction=3

    def right(self):
        self.direction=4

    def still(self):
        self.direction=0

    def upleft(self):
        self.direction=5

    def upright(self):
        self.direction=6

    def death(self):
        font = pygame.font.Font(None, 36)
        text = font.render("You have died", 1, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width()/2)
        background.blit(text, textpos)
        screen.blit(background, (0, 0))
        pygame.display.flip()
        pygame.time.delay(1000)
        self.alive=0
        pygame.quit()
       

#function to load the game engine
def game_engine():
    rand=random.randint(1,250)
    if rand==20 and platforma.dead==1:
        platforma.alive()
    if rand==10 and platformb.dead==1:
        platformb.alive()
    if rand==30 and platformc.dead==1:
        platformc.alive()
    if rand==40 and platformd.dead==1:
        platformd.alive()
    if rand==75 and platforme.dead==1:
        platforme.alive()
    done = collide_check()
    return done

#function for playing the game
def play_game():
    #Main Loop
    while player.alive==1 :
        clock.tick(25)

        #run the game engine
        game_engine()

        #Handle Input Events
        if player.alive==0:
            break
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                pygame.quit()
                return
            if event.type == MOUSEBUTTONDOWN:
                if projectilea.launch == 0:
                    projectilea.shoot()
                elif projectileb.launch == 0:
                    projectileb.shoot()
                elif projectilec.launch == 0:
                    projectilec.shoot()
            if event.type == KEYDOWN and event.key == K_UP and event.key == K_LEFT:
                player.upleft()
            elif event.type == KEYDOWN and event.key == K_UP and event.key == K_RIGHT:
                player.upright()
            elif event.type == KEYDOWN and event.key == K_UP:
                player.up()
            elif event.type == KEYDOWN and event.key == K_LEFT:
                player.left()
            elif event.type == KEYDOWN and event.key == K_RIGHT:
                player.right()
            else:
                player.still()

        allsprites.update()

    #Draw Everything
        screen.blit(background, (0, 0))
        allsprites.draw(screen)
        pygame.display.flip()

def collide_check():
    if player.rect.colliderect(platforma):
        if player.rect.bottom>=platforma.rect.bottom:
            player.death()
    if player.rect.colliderect(platformb):
        if player.rect.bottom>=platformb.rect.bottom:
            player.death()
    if player.rect.colliderect(platformc):
        if player.rect.bottom>=platformc.rect.bottom:
            player.death()
    if player.rect.colliderect(platformd):
        if player.rect.bottom>=platformd.rect.bottom:
            player.death()
    if player.rect.colliderect(platforme):
        if player.rect.bottom>=platforme.rect.bottom:
            player.death()
    if projectilea.rect.colliderect(platforma)or \
    projectileb.rect.colliderect(platforma)or \
    projectilec.rect.colliderect(platforma):
        platforma.death()
    if projectilea.rect.colliderect(platformb)or \
    projectileb.rect.colliderect(platformb)or \
    projectilec.rect.colliderect(platformb):
        platformb.death()
    if projectilea.rect.colliderect(platformc)or \
    projectileb.rect.colliderect(platformc)or \
    projectilec.rect.colliderect(platformc):
        platformc.death()
    if projectilea.rect.colliderect(platformd)or \
    projectileb.rect.colliderect(platformd)or \
    projectilec.rect.colliderect(platformd):
        platformd.death()
    if projectilea.rect.colliderect(platformd)or \
    projectileb.rect.colliderect(platformd)or \
    projectilec.rect.colliderect(platformd):
        platformd.death()

def main():
    #define needed local variables here
   
    #start game
    play_game()

#Initialize Everything
pygame.init()
screen = pygame.display.set_mode((900, 600))
pygame.display.set_caption('Physics!')
pygame.mouse.set_visible(1)
turn = 0
win = False
lose = False
achievements = 0

    #Create The Backgound
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))

    #Display The Background
screen.blit(background, (0, 0))
pygame.display.flip()

    #Prepare Game Objects
clock = pygame.time.Clock()
player = Player()
platforma = Platform()
platformb = Platform()
platformc = Platform()
platformd = Platform()
platforme = Platform()
projectilea = Projectile()
projectileb = Projectile()
projectilec = Projectile()
playersprites = (player,projectilea, projectileb, projectilec)
objectsprites = (platforma, platformb, platformc, platformd, platforme)
allsprites = pygame.sprite.RenderPlain(playersprites, objectsprites)

   
if __name__ == '__main__':
    main()
I currently don't do much, but I am a developer for a game you should totally try out called AssaultCube Reloaded download here https://assaultcuber.codeplex.com/
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCM/CS/M/S d- s++: a---- C++ UL++ P+ L++ E---- W++ N o? K- w-- o? !M V?
PS+ PE+ Y+ PGP++ t 5? X R tv-- b+++ DI+ D+ G++ e- h! !r y