これを7秒で作成するGrokさん。
import pygame
import sys
import random
# 初期化
pygame.init()
# 画面設定
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("ドンキーコング風アドベンチャー")
clock = pygame.time.Clock()
FONT = pygame.font.SysFont("meiryo", 36) # 日本語対応フォント
# 色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BROWN = (139, 69, 19)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# プレイヤー
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((40, 50))
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = HEIGHT - 100
self.vel_x = 0
self.vel_y = 0
self.on_ground = False
self.climbing = False
self.lives = 3
def update(self, platforms, ladders):
# 重力
if not self.climbing:
self.vel_y = 0.8 # 重力
self.rect.x = self.vel_x
self.collide(self.vel_x, 0, platforms)
self.rect.y = self.vel_y
self.on_ground = self.collide(0, self.vel_y, platforms)
# はしご
self.climbing = False
for ladder in ladders:
if pygame.sprite.collide_rect(self, ladder):
self.climbing = True
if abs(self.vel_y) > 0 or abs(self.vel_x) > 0:
self.rect.y = self.vel_y * 0.5 # 登る速度調整
break
def collide(self, vel_x, vel_y, platforms):
for p in platforms:
if pygame.sprite.collide_rect(self, p):
if vel_x > 0:
self.rect.right = p.rect.left
if vel_x < 0:
self.rect.left = p.rect.right
if vel_y > 0:
self.rect.bottom =
p.rect.top
self.vel_y = 0
self.on_ground = True
if vel_y < 0:
self.rect.top = p.rect.bottom
self.vel_y = 0
return self.on_ground
def jump(self):
if self.on_ground:
self.vel_y = -15
# プラットフォーム
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
super().__init__()
self.image = pygame.Surface((w, h))
self.image.fill(BROWN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# はしご
class Ladder(pygame.sprite.Sprite):
def __init__(self, x, y, h):
super().__init__()
self.image = pygame.Surface((30, h))
self.image.fill((200, 150, 50))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# バレル(敵)
class Barrel(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_x = random.choice([-4, 4])
self.vel_y = 0
def update(self, platforms):
self.rect.x = self.vel_x
self.vel_y = 0.5
self.rect.y = self.vel_y
for p in platforms:
if pygame.sprite.collide_rect(self, p):
if self.vel_y > 0:
self.rect.bottom =
p.rect.top
self.vel_y = -8 # バウンド
self.vel_x *= -1 # 跳ね返り
# メインゲーム
def main():
player = Player()
all_sprites =
pygame.sprite.Group(player)
platforms =
pygame.sprite.Group()
ladders =
pygame.sprite.Group()
barrels =
pygame.sprite.Group()
# プラットフォーム作成
ground = Platform(0, HEIGHT - 40, WIDTH, 40)
platforms.add(ground)
platforms.add(Platform(100, 450, 200, 20))
platforms.add(Platform(500, 380, 250, 20))