Bir kod daha veriyorum arkadaşlar.
Bu örnek kodda, yılan ve yem nesneleri oluşturduk ve bunların hareket ve çarpışma özelliklerini tanımladık. Pygame kütüphanesi sayesinde de bu nesneleri ekranda gösterdik. Oyunun kontrolünü ise klavyeden alınan tuşlara göre yapıyoruz.
Python:
import pygame
import random
pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Piton Yilan Oyunu")
clock = pygame.time.Clock()
yilan_renk = (0, 255, 0)
yem_renk = (255, 0, 0)
class Yilan:
def __init__(self):
self.pozisyonlar = [(width/2, height/2)]
self.yon = random.choice(["up", "down", "left", "right"])
def hareket(self):
x, y = self.pozisyonlar[0]
if self.yon == "up":
y -= 10
elif self.yon == "down":
y += 10
elif self.yon == "left":
x -= 10
elif self.yon == "right":
x += 10
self.pozisyonlar.insert(0, (x, y))
self.pozisyonlar.pop()
def yeme(self):
x, y = self.pozisyonlar[0]
yeni_yem = False
if x == yem.x and y == yem.y:
yeni_yem = True
return yeni_yem
def carpisma(self):
x, y = self.pozisyonlar[0]
if x < 0 or x > width or y < 0 or y > height:
return True
for pozisyon in self.pozisyonlar[1:]:
if x == pozisyon[0] and y == pozisyon[1]:
return True
return False
def yon_degis(self, yon):
if yon == "up" and self.yon != "down":
self.yon = yon
elif yon == "down" and self.yon != "up":
self.yon = yon
elif yon == "left" and self.yon != "right":
self.yon = yon
elif yon == "right" and self.yon != "left":
self.yon = yon
class Yem:
def __init__(self):
self.x = round(random.randrange(0, width-10) / 10.0) * 10.0
self.y = round(random.randrange(0, height-10) / 10.0) * 10.0
def ciz(self):
pygame.draw.rect(screen, yem_renk, (self.x, self.y, 10, 10))
yilan = Yilan()
yem = Yem()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
yilan.yon_degis("up")
elif event.key == pygame.K_DOWN:
yilan.yon_degis("down")
elif event.key == pygame.K_LEFT:
yilan.yon_degis("left")
elif event.key == pygame.K_RIGHT:
yilan.yon_degis("right")
screen.fill((0, 0, 0))
if yilan.yeme():
yem = Yem()
yilan.hareket()
yem.ciz()
if yilan.carpisma():
pygame.quit()
sys.exit()
for pozisyon in yilan.pozisyonlar:
x, y = pozisyon
pygame.draw.rect(screen, yilan_renk, (x, y, 10, 10))
pygame.display.update()
clock.tick(20)