优客文库提供全面的范文格式和文档模板,包括申请书、合同、借据、证明、求职信等,助力您快速撰写专业文档。

小游戏的代码

来自 甘肃省天水市 的网友 时间: 热度:°C 加入收藏 我要投稿 点赞()
```python
import pygame
import random

pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("小游戏")

# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)

# 设置游戏时钟
clock = pygame.time.Clock()

# 设置字体
font = pygame.font.SysFont(None, 25)

def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [screen_width/2 - screen_text.get_width()/2, screen_height/2 - screen_text.get_height()/2])

def game_loop():
game_exit = False
game_over = False

x = screen_width / 2
y = screen_height / 2
x_change = 0
y_change = 0

block_size = 10
speed = 30

while not game_exit:

while game_over:
screen.fill(white)
message_to_screen("游戏结束,按C重新开始,按Q退出", black)
pygame.display.update()

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()

for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = block_size
x_change = 0

if x >= screen_width or x < 0 or y >= screen_height or y < 0:
game_over = True

x += x_change
y += y_change

screen.fill(white)
pygame.draw.rect(screen, black, [x, y, block_size, block_size])
pygame.display.update()

clock.tick(speed)

pygame.quit()

game_loop()
```
221381
领取福利

微信扫码领取福利

微信扫码分享