-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjuego.py
183 lines (149 loc) · 5.57 KB
/
juego.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------
# Importacion de los módulos
# ---------------------------
import pygame
from pygame.locals import *
import os
import sys
# -----------
# Constantes
# -----------
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
IMG_DIR = "imagenes"
SONIDO_DIR = "sonidos"
# ------------------------------
# Clases y Funciones utilizadas
# ------------------------------
def load_image(nombre, dir_imagen, alpha=False):
# Encontramos la ruta completa de la imagen
ruta = os.path.join(dir_imagen, nombre)
try:
image = pygame.image.load(ruta)
except:
print("Error, no se puede cargar la imagen: " + ruta)
sys.exit(1)
# Comprobar si la imagen tiene "canal alpha" (como los png)
if alpha is True:
image = image.convert_alpha()
else:
image = image.convert()
return image
def load_sound(nombre, dir_sonido):
ruta = os.path.join(dir_sonido, nombre)
# Intentar cargar el sonido
try:
sonido = pygame.mixer.Sound(ruta)
except (pygame.error) as message:
print("No se pudo cargar el sonido:" + ruta)
sonido = None
return sonido
# -----------------------------------------------
# Creamos los sprites (clases) de los objetos del juego:
class Pelota(pygame.sprite.Sprite):
"La bola y su comportamiento en la pantalla"
def __init__(self, sonido_golpe, sonido_punto):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bola.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = SCREEN_WIDTH / 2
self.rect.centery = SCREEN_HEIGHT / 2
self.speed = [3, 3]
self.sonido_golpe = sonido_golpe
self.sonido_punto = sonido_punto
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -self.speed[0]
self.sonido_punto.play() # Reproducir sonido de punto
self.rect.centerx = SCREEN_WIDTH / 2
self.rect.centery = SCREEN_HEIGHT / 2
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -self.speed[1]
self.rect.move_ip((self.speed[0], self.speed[1]))
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect):
self.speed[0] = -self.speed[0]
self.sonido_golpe.play() # Reproducir sonido de rebote
class Paleta(pygame.sprite.Sprite):
"Define el comportamiento de las paletas de ambos jugadores"
def __init__(self, x):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("paleta.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = SCREEN_HEIGHT / 2
def humano(self):
# Controlar que la paleta no salga de la pantalla
if self.rect.bottom >= SCREEN_HEIGHT:
self.rect.bottom = SCREEN_HEIGHT
elif self.rect.top <= 0:
self.rect.top = 0
def cpu(self, pelota):
self.speed = [0, 2.5]
if pelota.speed[0] >= 0 and pelota.rect.centerx >= SCREEN_WIDTH / 2:
if self.rect.centery > pelota.rect.centery:
self.rect.centery -= self.speed[1]
if self.rect.centery < pelota.rect.centery:
self.rect.centery += self.speed[1]
# ------------------------------
# Funcion principal del juego
# ------------------------------
def main():
pygame.init()
pygame.mixer.init()
# creamos la ventana y le indicamos un titulo:
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Ping Pong - Braysen - Primer Juego")
# cargamos los objetos
fondo = load_image("fondo.jpg", IMG_DIR, alpha=False)
sonido_golpe = load_sound("tennis.ogg", SONIDO_DIR)
sonido_punto = load_sound("aplausos.ogg", SONIDO_DIR)
bola = Pelota(sonido_golpe, sonido_punto)
jugador1 = Paleta(40)
jugador2 = Paleta(SCREEN_WIDTH - 40)
clock = pygame.time.Clock()
pygame.key.set_repeat(1, 25) # Activa repeticion de teclas
pygame.mouse.set_visible(False)
# el bucle principal del juego
while True:
clock.tick(60)
# Obtenemos la posicon del mouse
pos_mouse = pygame.mouse.get_pos()
mov_mouse = pygame.mouse.get_rel()
# Actualizamos los obejos en pantalla
jugador1.humano()
jugador2.cpu(bola)
bola.update()
# Comprobamos si colisionan los objetos
bola.colision(jugador1)
bola.colision(jugador2)
# Posibles entradas del teclado y mouse
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
elif event.type == pygame.KEYDOWN:
if event.key == K_UP:
jugador1.rect.centery -= 5
elif event.key == K_DOWN:
jugador1.rect.centery += 5
elif event.key == K_ESCAPE:
sys.exit(0)
elif event.type == pygame.KEYUP:
if event.key == K_UP:
jugador1.rect.centery += 0
elif event.key == K_DOWN:
jugador1.rect.centery += 0
# Si el mouse no esta quieto, mover la paleta a su posicion
elif mov_mouse[1] != 0:
jugador1.rect.centery = pos_mouse[1]
# actualizamos la pantalla
screen.blit(fondo, (0, 0))
todos = pygame.sprite.RenderPlain(bola, jugador1, jugador2)
todos.draw(screen)
pygame.display.flip()
"""
if __name__ == "__main__":
main()
"""