- Python (使用Pygame库制作一个简单的“Pong”游戏)szchuantian.com
首先,你需要安装Pygame库。可以通过pip安装:pip install pygame
python
import pygame
import sys
初始化pygame
pygame.init()
设置屏幕
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption(“Pong Game”)
游戏变量
ball_pos = [screen_width // 2, screen_height // 2]
ball_dir = [2, 2]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 边界碰撞检测 if ball_pos[0] <= 0 or ball_pos[0] >= screen_width - 10: ball_dir[0] = -ball_dir[0] if ball_pos[1] <= 0 or ball_pos[1] >= screen_height - 10: ball_dir[1] = -ball_dir[1] # 移动球 ball_pos[0] += ball_dir[0] ball_pos[1] += ball_dir[1] # 绘制 screen.fill((0, 0, 0)) pygame.draw.ellipse(screen, (255, 255, 255), (ball_pos[0], ball_pos[1], 10, 10)) pygame.display.flip() # 控制帧率 pygame.time.Clock().tick(60)
复制
pygame.quit()
sys.exit()
2. JavaScript (HTML5 Canvas制作一个简单的移动方块)
html
csharp
using UnityEngine;
public class MoveBall : MonoBehaviour
{
public float speed = 2.0f;
void Update() { // 简单地让球体沿着X轴移动 transform.Translate(Vector3.right * speed * Time.deltaTime); // 如果球体移出屏幕,则重置位置 if (transform.position.x > 10 || transform.position.x < -10) { transform.position = new Vector3(-5, transform.position.y, transform.position.z); } }
复制
}
这些示例提供了在不同编程语言和游戏引擎中制作基础小游戏的起点。你可以根据这些示例进一步扩展和自定义游戏功能。由于篇幅限制,我将为你提供三种不同编程语言中的简单小游戏示例:Python(使用Pygame库)、JavaScript(HTML5 Canvas),以及C#(Unity游戏引擎中的基础代码)。请注意,这些示例需要相应的开发环境和库来运行。
- Python (使用Pygame库制作一个简单的“Pong”游戏)
首先,你需要安装Pygame库。可以通过pip安装:pip install pygame
python
import pygame
import sys
初始化pygame
pygame.init()
设置屏幕
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption(“Pong Game”)
游戏变量
ball_pos = [screen_width // 2, screen_height // 2]
ball_dir = [2, 2]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 边界碰撞检测 if ball_pos[0] <= 0 or ball_pos[0] >= screen_width - 10: ball_dir[0] = -ball_dir[0] if ball_pos[1] <= 0 or ball_pos[1] >= screen_height - 10: ball_dir[1] = -ball_dir[1] # 移动球 ball_pos[0] += ball_dir[0] ball_pos[1] += ball_dir[1] # 绘制 screen.fill((0, 0, 0)) pygame.draw.ellipse(screen, (255, 255, 255), (ball_pos[0], ball_pos[1], 10, 10)) pygame.display.flip() # 控制帧率 pygame.time.Clock().tick(60)
复制
pygame.quit()
sys.exit()
2. JavaScript (HTML5 Canvas制作一个简单的移动方块)
html
csharp
using UnityEngine;
public class MoveBall : MonoBehaviour
{
public float speed = 2.0f;
void Update() { // 简单地让球体沿着X轴移动 transform.Translate(Vector3.right * speed * Time.deltaTime); // 如果球体移出屏幕,则重置位置 if (transform.position.x > 10 || transform.position.x < -10) { transform.position = new Vector3(-5, transform.position.y, transform.position.z); } }
复制
}
这些示例提供了在不同编程语言和游戏引擎中制作基础小游戏的起点。你可以根据这些示例进一步扩展和自定义游戏功能。