目录:
1,猜拳游戏
2,俄罗斯方块
1,"猜拳游戏"
先用最基础的也是比较经典,猜拳游戏,源码如下:
import random
b = random.randint(0,2)
print(b)
#b = int(b)
a = input("输入你的数字:")
a = int(a)
if a > 3:
print("数字错误")
elif a == b :
print("平手了")
elif a > b :
print("你输了")
else:
print("你赢了")
pass
这个只要有一点Python基础的人,都看得懂。
2,"俄罗斯方块"
这个需要用到“pygame”模块,需要下载,这个安装并添加模块,pip就行了。文章来源:https://www.toymoban.com/news/detail-602548.html
源码如下:文章来源地址https://www.toymoban.com/news/detail-602548.html
import sys
import time
import pygame
from pygame.localsimport *
import blocks
SIZE =30 # 每个小方格大小
BLOCK_HEIGHT =25 # 游戏区高度
BLOCK_WIDTH =10 # 游戏区宽度
BORDER_WIDTH =4 # 游戏区边框宽度
BORDER_COLOR = (40, 40, 200)# 游戏区边框颜色
SCREEN_WIDTH = SIZE * (BLOCK_WIDTH +5)# 游戏屏幕的宽
SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT# 游戏屏幕的高
BG_COLOR = (40, 40, 60)# 背景色
BLOCK_COLOR = (20, 128, 200)
BLACK = (0, 0, 0)
RED = (200, 30, 30)# GAME OVER 的字体颜色
# 画背景
def _draw_background(screen):
# 填充背景色
screen.fill(BG_COLOR)
# 画游戏区域分隔线
pygame.draw.line(screen, BORDER_COLOR,
(SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
(SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)
# 画网格线
```python
def _draw_gridlines(screen):
# 画网格线 竖线
for x in range(BLOCK_WIDTH):
pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
# 画网格线 横线
for y in range(BLOCK_HEIGHT):
pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)
def _draw_game_area(screen, game_area):
if game_area:
for i, row in enumerate(game_area):
for j, cell in enumerate(row):
if cell != '.':
pygame.draw.rect(screen, BLOCK_COLOR, (j * SIZE, i * SIZE, SIZE,
SIZE), 0)
def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
if block:
for i in range(block.start_pos.Y, block.end_pos.Y + 1):
for j in range(block.start_pos.X, block.end_pos.X + 1):
if block.template[i][j] != '.':
pygame.draw.rect(screen, BLOCK_COLOR,
(offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)
def _draw_info(screen, font, pos_x, font_height, score):
print_text(screen, font, pos_x, 10, f'得分: ')
print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个:')
if __name__ == '__main__':
main()
到了这里,关于用Python写一个游戏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!