Gabungan Kode Python Untuk 2 Opsi Pilihan Formasi 2 Kuda, 1 Garuda dan Formasi 2 Garuda, 1 Kuda Pada Permainan Catur_Nine 9x9 Petak

GABUNGAN KODE PYTHON UNTUK 2 OPSI PILIHAN FORMASI 2 KUDA, 1 GARUDA DAN FORMASI 2 GARUDA, 1 KUDA PADA PERMAINAN CATUR_NINE 9X9 PETAK

(Oleh: SR.Pakpahan,SST)



Berikut diberikan kode dasar untuk pilihan formasi bagi pemain bidak putih dan bidak hitam untuk memilih formasi yang mereka inginkan sebelum memulai pertandingan catur_nine 9x9 petak.

Kode di pilih_formasi.py

import pygame
import sys
import os
import time

# === KONFIGURASI PYGAME ===
pygame.init()

# Ukuran layar
SCREEN_WIDTH, SCREEN_HEIGHT = 900, 700
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Chess Nine with Timer")

# Ukuran papan catur
BOARD_SIZE = 635
TILE_SIZE = BOARD_SIZE // 9
BOARD_X = (SCREEN_WIDTH - BOARD_SIZE) // 2 - 90
BOARD_Y = (SCREEN_HEIGHT - BOARD_SIZE) // 2 - (-170)

# Warna
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
LIGHT_BROWN = (240, 217, 181)
DARK_BROWN = (181, 136, 99)
RED = (200, 50, 50)
GREEN = (50, 200, 50)

# Font
font = pygame.font.Font(None, 40)

# Direktori gambar bidak

BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # Ambil direktori skrip saat ini
IMAGE_DIR = os.path.join(BASE_DIR, "images")  # Gabungkan dengan folder "images"

# === MEMUAT GAMBAR BIDAK ===
pieces_images = {}

def load_pieces():
    """Memuat gambar bidak dari direktori"""
    piece_names = ["pawn", "rook", "knight", "bishop", "queen", "king", "garuda"]
    colors = ["white", "black"]

    for color in colors:
        for piece in piece_names:
            path = os.path.join(IMAGE_DIR, f"{color}_{piece}.png")
            if os.path.exists(path):
                img = pygame.image.load(path)
                img = pygame.transform.scale(img, (TILE_SIZE, TILE_SIZE))
                pieces_images[f"{color}_{piece}"] = img
                
# === FORMASI AWAL BIDAK PUTIH ===
formasi_1_white = {  # 2 Kuda, 1 Garuda (Menambahkan gajah di c1)
    "white_knight": [(7, 8), (2, 8)],
    "white_garuda": [(1, 8)],
}

formasi_2_white = {  # 2 Garuda, 1 Kuda (Menambahkan gajah di c1 dan h1)
    "white_knight": [(1, 8)],
    "white_garuda": [(2, 8), (7, 8)]    
}

# === FORMASI AWAL BIDAK HITAM === (Disesuaikan dengan formasi putih)
formasi_1_black = {  # 2 Kuda, 1 Garuda (Menambahkan gajah di c9)
    "black_knight": [(7, 0), (2, 0)],
    "black_garuda": [(1, 0)]
}

formasi_2_black = {  # 2 Garuda, 1 Kuda (Menambahkan gajah di c9 dan h9)
    "black_knight": [(1, 0)],
    "black_garuda": [(2, 0), (7, 0)]
}

# === POSISI DEFAULT (TIDAK BERUBAH) ===
default_position = {
    "white_rook": [(0, 8), (8, 8)],
    "white_queen": [(5, 8)],
    "white_king": [(4, 8)],
    "white_bishop": [(3, 8), (6, 8)],  # Gajah putih di d1 dan g1
    "white_pawn": [(i, 7) for i in range(9)],

    "black_rook": [(0, 0), (8, 0)],
    "black_queen": [(5, 0)],
    "black_king": [(4, 0)],
    "black_bishop": [(3, 0), (6, 0)],  # Gajah putih di d9 dan g9   
    "black_pawn": [(i, 1) for i in range(9)],
}
                
# === WAKTU PERMAINAN ===
WHITE_TIME = 3600  # 60 menit dalam detik
BLACK_TIME = 3600
current_player = "white"
last_time = time.time()

def draw_timer():
    """Menampilkan timer di layar dengan kotak pembungkus"""
    # Format teks timer
    white_timer_text = font.render(f"{WHITE_TIME // 60}:{WHITE_TIME % 60:02d}", True, BLACK)
    black_timer_text = font.render(f"{BLACK_TIME // 60}:{BLACK_TIME % 60:02d}", True, BLACK)

    # Ukuran kotak pembungkus
    box_width, box_height = 140, 50

    # Posisi kotak untuk white_timer (kanan bawah papan)
    white_box_x = BOARD_X + BOARD_SIZE -  100
    white_box_y = BOARD_Y + BOARD_SIZE - box_height + 60

    # Posisi kotak untuk black_timer (kanan atas papan)
    black_box_x = BOARD_X + BOARD_SIZE - 100
    black_box_y = BOARD_Y - 60

    # Gambar kotak untuk white_timer
    pygame.draw.rect(screen, LIGHT_BROWN, (white_box_x, white_box_y, box_width, box_height), border_radius=10)
    pygame.draw.rect(screen, BLACK, (white_box_x, white_box_y, box_width, box_height), 2, border_radius=10)
    screen.blit(white_timer_text, (white_box_x + 40, white_box_y + 10))

    # Gambar kotak untuk black_timer
    pygame.draw.rect(screen, LIGHT_BROWN, (black_box_x, black_box_y, box_width, box_height), border_radius=10)
    pygame.draw.rect(screen, BLACK, (black_box_x, black_box_y, box_width, box_height), 2, border_radius=10)
    screen.blit(black_timer_text, (black_box_x + 40, black_box_y + 10))

def update_timer():
    """Mengupdate timer berdasarkan giliran pemain"""
    global WHITE_TIME, BLACK_TIME, last_time

    current_time = time.time()
    elapsed_time = current_time - last_time
    last_time = current_time

    if current_player == "white":
        WHITE_TIME -= int(elapsed_time)
        if WHITE_TIME <= 0:
            print("Waktu Habis! Hitam Menang!")
            pygame.quit()
            sys.exit()
    else:
        BLACK_TIME -= int(elapsed_time)
        if BLACK_TIME <= 0:
            print("Waktu Habis! Putih Menang!")
            pygame.quit()
            sys.exit()

# === FUNGSI GAMBAR PAPAN DAN BIDAK ===
def draw_board():
    for row in range(9):
        for col in range(9):
             # Petak e5 (indeks array: 4,4) diwarnai putih
            if row == 4 and col == 4:
                color = WHITE
            else:
                # Warna petak papan catur normal           
            
                color = DARK_BROWN if (row + col) % 2 == 0 else LIGHT_BROWN
                pygame.draw.rect(screen, color, 
                             (BOARD_X + col * TILE_SIZE, BOARD_Y + row * TILE_SIZE, TILE_SIZE, TILE_SIZE))

def draw_pieces(starting_position):
    """Menggambar semua bidak di posisi awal"""
    for piece, positions in starting_position.items():
        if piece in pieces_images:
            for pos in positions:
                x, y = pos
                screen.blit(pieces_images[piece], 
                            (BOARD_X + x * TILE_SIZE, BOARD_Y + y * TILE_SIZE))

# === FUNGSI GILIRAN ===
def switch_turn():
    """Mengubah giliran pemain"""
    global current_player
    if current_player == "white":
        current_player = "black"
    else:
        current_player = "white"

# === FUNGSI TOMBOL FORMASI ===
def draw_button(text, x, y, width, height, color):
    pygame.draw.rect(screen, color, (x, y, width, height), border_radius=5)
    button_text = font.render(text, True, WHITE)
    screen.blit(button_text, (x + 10, y + 10))
    return pygame.Rect(x, y, width, height)

def choose_white_formation():
    """Menampilkan tombol pilihan formasi untuk bidak putih sebelum permainan dimulai dengan latar papan catur."""
    selected_formation = None

    while selected_formation is None:
        screen.fill(WHITE)  # Membersihkan layar sebelum menggambar ulang
        
        # **Gambar papan catur 9x9 sebagai latar belakang**
        draw_board()
        
        label_text = font.render("GAME CATUR_NINE 9x9 PETAK", True, BLACK)
        screen.blit(label_text, (SCREEN_WIDTH // 2 - 300,  SCREEN_HEIGHT // 3 - 220))

        # **Tambahkan label pemilihan formasi**
        title_text = font.render("Pilih Formasi Bidak Putih:", True, BLACK)
        screen.blit(title_text, (SCREEN_WIDTH // 2 - 270,  SCREEN_HEIGHT // 3  + 605))

        # **Gambar tombol pilihan formasi**
        btn_1 = draw_button("2 Kuda, 1 Garuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 3+638, 280, 50, RED)
        btn_2 = draw_button("2 Garuda, 1 Kuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 3 + 700, 280, 50, GREEN)

        # **Perbarui tampilan**
        pygame.display.flip()

        # **Tangani event klik tombol**
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if btn_1.collidepoint(mouse_pos):
                    selected_formation = formasi_1_white
                elif btn_2.collidepoint(mouse_pos):
                    selected_formation = formasi_2_white

    return selected_formation

def choose_black_formation():
    """Menampilkan tombol pilihan formasi untuk bidak hitam sebelum permainan dimulai."""
    selected_formation = None

    while selected_formation is None:
        screen.fill(WHITE)
        
        # **Gambar papan catur 9x9 sebagai latar belakang**
        draw_board()      
        
        label_text = font.render("GAME CATUR_NINE 9x9 PETAK", True, BLACK)
        screen.blit(label_text, (SCREEN_WIDTH // 2 - 300,  SCREEN_HEIGHT // 3 - 220))    

        ltitle_text = font.render("Pilih Formasi Bidak Hitam:", True, BLACK)
        screen.blit(ltitle_text, (SCREEN_WIDTH // 2 - 270, SCREEN_HEIGHT // 10 - 20))

        btn_1 = draw_button("2 Kuda, 1 Garuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 12 + 28, 280, 50, RED)
        btn_2 = draw_button("2 Garuda, 1 Kuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 13 + 95, 280, 50, GREEN)

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if btn_1.collidepoint(mouse_pos):
                    selected_formation = formasi_1_black
                elif btn_2.collidepoint(mouse_pos):
                    selected_formation = formasi_2_black

    return selected_formation

def choose_formation():
    """Menampilkan tombol pilihan formasi sebelum permainan dimulai."""
    selected_formation = None

    while selected_formation is None:
        screen.fill(WHITE)
        
        label_text = font.render("GAME CATUR_NINE 9x9 PETAK", True, BLACK)
        screen.blit(label_text, (SCREEN_WIDTH // 2 - 300, SCREEN_HEIGHT // 5 - 50))
        
        title_text = font.render("Pilih Formasi Bidak:", True, BLACK)
        screen.blit(title_text, (SCREEN_WIDTH // 2 - 135, SCREEN_HEIGHT // 3 - 50))

        btn_1 = draw_button("2 Kuda, 1 Garuda", SCREEN_WIDTH // 2 - 140, SCREEN_HEIGHT // 3, 280, 50, RED)
        btn_2 = draw_button("2 Garuda, 1 Kuda", SCREEN_WIDTH // 2 - 140, SCREEN_HEIGHT // 3 + 70, 280, 50, GREEN)

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if btn_1.collidepoint(mouse_pos):
                    selected_formation = (formasi_1_white, formasi_1_black)
                elif btn_2.collidepoint(mouse_pos):
                    selected_formation = (formasi_2_white, formasi_2_black)

    return selected_formation

# === MULAI GAME ===
clock = pygame.time.Clock()

# Muat gambar bidak
load_pieces()

# Pemain memilih formasi awal
chosen_white = choose_white_formation()
chosen_black = choose_black_formation()

# Gabungkan posisi default dengan formasi yang dipilih
starting_position = {**default_position, **chosen_white, **chosen_black}
running = True
while running:
    screen.fill(WHITE)

    # Update timer sebelum menggambar papan
    update_timer()

    draw_board()
    draw_pieces(starting_position)
    draw_timer()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            switch_turn()  # Simulasi pergantian giliran jika ada klik mouse

    pygame.display.flip()
    clock.tick(30)

pygame.quit()
sys.exit()

Perbaikan dan Pengembangan Kode

1. Perbaikan Timer pada Permainan
Untuk mengoptimalkan timer permainan pada kode catur Anda, berikut beberapa perbaikan yang bisa dilakukan:
  • Gunakan pygame.time.get_ticks()
Alih-alih mengandalkan perhitungan manual, gunakan pygame.time.get_ticks() untuk mendapatkan waktu dalam milidetik sejak permainan dimulai.
  • Kurangi Pembaruan Berlebihan
Pastikan timer hanya diperbarui jika ada perubahan signifikan, bukan setiap frame.
  • Optimalkan Loop Timer
Gunakan interval pembaruan yang efisien, misalnya dengan pygame.time.delay(100).

Dari kode sebelumnya, ada beberapa masalah yang mungkin menyebabkan timer tidak berjalan dengan baik:

  1. Timer berjalan terus tanpa memperhitungkan giliran pemain.
  2. switch_turn() tidak memperbarui current_player secara global.
  3. update_timer() tetap berjalan setiap frame, bahkan ketika pemain belum bergerak.

Solusi

  1. Gunakan pygame.time.get_ticks() untuk menghitung waktu dengan lebih akurat.
  2. Pastikan timer hanya berkurang saat giliran pemain yang bersangkutan.
  3. Modifikasi switch_turn() agar memperbarui last_time.

Perbaikan Kode:

# === WAKTU PERMAINAN ===
WHITE_TIME = 3600  # 60 menit dalam detik
BLACK_TIME = 3600
current_player = "white"
last_time = pygame.time.get_ticks()  # Gunakan get_ticks()

def update_timer():
    """Mengupdate timer berdasarkan giliran pemain"""
    global WHITE_TIME, BLACK_TIME, last_time

    current_time = pygame.time.get_ticks()
    elapsed_time = (current_time - last_time) // 1000  # Konversi ms ke detik

    if elapsed_time > 0:
        if current_player == "white":
            WHITE_TIME -= elapsed_time
            if WHITE_TIME <= 0:
                print("Waktu Habis! Hitam Menang!")
                pygame.quit()
                sys.exit()
        else:
            BLACK_TIME -= elapsed_time
            if BLACK_TIME <= 0:
                print("Waktu Habis! Putih Menang!")
                pygame.quit()
                sys.exit()

        last_time = current_time  # Perbarui last_time setelah mengurangi waktu

def switch_turn():
    """Beralih giliran pemain"""
    global current_player, last_time
    current_player = "black" if current_player == "white" else "white"
    last_time = pygame.time.get_ticks()  # Reset last_time saat pergantian giliran

Perubahan yang Dilakukan:

✅ Menggunakan pygame.time.get_ticks() untuk memastikan timer tetap akurat.

Pada kode sebelumnya:

# === WAKTU PERMAINAN ===

WHITE_TIME = 3600  # 60 menit dalam detik

BLACK_TIME = 3600

current_player = "white"

last_time = time.time()

Gantikan dengan kode yang ini:

# === WAKTU PERMAINAN ===

WHITE_TIME = 3600  # 60 menit dalam detik

BLACK_TIME = 3600

current_player = "white"

last_time = pygame.time.get_ticks()  # Gunakan get_ticks()

✅ Fungsi update_timer(). Timer hanya berjalan saat giliran pemain berlangsung.

Pada kode sebelumnya:

def update_timer():

    """Mengupdate timer berdasarkan giliran pemain"""

    global WHITE_TIME, BLACK_TIME, last_time


    current_time = time.time()

    elapsed_time = current_time - last_time

    last_time = current_time


    if current_player == "white":

        WHITE_TIME -= int(elapsed_time)

        if WHITE_TIME <= 0:

            print("Waktu Habis! Hitam Menang!")

            pygame.quit()

            sys.exit()

    else:

        BLACK_TIME -= int(elapsed_time)

        if BLACK_TIME <= 0:

            print("Waktu Habis! Putih Menang!")

            pygame.quit()

            sys.exit()

Gantikan dengan kode yang ini:

def update_timer():

    """Mengupdate timer berdasarkan giliran pemain"""

    global WHITE_TIME, BLACK_TIME, last_time


    current_time = pygame.time.get_ticks()

    elapsed_time = (current_time - last_time) // 1000  # Konversi ms ke detik


    if elapsed_time > 0:

        if current_player == "white":

            WHITE_TIME -= elapsed_time

            if WHITE_TIME <= 0:

                print("Waktu Habis! Hitam Menang!")

                pygame.quit()

                sys.exit()

        else:

            BLACK_TIME -= elapsed_time

            if BLACK_TIME <= 0:

                print("Waktu Habis! Putih Menang!")

                pygame.quit()

                sys.exit()


        last_time = current_time  # Perbarui last_time setelah mengurangi waktu

✅ switch_turn() memperbarui last_time agar timer tidak langsung berkurang drastis.

Pada kode sebelumnya:

# === FUNGSI GILIRAN ===

def switch_turn():

    """Mengubah giliran pemain"""

    global current_player

    if current_player == "white":

        current_player = "black"

    else:

        current_player = "white"

Gantikan dengan kode yang ini:

def switch_turn():

    """Beralih giliran pemain"""

    global current_player, last_time

    current_player = "black" if current_player == "white" else "white"

    last_time = pygame.time.get_ticks()  # Reset last_time saat pergantian giliran

Dengan perubahan ini, timer seharusnya berjalan optimal dan tidak berkurang saat giliran belum berpindah. Agar lebih sesuai nama filenya diganti dari pilih_formasi.py menjadi pilih_formasi+timer.py

Perbaikan Kode: pilih_formasi+timer.py

import pygame

import sys

import os

import time


# === KONFIGURASI PYGAME ===

pygame.init()


# Ukuran layar

SCREEN_WIDTH, SCREEN_HEIGHT = 900, 700

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))


pygame.display.set_caption("Chess Nine with Timer")


# Ukuran papan catur

BOARD_SIZE = 635

TILE_SIZE = BOARD_SIZE // 9

BOARD_X = (SCREEN_WIDTH - BOARD_SIZE) // 2 - 90

BOARD_Y = (SCREEN_HEIGHT - BOARD_SIZE) // 2 - (-170)


# Warna

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

LIGHT_BROWN = (240, 217, 181)

DARK_BROWN = (181, 136, 99)

RED = (200, 50, 50)

GREEN = (50, 200, 50)


# Font

font = pygame.font.Font(None, 40)


# Direktori gambar bidak

IMAGE_DIR = "/storage/emulated/0/AppJadi/Catur/Catur_9x9/images"


# === MEMUAT GAMBAR BIDAK ===

pieces_images = {}

def load_pieces():

    """Memuat gambar bidak dari direktori"""

    piece_names = ["pawn", "rook", "knight", "bishop", "queen", "king", "garuda"]

    colors = ["white", "black"]

    for color in colors:

        for piece in piece_names:

            path = os.path.join(IMAGE_DIR, f"{color}_{piece}.png")

            if os.path.exists(path):

                img = pygame.image.load(path)

                img = pygame.transform.scale(img, (TILE_SIZE, TILE_SIZE))

                pieces_images[f"{color}_{piece}"] = img

               

# === FORMASI AWAL BIDAK PUTIH ===

formasi_1_white = {  # 2 Kuda, 1 Garuda (Menambahkan gajah di c1)

    "white_knight": [(7, 8), (2, 8)],

    "white_garuda": [(1, 8)],

}


formasi_2_white = {  # 2 Garuda, 1 Kuda (Menambahkan gajah di c1 dan h1)

    "white_knight": [(1, 8)],

    "white_garuda": [(2, 8), (7, 8)]    

}


# === FORMASI AWAL BIDAK HITAM === (Disesuaikan dengan formasi putih)

formasi_1_black = {  # 2 Kuda, 1 Garuda (Menambahkan gajah di c9)

    "black_knight": [(7, 0), (2, 0)],

    "black_garuda": [(1, 0)]

}


formasi_2_black = {  # 2 Garuda, 1 Kuda (Menambahkan gajah di c9 dan h9)

    "black_knight": [(1, 0)],

    "black_garuda": [(2, 0), (7, 0)]

}


# === POSISI DEFAULT (TIDAK BERUBAH) ===

default_position = {

    "white_rook": [(0, 8), (8, 8)],

    "white_queen": [(5, 8)],

    "white_king": [(4, 8)],

    "white_bishop": [(3, 8), (6, 8)],  # Gajah putih di d1 dan g1

    "white_pawn": [(i, 7) for i in range(9)],


    "black_rook": [(0, 0), (8, 0)],

    "black_queen": [(5, 0)],

    "black_king": [(4, 0)],

    "black_bishop": [(3, 0), (6, 0)],  # Gajah putih di d9 dan g9   

    "black_pawn": [(i, 1) for i in range(9)],

}


# === WAKTU PERMAINAN ===

WHITE_TIME = 3600  # 60 menit dalam detik

BLACK_TIME = 3600

current_player = "white"

last_time = pygame.time.get_ticks()  # Gunakan get_ticks()                

                                              

def draw_timer():

    """Menampilkan timer di layar dengan kotak pembungkus"""

    white_timer_text = font.render(f"{WHITE_TIME // 60}:{WHITE_TIME % 60:02d}", True, BLACK)

    black_timer_text = font.render(f"{BLACK_TIME // 60}:{BLACK_TIME % 60:02d}", True, BLACK)


    # Ukuran kotak pembungkus

    box_width, box_height = 140, 50

    # Posisi kotak untuk white_timer

    white_box_x = BOARD_X + BOARD_SIZE - 100

    white_box_y = BOARD_Y + BOARD_SIZE - box_height + 60


    # Posisi kotak untuk black_timer

    black_box_x = BOARD_X + BOARD_SIZE - 100

    black_box_y = BOARD_Y - 60


    # Gambar kotak untuk white_timer

    pygame.draw.rect(screen, LIGHT_BROWN, (white_box_x, white_box_y, box_width, box_height), border_radius=10)

    pygame.draw.rect(screen, BLACK, (white_box_x, white_box_y, box_width, box_height), 2, border_radius=10)

    screen.blit(white_timer_text, (white_box_x + 40, white_box_y + 10))


    # Gambar kotak untuk black_timer

    pygame.draw.rect(screen, LIGHT_BROWN, (black_box_x, black_box_y, box_width, box_height), border_radius=10)

    pygame.draw.rect(screen, BLACK, (black_box_x, black_box_y, box_width, box_height), 2, border_radius=10)

    screen.blit(black_timer_text, (black_box_x + 40, black_box_y + 10))


def update_timer():

    """Mengupdate timer berdasarkan giliran pemain"""

    global WHITE_TIME, BLACK_TIME, last_time

    current_time = pygame.time.get_ticks()

    elapsed_time = (current_time - last_time) // 1000  # Konversi ms ke detik

    if elapsed_time > 0:

        if current_player == "white":

            WHITE_TIME -= elapsed_time

            if WHITE_TIME <= 0:

                print("Waktu Habis! Hitam Menang!")

                pygame.quit()

                sys.exit()

        else:

            BLACK_TIME -= elapsed_time

            if BLACK_TIME <= 0:

                print("Waktu Habis! Putih Menang!")

                pygame.quit()

                sys.exit()

        last_time = current_time  # Perbarui last_time setelah mengurangi waktu


# === FUNGSI GAMBAR PAPAN DAN BIDAK ===

def draw_board():

    for row in range(9):

        for col in range(9):

             # Petak e5 (indeks array: 4,4) diwarnai putih

            if row == 4 and col == 4:

                color = WHITE

            else:

                # Warna petak papan catur normal                      

                color = DARK_BROWN if (row + col) % 2 == 0 else LIGHT_BROWN

                pygame.draw.rect(screen, color, 

                             (BOARD_X + col * TILE_SIZE, BOARD_Y + row * TILE_SIZE, TILE_SIZE, TILE_SIZE))


def draw_pieces(starting_position):

    """Menggambar semua bidak di posisi awal"""

    for piece, positions in starting_position.items():

        if piece in pieces_images:

            for pos in positions:

                x, y = pos

                screen.blit(pieces_images[piece],

                            (BOARD_X + x * TILE_SIZE, BOARD_Y + y * TILE_SIZE))

                                               

# === FUNGSI GILIRAN ===

def switch_turn():

    """Beralih giliran pemain"""

    global current_player, last_time

    current_player = "black" if current_player == "white" else "white"

    last_time = pygame.time.get_ticks()  # Reset last_time saat pergantian giliran       


# === FUNGSI TOMBOL FORMASI ===

def draw_button(text, x, y, width, height, color):

    pygame.draw.rect(screen, color, (x, y, width, height), border_radius=5)

    button_text = font.render(text, True, WHITE)

    screen.blit(button_text, (x + 10, y + 10))

    return pygame.Rect(x, y, width, height)


def choose_white_formation():

    """Menampilkan tombol pilihan formasi untuk bidak putih sebelum permainan dimulai dengan latar papan catur."""

    selected_formation = None

    while selected_formation is None:

        screen.fill(WHITE)  # Membersihkan layar sebelum menggambar ulang

       

        # **Gambar papan catur 9x9 sebagai latar belakang**

        draw_board()               

        label_text = font.render("GAME CATUR_NINE 9x9 PETAK", True, BLACK)

        screen.blit(label_text, (SCREEN_WIDTH // 2 - 300,  SCREEN_HEIGHT // 3 - 220))

        # **Tambahkan label pemilihan formasi**

        title_text = font.render("Pilih Formasi Bidak Putih:", True, BLACK)

        screen.blit(title_text, (SCREEN_WIDTH // 2 - 270,  SCREEN_HEIGHT // 3  + 605))

        # **Gambar tombol pilihan formasi**

        btn_1 = draw_button("2 Kuda, 1 Garuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 3+638, 280, 50, RED)

        btn_2 = draw_button("2 Garuda, 1 Kuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 3 + 700, 280, 50, GREEN)

        # **Perbarui tampilan**

        pygame.display.flip()

        # **Tangani event klik tombol**

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.MOUSEBUTTONDOWN:

                mouse_pos = pygame.mouse.get_pos()

                if btn_1.collidepoint(mouse_pos):

                    selected_formation = formasi_1_white

                elif btn_2.collidepoint(mouse_pos):

                    selected_formation = formasi_2_white

    return selected_formation


def choose_black_formation():

    """Menampilkan tombol pilihan formasi untuk bidak hitam sebelum permainan dimulai."""

    selected_formation = None

    while selected_formation is None:

        screen.fill(WHITE)     

        # **Gambar papan catur 9x9 sebagai latar belakang**

        draw_board()            

        label_text = font.render("GAME CATUR_NINE 9x9 PETAK", True, BLACK)

        screen.blit(label_text, (SCREEN_WIDTH // 2 - 300,  SCREEN_HEIGHT // 3 - 220))    

        ltitle_text = font.render("Pilih Formasi Bidak Hitam:", True, BLACK)

        screen.blit(ltitle_text, (SCREEN_WIDTH // 2 - 270, SCREEN_HEIGHT // 10 - 20))

        btn_1 = draw_button("2 Kuda, 1 Garuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 12 + 28, 280, 50, RED)

        btn_2 = draw_button("2 Garuda, 1 Kuda", SCREEN_WIDTH // 2 - 230, SCREEN_HEIGHT // 13 + 95, 280, 50, GREEN)

        pygame.display.flip()

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.MOUSEBUTTONDOWN:

                mouse_pos = pygame.mouse.get_pos()

                if btn_1.collidepoint(mouse_pos):

                    selected_formation = formasi_1_black

                elif btn_2.collidepoint(mouse_pos):

                    selected_formation = formasi_2_black

    return selected_formation


def choose_formation():

    """Menampilkan tombol pilihan formasi sebelum permainan dimulai."""

    selected_formation = None

    while selected_formation is None:

        screen.fill(WHITE)      

        label_text = font.render("GAME CATUR_NINE 9x9 PETAK", True, BLACK)

        screen.blit(label_text, (SCREEN_WIDTH // 2 - 300, SCREEN_HEIGHT // 5 - 50))       

        title_text = font.render("Pilih Formasi Bidak:", True, BLACK)

        screen.blit(title_text, (SCREEN_WIDTH // 2 - 135, SCREEN_HEIGHT // 3 - 50))

        btn_1 = draw_button("2 Kuda, 1 Garuda", SCREEN_WIDTH // 2 - 140, SCREEN_HEIGHT // 3, 280, 50, RED)

        btn_2 = draw_button("2 Garuda, 1 Kuda", SCREEN_WIDTH // 2 - 140, SCREEN_HEIGHT // 3 + 70, 280, 50, GREEN)

        pygame.display.flip()

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.MOUSEBUTTONDOWN:

                mouse_pos = pygame.mouse.get_pos()

                if btn_1.collidepoint(mouse_pos):

                    selected_formation = (formasi_1_white, formasi_1_black)

                elif btn_2.collidepoint(mouse_pos):

                    selected_formation = (formasi_2_white, formasi_2_black)

    return selected_formation


# === MULAI GAME ===

clock = pygame.time.Clock()


# Muat gambar bidak

load_pieces()


# Pemain memilih formasi awal

chosen_white = choose_white_formation()

chosen_black = choose_black_formation()


# Gabungkan posisi default dengan formasi yang dipilih

starting_position = {**default_position, **chosen_white, **chosen_black}


running = True

while running:

    screen.fill(WHITE)

    # Update timer sebelum menggambar papan

    update_timer()

    draw_board()

    draw_pieces(starting_position)

    draw_timer()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:

            switch_turn()  # Simulasi pergantian giliran jika ada klik mouse


    pygame.display.flip()

    clock.tick(30)

pygame.quit()

sys.exit()

Namun, masih terlihat bahwa kode ini belum memiliki bagian utama untuk menjalankan permainan (game loop). Selain itu, juga perlu menambahkan mekanisme interaksi, seperti pergerakan bidak, aturan permainan, atau validasi langkah, maka masih ada banyak hal yang perlu dikembangkan lebih lanjut, seperti:

- Implementasi pergerakan bidak:

 Tambahkan mekanisme klik untuk memilih dan memindahkan bidak. 

Buat fungsi untuk validasi langkah bidak sesuai aturan catur Nine 9x9.

- AI atau Multiplayer (Opsional):

Jika ingin bermain melawan AI, bisa menambahkan algoritma minimax atau rule-based AI.

- Jika ingin multiplayer online, bisa menggunakan pygame.networking atau socket programming.

- Simpan dan Muat Permainan (Opsional):

Tambahkan fitur untuk menyimpan dan melanjutkan permainan.

Gunakan format JSON atau SQLite untuk menyimpan status permainan.


Kode di __main__.py

 


Kode di catur_nine_move.py




Comments

Popular posts from this blog

Teknik Dasar Blind Search (Pencarian Blind/Buta

Membuat Server Online Menggunakan Hosting atau VPS

6 Langkah untuk Meningkatkan Catur Anda di Tahun 2025