PYHTON İLE OYUN

2 tane angry bird bulunmaktadır.

1. kırmızı olan oyuncudur. Bunu Player olarak adlandırdım.

2. yeşil olan ise hedeftir. Bunu Other olarak adlandırdım.

pygame ile atan2, degrees, pi matematiksel fonksiyonlarını yüklendi.

ilk değerler ayarlandı ve gerekli dosyalar yüklendi.

showCharacter fonksiyonu görüntüyü oluşturmak ve puanlama gibi oyun değerlerini atamak için kullanıldı.

other angry bird belirtilen oyun pencere boyutunun dışına çıkmaması için ayarlama yapılmaktadır.

her bir vuruş zamanına kadar other angry bird sabit hızla x ekseninde gidip gelmektedir.

çarpışma olduğunda saniye olarak geçen zaman sıfırlanmaktadır.

puan hesabında rastgele verilen hızdan her bir dakka için 1 puan çıkarılarak hesaplanmaktadır.

anlık puan angry bird üzerinde gösterilmektedir.

toplam puan ise sol üste gösterilmektedir.

collision olduğunda iki cismin iç içe girmesi engellenmiş olup bunu görsel olarak görebilirsiniz.

 

isCollision fonksiyonu player ve other arasında bir çarpışma varsa bu iki cismin iç içe girmesini engellemesi sağlayıp True değer döndürür.

 

getDegree fonksiyonu iki cisim arasındaki koordinat değerlerini kullanarak dereceye çevirmeyi sağlamaktadır.

 

momentum fonksiyonu çarpışan iki cismin ilk hızları ile aralarındaki açı bilgisini alarak momentum hesabından son hızlarını geri döndürür.

 

angryBird fonksiyonu mouse veya oyun konsoluyla atışı başlattığında çalışır.

burada çarpışma olursa momentum hesabıyla yeni hızlar bulunur ve bu yeni hızlarla yeniden cisimlerin davranışı düzenlenir.

hesaplama iki cisim için anlık hesaplanmaktadır bundan dolayı etkileşim daha hızlı olmaktadır.

 

Oyunun Oynanması:

  Mouse ile oynanması:

      mouse ile tıklanır ve belli bir uzaklığa kadar çekilip bırakılır.

      kırmızı çizginin x ve y doğrultusundaki uzaklık angry bird player cisminin ilk hızını oluşturmaktadır.

      bu ilk hızla fizik kurallarıyla hareket etmektedir.

      eğer çarpışma gerçekleşirse puan kazanılacaktır.

      her 1 dakka geçikmede 1 puan kaybedilmektedir.

  Oyun konsoluyla oynama:

      sağdaki gideceği ilk konumu soldaki ise mevcut konumunu ayarlamaya yaramaktadır.

      sonrasında kenardaki butonlar ile atış yapılmaktadır [get_button(4), get_button(5)].

      çıkmak için de üsteki menüler kullanılabilir [get_button(8), get_button(9)].


2 tane angry bird bulunmaktadır.
1. kırmızı olan oyuncudur. Bunu Player olarak adlandırdım.
2. yeşil olan ise hedeftir. Bunu Other olarak adlandırdım.
pygame ile atan2, degrees, pi matematiksel fonksiyonlarını yüklendi.
ilk değerler ayarlandı ve gerekli dosyalar yüklendi.

showCharacter fonksiyonu görüntüyü oluşturmak ve puanlama gibi oyun değerlerini atamak için kullanıldı.
other angry bird belirtilen oyun pencere boyutunun dışına çıkmaması için ayarlama yapılmaktadır.
her bir vuruş zamanına kadar other angry bird sabit hızla x ekseninde gidip gelmektedir.
çarpışma olduğunda saniye olarak geçen zaman sıfırlanmaktadır.
puan hesabında rastgele verilen hızdan her bir dakka için 1 puan çıkarılarak hesaplanmaktadır.
anlık puan angry bird üzerinde gösterilmektedir.
toplam puan ise sol üste gösterilmektedir.
collision olduğunda iki cismin iç içe girmesi engellenmiş olup bunu görsel olarak görebilirsiniz.

isCollision fonksiyonu player ve other arasında bir çarpışma varsa bu iki cismin iç içe girmesini engellemesi sağlayıp True değer döndürür.

getDegree fonksiyonu iki cisim arasındaki koordinat değerlerini kullanarak dereceye çevirmeyi sağlamaktadır.

momentum fonksiyonu çarpışan iki cismin ilk hızları ile aralarındaki açı bilgisini alarak momentum hesabından son hızlarını geri döndürür.

angryBird fonksiyonu mouse veya oyun konsoluyla atışı başlattığında çalışır.
burada çarpışma olursa momentum hesabıyla yeni hızlar bulunur ve bu yeni hızlarla yeniden cisimlerin davranışı düzenlenir.
hesaplama iki cisim için anlık hesaplanmaktadır bundan dolayı etkileşim daha hızlı olmaktadır.

Oyunun Oynanması:
  Mouse ile oynanması:
      mouse ile tıklanır ve belli bir uzaklığa kadar çekilip bırakılır.
      kırmızı çizginin x ve y doğrultusundaki uzaklık angry bird player cisminin ilk hızını oluşturmaktadır.
      bu ilk hızla fizik kurallarıyla hareket etmektedir.
      eğer çarpışma gerçekleşirse puan kazanılacaktır.
      her 1 dakka geçikmede 1 puan kaybedilmektedir.
  Oyun konsoluyla oynama:
      sağdaki gideceği ilk konumu soldaki ise mevcut konumunu ayarlamaya yaramaktadır.
      sonrasında kenardaki butonlar ile atış yapılmaktadır [get_button(4), get_button(5)].
      çıkmak için de üsteki menüler kullanılabilir [get_button(8), get_button(9)].

"""
from pylab import *
from math import atan2, degrees, pi
import pygame



# Define the colors we will use in RGB format
BLACK = (  0,  0,    0)
WHITE = (255, 255, 255)
BLUE = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED =   (255,   0,   0)
MYCOLOR = (0, 0, 0)

random_int = randint(1,5)

# Call this function so the Pygame library can initialize itself
pygame.init()
# This sets the name of the window
pygame.display.set_caption('BCO611 Final Exam')
clock = pygame.time.Clock()
# Before the loop, load the sounds:
#player_colision_sound = pygame.mixer.music.load('fire.ogg')
#player_start_sound = pygame.mixer.music.load('voyyy.ogg')
# Set positions of graphics
background_position = [0, 0]
# Load and set up graphics.
background_image = pygame.image.load("background.png")

# Create an load image sized screen
screen = pygame.display.set_mode(background_image.get_rect().size)
background_image = background_image.convert()
#screen = pygame.display.set_mode([1280, 800])
[screen_size, screen_size] = background_image.get_rect().size
background_image_ground = 600
player_image_left = pygame.image.load("red_sprite_small_left.png")
player_image_right = pygame.image.load("red_sprite_small_right.png")
selected_player_image = player_image_right
selected_player_image = selected_player_image.convert()

player_image_width, player_image_height = selected_player_image.get_rect().size

other_image = pygame.image.load("rock_small.png")
other_image = other_image.convert()
other_image_width, other_image_height = selected_player_image.get_rect().size

# value for collision and physics
mass = 0.3 
mass2 = 0.5             # mass of the ball in kg
gravity = 9.81          # gravitational acceleration in m/sˆ2
v0 = [550,550]          # Initial velocity in m/s

#y0 = 0                 # Initial position in meters
alpha = 60              # Initial angle in degrees
diameter = 0.02         # diameter of the ball in meters
airdensity = 1.225      # air density in kg/m^3
stiffnes = 1000.0       # stiffnes of the spring N/m
time = 30.0             # simulation time
dt = 0.03               # time step

# value to play game
done = False
simulation = False
player_score = 0
player_now_score = 0
player_timer = 0
# Current position
player_coord_x = 10
player_coord_y = 10
player_r = (player_image_width+player_image_height)/4
# Current position
other_coord_x = 500
other_coord_y = screen_size - 150
other_r = (other_image_width+other_image_height)/4

# Current position
player_line_coord_x = 50
player_line_coord_y = 50
collision_show_time = 0

v0_dist = math.hypot(player_coord_x-player_line_coord_x, player_coord_y-player_line_coord_y)
# Count the joysticks the computer has
joystick_count = pygame.joystick.get_count()

   
def showCharacter(is_simulation, is_collision):
    global player_colision_sound, background_image, background_position, collision_show_time, random_int, player_timer, player_score, player_now_score, player_image_left, player_image_right, player_coord_x, player_coord_y, other_coord_x, other_coord_y, player_r, other_r, player_line_coord_x, player_line_coord_y 
    # Erase game screen with backround image
    screen.blit(background_image, background_position)
    # To prevent the emergence out of the window
    if other_coord_x > screen_size + 500:
        other_coord_x = screen_size + 500
        random_int = -random_int
    elif other_coord_x < 0:
        other_coord_x = 0
        random_int = -random_int        
            
    # for better game
    if player_coord_x > player_line_coord_x:
        selected_player_image = player_image_left
    else:
        selected_player_image = player_image_right
    # when collision show red circle in collision time
    if(collision_show_time > 0):
       collision_show_time = collision_show_time - 1
       pygame.draw.ellipse(screen, RED, [other_coord_x - other_r, other_coord_y - other_r, other_r + 50, other_r + 50], 20) 
                  
    if is_simulation:
        # COLLISION
        if is_collision:
            if(random_int < 0):
                player_now_score = -random_int - int (player_timer / 3600)
            else:
                player_now_score = random_int - int (player_timer / 3600)
            player_score = player_score + player_now_score
            if(player_score < 0):
                player_now_score = 0
                player_score= 0
                
            random_int = randint(1,5)
            player_timer = 0
            collision_show_time = 20
            sys.stdout.write(" >>> Score Now: %d  Score: %d >> \n\r\n\r" % (player_now_score, player_score) )
        pygame.draw.line(screen, GREEN, [player_coord_x, player_coord_y ], [other_coord_x, other_coord_y ], 5) 

    else:  
        if isCollision(player_coord_x,other_coord_x,player_coord_y,other_coord_y,player_r,other_r):
            collision_show_time = 20 
        pygame.draw.line(screen, RED, [player_coord_x, player_coord_y ], [player_line_coord_x+10, player_line_coord_y+10], 7)
        pygame.draw.line(screen, WHITE, [player_coord_x, player_coord_y ], [player_line_coord_x+10, player_line_coord_y+10], 3)    
        pygame.draw.rect(screen, RED, [player_line_coord_x, player_line_coord_y, 20, 20]) 

    # set time for game  
    player_timer = player_timer + 1
    screen.blit(selected_player_image, [player_coord_x - player_r, player_coord_y - player_r])
    # OTHER IMAGE Copy image to screen :
    screen.blit(other_image, [other_coord_x-other_r, other_coord_y - other_r])
    other_coord_x = other_coord_x + random_int
    # Show score for player
    font=pygame.font.Font(None,50)
    scoretext=font.render(str(player_now_score), 50,GREEN)
    screen.blit(scoretext, (player_coord_x, player_coord_y-50))
    font=pygame.font.Font(None,50)
    scoretext=font.render("Score: "+str(player_score), 50,WHITE)
    screen.blit(scoretext, (25, 25))
    timertext=font.render(str(int(player_timer / 60))+" sn", 1, RED)
    screen.blit(timertext, (player_coord_x+50, player_coord_y-50))
    
    return True
  
def isCollision(x1,x2,y1,y2,r1,r2):
    global player_coord_x, player_coord_y 
    result = False
    #dist = math.hypot(x2 - x1, y2 - y1)
    dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
    rr = r1+r2
    #sys.stdout.write(" <<<<<Collision  dist: %d  R: %d x1: %d x2: %d y1: %d y2: %d >> \n\r\n\r" % (dist,rr,x1,x2,y1,y2) )
   
   # Collision
    if dist <= rr:
        pygame.mixer.music.load('fire.ogg')
        pygame.mixer.music.play()
        dx = x2 - x1
        dy = y2 - y1 
        if(dx <= 0):
            player_coord_x = player_coord_x + dx + rr
        else:            
            player_coord_x = player_coord_x + dx - rr
        if(dy <= 0):
            player_coord_y = player_coord_y + dy + rr
        else:            
            player_coord_y = player_coord_y + dy - rr
        result = True
        #sys.stdout.write(" >>>>>> >>  dist: %d  R: %d x1: %d x2: %d y1: %d y2: %d >> \n\r\n\r" % (dist,rr,x1,x2,y1,y2) )
        #sys.stdout.write(" Collision >> dist: %d x1: %d x2: %d y1: %d y2: %d >> \n\r\n\r" % (dist,x1,x2,y1,y2) )
    return result
    
      #calculate degre use x and y coordinat
def getDegree(x1,x2,y1,y2):
    dx = x2 - x1 
    dy = y2 - y1 
    rads = atan2(-dy,dx)
    rads %= 2*pi
    alpha = degrees(rads)
    return alpha

  
def momentum(m1,m2,theta,v1,v2):
    e = 0.9 # the coefficient of restitution 
    v1pre = matrix([[v1[0]],
                    [v1[1]]])
    v2pre = matrix([[v2[0]],
                    [v2[1]]])
    R1 = matrix([[cos(theta), sin(theta)],
                 [-sin(theta), cos(theta)]])
    
    R2 = matrix([[cos(theta), -sin(theta)],
                 [sin(theta), cos(theta)]])
    
    v1p, v1n = R1*v1pre
    v2p, v2n = R1*v2pre
                       
    # Compute the post-collision velocities for the two spheres
    v1pt, v2pt = multiply((1.0/(m1+m2)), matrix([[(m1-e*m2), m2*(1+e)],[m1*(1+e), (m2-e*m1)]])*vstack((v1p, v2p)))
    # The final step in the process is to rotate the post-collision velocities
    # back to the standard Cartesian coordinate system
    v1post = R2*vstack((v1pt, v1n))
    v2post = R2*vstack((v2pt, v2n))
    
    #plot(v1post)
    #xlabel('x [v1]'), ylabel('y [v1]')
    #axis('equal'), show()
    
    #plot(v2post)
    #xlabel('x [v2]'), ylabel('y [v2]')
    #axis('equal'), show()
    
    #sys.stdout.write(" Momentum Before >>>> v1_x:%d v1_y:%d v2_x:%d v2_y:%d >> \n\r\n\r" % (v1pre[0],v1pre[1],v2pre[0],v2pre[1]) )
    #sys.stdout.write(" Momentum After >>>> v1_x:%d v1_y:%d v2_x:%d v2_y:%d >> \n\r\n\r" % (v1post[0],v1post[1],v2post[0],v2post[1]) )
    return v1post, v2post

def angryBird():
    global collision_show_time, mass, mass2, gravity, v0, alpha, time, dt, random_int, player_coord_x, player_coord_y, other_coord_x, other_coord_y, player_r, other_r, player_line_coord_x, player_line_coord_y 
    
    """ finds the trajectory of the redstripe with given initial values.
    
    Args:
        m     : mass of the redstripe in kg
        g     : gravity in m/s^2
        v0    : initial release velocity of the redstripe in m/s
        y0    : initial release height of the redstripe in meters
        alpha : initial release angle of the redstripe in degrees
        diam  : diameter of the redstripe in meters
        rho   : air density in kg/m^3
        k     : stiffnes of the spring N/m
        time  : simulation time
        dt    : time step.
    Returns:
        t     : time in seconds
        r     : position in meters
        v     : velocity in m/s
    Raises:
        TypeError: if n is not a number
        ValueError: if n is negative
    """
    
    v0_other = [random_int*100,0]       
    done = False 
    while not done:
        done = True
        m = mass
        m_other = mass2
        g = gravity
        diam = diameter
        rho = airdensity
        k = stiffnes
        
        alpha = radians(alpha)     # Initial angle in radian
        D = 3.0*rho*diam**2     # drag coefficient
        R = (diam/2)            # ball contact starts - equilibrium length of Spring
        # Numerical initialization
        n = int(ceil(time/dt))
        a = zeros((n, 2), float)
        a_other = zeros((n, 2), float)
        v = zeros((n, 2), float)
        v_other = zeros((n, 2), float)
        r = zeros((n, 2), float)
        r_other = zeros((n, 2), float)
        t = zeros((n, 2), float)
        # Set initial values
        r[0,1] = player_coord_y                             # initial position of the ball
        r_other[0,1] = 0 
        #v[0,:] = v0*cos(alpha), v0*sin(alpha)   # initial velocity in i, j
        v[0,:] = -v0[0], v0[1]   # initial velocity in i, j
        v_other[0,:] = -v0_other[0], v0_other[1]
    
    
        start_player_coord_x = player_coord_x
        start_other_coord_x = other_coord_x 
        # Integration loop
        for i in range(n-1):
            if (r[i,1] < R):
                N = k*(R-r[i,1])*array([0,1])
            else:
                N = array([0,0])
            FD = - D*norm(v[i,:])*v[i,:]
            G = -m*g*array([0,1])
            Fnet = N + FD + G
            a = Fnet/m
            v[i+1,:] = v[i] + a*dt
            r[i+1,:] = r[i] + v[i+1]*dt
            t[i+1] = t[i] + dt
            
            #OTHER 
            if (r_other[i,1] < R):
                N = k*(R-r_other[i,1])*array([0,1])
            else:
                N = array([0,0])
            FD = - D*norm(v_other[i,:])*v_other[i,:]
            G = -m_other*g*array([0,1])
            Fnet = N + FD + G
            a_other = Fnet/m_other
            v_other[i+1,:] = v_other[i] + a_other*dt
            r_other[i+1,:] = r_other[i] + v_other[i+1]*dt
            t[i+1] = t[i] + dt
            
            #Result
            player_coord_x = start_player_coord_x + r[i+1, 0]
            player_coord_y = background_image_ground - r[i+1, 1]
            other_coord_y = background_image_ground - r_other[i+1, 1]
            if(collision_show_time > 0):
               other_coord_x = start_other_coord_x + r_other[i+1, 0]
             # COLLISION
            if isCollision(player_coord_x, other_coord_x, player_coord_y, other_coord_y, player_r, other_r):
               alpha = getDegree(player_coord_x, other_coord_x, player_coord_y, other_coord_y)
               v0, v0_other = momentum(mass, mass2,alpha,v[i,:],v_other[i,:])
               showCharacter(True, True) 
               done = False
               break
            else:
               showCharacter(True, False)   
                    
            pygame.display.flip()
            
    return t, r, v

    

if joystick_count == 0:
    # No joysticks!
    print("Error, I didn't find any joysticks.")
else:
    # Use joystick #0 and initialize it
    my_joystick = pygame.joystick.Joystick(0)
    my_joystick.init()

while not done:
      
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
             player_position = pygame.mouse.get_pos()
             player_line_coord_x = player_position[0] - player_image_width/2
             player_line_coord_y = player_position[1] - player_image_height/2     
        elif event.type == pygame.MOUSEBUTTONUP:
            simulation = True
        elif event.type == pygame.MOUSEMOTION:
             pygame.mouse.set_visible(True)
             player_position = pygame.mouse.get_pos()
             player_coord_x = player_position[0] - player_image_width/2
             player_coord_y = player_position[1] - player_image_height/2       
    # Copy image to screen:
    screen.blit(background_image, background_position)
    # Get the current mouse position. This returns the position
    # as a list of two numbers.
    if not simulation:
        if joystick_count != 0:
            # Hide the mouse cursor
            pygame.mouse.set_visible(False)
            # This gets the position of the axis on the game controller
            # It returns a number between -1.0 and +1.0
            horiz_axis_pos = my_joystick.get_axis(0)
            vert_axis_pos = my_joystick.get_axis(1)
            player_coord_x += int(horiz_axis_pos * 5)
            player_coord_y += int(vert_axis_pos * 5)
            
            if my_joystick.get_button(0) == 1: 
                player_line_coord_y -= 5
            elif my_joystick.get_button(1) == 1:
                player_line_coord_x += 5
            elif my_joystick.get_button(2) == 1: 
                player_line_coord_y += 5
            elif my_joystick.get_button(3) == 1: 
                player_line_coord_x -= 5
            elif my_joystick.get_button(4) == 1: 
                simulation = True
            elif my_joystick.get_button(5) == 1: 
                simulation = True 
            elif my_joystick.get_button(8) == 1:   
                done = True 
            elif my_joystick.get_button(9) == 1:   
                done = True
        other_coord_y = screen_size - 150
        showCharacter(False, False)
    else:
        pygame.mixer.music.load('voyyy.ogg')
        pygame.mixer.music.play()
        pygame.mouse.set_visible(False)
        #v0 = math.hypot(player_coord_x-player_line_coord_x, player_coord_y-player_line_coord_y)  
        v0 = [player_coord_x - player_line_coord_x, player_coord_y - player_line_coord_y]   
        alpha = getDegree(player_coord_x, player_line_coord_x, player_coord_y, player_line_coord_y)
        t, r, v = angryBird() 
        pygame.mouse.set_pos(player_coord_x , player_coord_y)
        simulation = False
    
    pygame.display.flip()
    clock.tick(120)
    
pygame.quit ()

kodu buradan indirebilirsiniz.

barcode
Destek İçin Buradaki Reklamları Tıklayabilirsiniz.
Destek İçin Buradaki Reklamları Tıklayabilirsiniz.

Ses Kontrolleri

Tam Ekran Yap