使用python+pygame编写一个24点计算的小游戏
时间: 2024-04-15 20:28:20 浏览: 177
当然可以!下面是一个使用Python和Pygame编写的24点计算小游戏的示例代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口尺寸
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("24点计算游戏")
# 设置字体
font = pygame.font.SysFont(None, 48)
def generate_numbers():
"""随机生成四个数字"""
numbers = []
for _ in range(4):
numbers.append(random.randint(1, 9)) # 生成1到9之间的随机数
return numbers
def calculate_result(numbers, operators):
"""根据给定的操作符计算结果"""
expression = ""
for i in range(4):
expression += str(numbers[i])
if i < 3:
expression += operators[i]
try:
result = eval(expression) # 使用eval函数计算表达式的结果
return result
except ZeroDivisionError:
return None
def draw_numbers(numbers):
"""绘制四个数字"""
for i in range(4):
text = font.render(str(numbers[i]), True, (255, 255, 255))
text_rect = text.get_rect(center=(WINDOW_WIDTH // 5 * (i + 1), WINDOW_HEIGHT // 2))
window.blit(text, text_rect)
def draw_operators(operators):
"""绘制三个运算符"""
for i in range(3):
text = font.render(operators[i], True, (255, 255, 255))
text_rect = text.get_rect(center=(WINDOW_WIDTH // 5 * (i + 2), WINDOW_HEIGHT // 2))
window.blit(text, text_rect)
def draw_result(result):
"""绘制计算结果"""
if result is not None:
text = font.render("= " + str(result), True, (255, 255, 255))
text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
window.blit(text, text_rect)
def main():
numbers = generate_numbers()
operators = ['+', '-', '*', '/']
result = None
running = True
while running:
window.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
draw_numbers(numbers)
draw_operators(operators)
draw_result(result)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
```
这个小游戏会在窗口中随机生成四个数字,并随机选择三个运算符。你需要尝试组合这些数字和运算符,使得计算结果等于24。祝你玩得开心!
阅读全文