Python 游戏开发实战:从入门到精通
pip install pygame
import pygame
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
# 创建屏幕
screen = pygame.display.set_mode((screen_width, screen_height))
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充屏幕背景色
screen.fill((0, 0, 0))
# 在这里添加游戏的逻辑和图形绘制
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
import pygame
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
# 创建屏幕
screen = pygame.display.set_mode((screen_width, screen_height))
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充屏幕背景色
screen.fill((0, 0, 0))
# 绘制矩形
pygame.draw.rect(screen, (255, 0, 0), [200, 200, 100, 100])
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
import pygame
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
# 创建屏幕
screen = pygame.display.set_mode((screen_width, screen_height))
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print("Space key pressed")
# 填充屏幕背景色
screen.fill((0, 0, 0))
# 在这里添加游戏的逻辑和图形绘制
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
import pygame
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.speed = 5
def move_up(self):
self.y -= self.speed
def move_down(self):
self.y += self.speed
def move_left(self):
self.x -= self.speed
def move_right(self):
self.x += self.speed
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
# 创建屏幕
screen = pygame.display.set_mode((screen_width, screen_height))
# 创建玩家对象
player = Player(400, 300)
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充屏幕背景色
screen.fill((0, 0, 0))
# 处理玩家移动
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_UP]:
player.move_up()
if keys_pressed[pygame.K_DOWN]:
player.move_down()
if keys_pressed[pygame.K_LEFT]:
player.move_left()
if keys_pressed[pygame.K_RIGHT]:
player.move_right()
# 绘制玩家
pygame.draw.rect(screen, (255, 255, 255), [player.x, player.y, 50, 50])
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
本文转自:https://www.wodianping.com/app/2024-10/51647.html