Jakub Škrabánek 7 days ago
parent
commit
8711fc0c9f
  1. 72
      36_pygame_intro/03_kolize.py
  2. 4
      36_pygame_intro/poznamky.txt

72
36_pygame_intro/03_kolize.py

@ -0,0 +1,72 @@
import pygame
import random
import sys
pygame.init()
SIRKA = 800
VYSKA = 600
okno = pygame.display.set_mode((SIRKA,VYSKA))
pygame.display.set_caption("Kolize")
CERNA = (0,0,0)
CERVENA = (255,0,0)
ZELENA = (0,255,0)
MODRA = (0,0,255)
hodiny = pygame.time.Clock()
#proměná hráče
hrac_x = 400
hrac_y = 300
hrac_sirka = 50
hrac_vyska = 50
rychlost = 5
# proměnná "nepřítele"
nepritel_x, nepritel_y = 600, 300
nepritel_sirka, nepritel_vyska = 100, 100
bezime = True
while bezime:
for udalost in pygame.event.get():
if udalost.type == pygame.QUIT:
bezime = False
# if "OneLine"
klavesy = pygame.key.get_pressed()
if klavesy[pygame.K_LEFT]: hrac_x -= rychlost
if klavesy[pygame.K_RIGHT]: hrac_x += rychlost
if klavesy[pygame.K_UP]: hrac_y -= rychlost
if klavesy[pygame.K_DOWN]: hrac_y += rychlost
if hrac_x < 0 : hrac_x = 0
if hrac_y < 0 : hrac_y = 0
if hrac_x > SIRKA - hrac_sirka: hrac_x = SIRKA - hrac_sirka
if hrac_y > VYSKA - hrac_vyska: hrac_y = VYSKA - hrac_vyska
#Pro detekci kolizi musíme vytvořit objekty typu pygame.Rect
rect_hrac = pygame.Rect(hrac_x,hrac_y,hrac_sirka,hrac_vyska)
rect_nepritel = pygame.Rect(nepritel_x,nepritel_y,nepritel_sirka,nepritel_vyska)
#DETECTE KOLIZE -> dotíká se hráč "nepřítele"?
doslo_ke_kolizi = rect_hrac.colliderect(rect_nepritel)
#Pokud dojde ke kolizi, "nepřitel" změni barvu na zelnou, jinak červená
if doslo_ke_kolizi:
barva_nepritele = ZELENA
else:
barva_nepritele = CERVENA
okno.fill(CERNA)
#Vykreslíme obdelníky za pomocí podmínek a nových OBJKETU rect_...
pygame.draw.rect(okno,MODRA, rect_hrac)
pygame.draw.rect(okno, barva_nepritele, rect_nepritel)
pygame.display.flip()
hodiny.tick(60)
pygame.quit()
sys.exit()

4
36_pygame_intro/poznamky.txt

@ -2,4 +2,6 @@ python -m venv .venv
.venv\Scripts\activate
pip install pygame
pip install pygame
NEBO
pip install pygame-ce (pokud by pygame nešel nainstalovat)
Loading…
Cancel
Save