来源:小编 更新:2025-01-28 12:17:50
用手机看
哎呀呀,小伙伴们,你们有没有想过,用Python写个游戏,那感觉简直就像是在电脑上种了个小花园,看着它一点点长大,多有意思啊!今天,我就要带你们走进这个奇妙的世界,一起探索那些有趣的Python游戏源代码,让你在编程的道路上越走越远,越玩越开心!
还记得小时候玩过的猜数字游戏吗?现在,用Python也能轻松实现!这里,我就给你分享一个简单的猜数字游戏源代码,让你感受一下Python的魔力。
```python
import random
print(\欢迎来到猜数字游戏!\)
print(\你需要猜一个 1 到 100 之间的数字。\)
number = random.randint(1, 100)
guess = None
attempts = 0
while guess != number:
guess = int(input(\请输入你猜的数字:\))
attempts += 1
if guess < number:
print(\猜的数字太小了,请再试一次。\)
elif guess > number:
print(\猜的数字太大了,请再试一次。\)
else:
print(\恭喜你,猜对了!\)
print(f\你一共尝试了 {attempts} 次。\)
这个游戏是不是很简单?其实,Python游戏源代码的魅力就在这里,简单易懂,却又充满乐趣。
当你对猜数字游戏有了初步的了解后,是时候挑战更高难度的游戏了。比如,贪吃蛇!这是一个经典的街机游戏,用Python实现起来也是相当有趣的。
```python
import pygame
import time
import random
pygame.init()
设置屏幕大小
width, height = 600, 400
screen = pygame.display.set_mode((width, height))
设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
设置贪吃蛇的初始位置和大小
snake_block = 10
snake_speed = 15
snake_list = []
snake_length = 1
设置食物的初始位置和大小
foodx = round(random.randrange(0, width - snake_block) / 10.0) 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) 10.0
设置游戏循环
clock = pygame.time.Clock()
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 3])
def gameLoop():
game_over = False
game_close = False
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
while not game_over:
while game_close == True:
screen.fill(blue)
message(\你输了!按Q退出,按C重新开始\, red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill(blue)
pygame.draw.rect(screen, green, [foodx, foody, snake_block, snake_block])
snake_head = []
snake_head.append(x1)
snake_head.append(y