小游戏代码大全可复制python
时间: 2023-08-25 17:07:56 浏览: 369
基于Python的小游戏代码
以下是一个简单的 Python 小游戏代码集合,你可以根据自己的兴趣选择其中一个进行复制和运行。注意,这些代码仅供学习和娱乐使用。
1. 猜数字游戏
```python
import random
num = random.randint(1, 10)
while True:
guess = int(input("请猜一个数字(1-10):"))
if guess == num:
print("恭喜你,猜对了!")
break
elif guess < num:
print("猜小了,再试一次。")
else:
print("猜大了,再试一次。")
```
2. 石头、剪刀、布游戏
```python
import random
print("欢迎来到石头、剪刀、布游戏!")
print("请出拳:1.石头 2.剪刀 3.布")
while True:
player = int(input("你的选择:"))
computer = random.randint(1, 3)
if player == computer:
print("平局!")
elif (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("你赢了!")
else:
print("你输了!")
```
3. 猜单词游戏
```python
import random
words = ["apple", "banana", "orange", "pear", "peach"]
word = random.choice(words)
hint = word[0] + word[-1]
print("欢迎来到猜单词游戏!")
print("提示:单词的第一个字母是 {},最后一个字母是 {}。".format(hint[0], hint[1]))
while True:
guess = input("请猜一个单词:")
if guess == word:
print("恭喜你,猜对了!")
break
else:
print("猜错了,再试一次。")
```
4. 打飞机游戏
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义窗口大小
width = 640
height = 480
# 创建窗口
screen = pygame.display.set_mode((width, height))
# 加载图片
player_img = pygame.image.load("player.png")
enemy_img = pygame.image.load("enemy.png")
bullet_img = pygame.image.load("bullet.png")
# 设置游戏标题
pygame.display.set_caption("打飞机游戏")
# 定义游戏角色类
class Actor:
def __init__(self, x, y, img):
self.x = x
self.y = y
self.img = img
self.width = img.get_width()
self.height = img.get_height()
def draw(self):
screen.blit(self.img, (self.x, self.y))
# 定义玩家类
class Player(Actor):
def move_left(self):
self.x -= 5
def move_right(self):
self.x += 5
def fire(self):
bullet = Bullet(self.x + self.width // 2, self.y)
bullets.append(bullet)
# 定义敌人类
class Enemy(Actor):
def move_down(self):
self.y += 5
# 定义子弹类
class Bullet(Actor):
def move_up(self):
self.y -= 10
# 创建游戏角色
player = Player(width // 2 - player_img.get_width() // 2, height - player_img.get_height(), player_img)
enemies = []
bullets = []
# 游戏循环
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_LEFT:
player.move_left()
elif event.key == pygame.K_RIGHT:
player.move_right()
elif event.key == pygame.K_SPACE:
player.fire()
# 绘制背景
screen.fill((255, 255, 255))
# 绘制玩家
player.draw()
# 绘制敌人
if len(enemies) < 10:
enemy = Enemy(random.randint(0, width - enemy_img.get_width()), -enemy_img.get_height(), enemy_img)
enemies.append(enemy)
for enemy in enemies:
enemy.move_down()
enemy.draw()
# 绘制子弹
for bullet in bullets:
bullet.move_up()
bullet.draw()
# 碰撞检测
for bullet in bullets:
for enemy in enemies:
if bullet.x >= enemy.x and bullet.x <= enemy.x + enemy.width and bullet.y >= enemy.y and bullet.y <= enemy.y + enemy.height:
bullets.remove(bullet)
enemies.remove(enemy)
# 更新屏幕
pygame.display.update()
# 结束游戏
pygame.quit()
```
这些代码只是小游戏的入门级别,如果你想尝试更复杂的游戏,可以从这里开始学习。
阅读全文