pycharm用pygame写游戏
时间: 2023-07-18 16:35:07 浏览: 108
好的,我可以给你一个简单的示例——一个小球在窗口中反弹的游戏。
首先,我们需要安装Pygame库。在PyCharm中,可以打开终端并输入以下命令来安装Pygame:
```
pip install pygame
```
然后,我们可以创建一个窗口并在窗口中绘制一个小球。可以使用Pygame中的Surface和draw模块来实现:
```python
import pygame
import sys
pygame.init() # 初始化Pygame
# 设置窗口大小和标题
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
pygame.display.set_caption('小球反弹游戏')
# 设置小球的初始位置和速度
ball_pos = [width // 2, height // 2]
ball_speed = [5, 5]
# 设置小球的半径和颜色
ball_radius = 20
ball_color = (255, 0, 0)
# 进入游戏循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 让小球移动
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# 判断小球是否碰到边界
if ball_pos[0] < ball_radius or ball_pos[0] > width - ball_radius:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] < ball_radius or ball_pos[1] > height - ball_radius:
ball_speed[1] = -ball_speed[1]
# 绘制小球
screen.fill((255, 255, 255)) # 设置背景色为白色
pygame.draw.circle(screen, ball_color, ball_pos, ball_radius)
pygame.display.update() # 更新窗口
```
最后,我们可以将以上代码整合在一起,并在PyCharm中运行:
```python
import pygame
import sys
pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
pygame.display.set_caption('小球反弹游戏')
ball_pos = [width // 2, height // 2]
ball_speed = [5, 5]
ball_radius = 20
ball_color = (255, 0, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
if ball_pos[0] < ball_radius or ball_pos[0] > width - ball_radius:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] < ball_radius or ball_pos[1] > height - ball_radius:
ball_speed[1] = -ball_speed[1]
screen.fill((255, 255, 255))
pygame.draw.circle(screen, ball_color, ball_pos, ball_radius)
pygame.display.update()
```
运行后,程序会创建一个窗口并在窗口中绘制一个小球,小球会在窗口中反弹。按下窗口的关闭按钮或者按下Ctrl+C可以退出程序。
阅读全文