Lv.1
在 【Python作品分享】贪吃蛇【作品秀】 中回复
importpygame importsys importtime importrandom frompygame.localsimport* #定义颜色变量 BLUE_COLOR=pygame.Color(0,0,255) BLACK_COLOR=pygame.Color(0,0,0) WHITE_COLOR=pygame.Color(255,255,255) GREY_COLOR=pygame.Color(150,150,150) #定义游戏结束函数 defgame_over(play_surface): game_over_font=pygame.font.Font('arial.ttf',72) game_over_surf=game_over_font.render('GameOver',True,GREY_COLOR) game_over_rect=game_over_surf.get_rect() game_over_rect.midtop=(320,10) play_surface.blit(game_over_surf,game_over_rect) pygame.display.flip() time.sleep(3)#等待3秒后结束游戏 pygame.quit() sys.exit() #定义主函数 defmain(): #初始化pygame pygame.init() fps_clock=pygame.time.Clock() #创建pygame显示层 play_surface=pygame.display.set_mode((喵0,480)) pygame.display.set_caption('RaspberrySnake') #初始化变量 snake_position=[100,100] snake_segments=[[100,100],[80,100],[60,100]] raspberry_position=[300,300] raspberry_spawned=True direction='RIGHT' score=0 whileTrue: #检测pygame事件 foreventinpygame.event.get(): ifevent.type==QUIT: pygame.quit() sys.exit() elifevent.type==KEYDOWN: #判断键盘事件 ifevent.keyin[K_RIGHT,ord('d')]anddirection!='LEFT': direction='RIGHT' elifevent.keyin[K_LEFT,ord('a')]anddirection!='RIGHT': direction='LEFT' elifevent.keyin[K_UP,ord('w')]anddirection!='DOWN': direction='UP' elifevent.keyin[K_DOWN,ord('s')]anddirection!='UP': direction='DOWN' elifevent.key==K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT)) #根据方向移动蛇头的坐标 ifdirection=='RIGHT': snake_position[0]+=20 elifdirection=='LEFT': snake_position[0]-=20 elifdirection=='UP': snake_position[1]-=20 elifdirection=='DOWN': snake_position[1]+=20 #增加蛇的长度 snake_segments.insert(0,list(snake_position)) #判断是否吃掉了树莓 ifsnake_position==raspberry_position: score+=1#增加得分 raspberry_spawned=False else: snake_segments.pop()#移除蛇尾 #重新生成树莓 ifnotraspberry_spawned: raspberry_position=[random.randrange(1,32)*20,random.randrange(1,24)*20] raspberry_spawned=True #绘制pygame显示层 play_surface.fill(BLACK_COLOR) forindex,positioninenumerate(snake_segments): pygame.draw.rect(play_surface,WHITE_COLORifindex==0elseBLUE_COLOR,Rect(position[0],position[1],20,20)) pygame.draw.rect(play_surface,GREY_COLOR,Rect(raspberry_position[0],raspberry_position[1],20,20)) #更新显示 pygame.display.flip() #判断是否喵 ifsnake_position[0]>620orsnake_position[0]<0orsnake_position[1]>460orsnake_position[1]<0: game_over(play_surface) forsnake_bodyinsnake_segments[1:]: ifsnake_position==snake_body: game_over(play_surface) #控制游戏速度 fps_clock.tick(10)#增加游戏速度 if__name__=="__main__": main()改进点总结: 变量命名规范:将变量命名改为全大写以符合常量命名规范。 得分机制:添加了得分机制,吃掉树莓后得分加1。 蛇的颜色变化:蛇头与蛇身使用不同颜色以便于识别。 游戏速度:增加了游戏速度(fps)以提高游戏的可玩性。 代码结构优化:使用更清晰的条件判断和简化的代码结构,提高可读性。 希望这个改进后的版本能让你的蛇游戏更加有趣!
2024-08-24T19:10:45 点赞:0
在 【Python作品分享】贪吃蛇【作品秀】 中回复
importpygame importsys importtime importrandom frompygame.localsimport* #定义颜色变量 BLUE_COLOR=pygame.Color(0,0,255) BLACK_COLOR=pygame.Color(0,0,0) WHITE_COLOR=pygame.Color(255,255,255) GREY_COLOR=pygame.Color(150,150,150) #定义游戏结束函数 defgame_over(play_surface): game_over_font=pygame.font.Font('arial.ttf',72) game_over_surf=game_over_font.render('GameOver',True,GREY_COLOR) game_over_rect=game_over_surf.get_rect() game_over_rect.midtop=(320,10) play_surface.blit(game_over_surf,game_over_rect) pygame.display.flip() time.sleep(3)#等待3秒后结束游戏 pygame.quit() sys.exit() #定义主函数 defmain(): #初始化pygame pygame.init() fps_clock=pygame.time.Clock() #创建pygame显示层 play_surface=pygame.display.set_mode((喵0,480)) pygame.display.set_caption('RaspberrySnake') #初始化变量 snake_position=[100,100] snake_segments=[[100,100],[80,100],[60,100]] raspberry_position=[300,300] raspberry_spawned=True direction='RIGHT' score=0 whileTrue: #检测pygame事件 foreventinpygame.event.get(): ifevent.type==QUIT: pygame.quit() sys.exit() elifevent.type==KEYDOWN: #判断键盘事件 ifevent.keyin[K_RIGHT,ord('d')]anddirection!='LEFT': direction='RIGHT' elifevent.keyin[K_LEFT,ord('a')]anddirection!='RIGHT': direction='LEFT' elifevent.keyin[K_UP,ord('w')]anddirection!='DOWN': direction='UP' elifevent.keyin[K_DOWN,ord('s')]anddirection!='UP': direction='DOWN' elifevent.key==K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT)) #根据方向移动蛇头的坐标 ifdirection=='RIGHT': snake_position[0]+=20 elifdirection=='LEFT': snake_position[0]-=20 elifdirection=='UP': snake_position[1]-=20 elifdirection=='DOWN': snake_position[1]+=20 #增加蛇的长度 snake_segments.insert(0,list(snake_position)) #判断是否吃掉了树莓 ifsnake_position==raspberry_position: score+=1#增加得分 raspberry_spawned=False else: snake_segments.pop()#移除蛇尾 #重新生成树莓 ifnotraspberry_spawned: raspberry_position=[random.randrange(1,32)*20,random.randrange(1,24)*20] raspberry_spawned=True #绘制pygame显示层 play_surface.fill(BLACK_COLOR) forindex,positioninenumerate(snake_segments): pygame.draw.rect(play_surface,WHITE_COLORifindex==0elseBLUE_COLOR,Rect(position[0],position[1],20,20)) pygame.draw.rect(play_surface,GREY_COLOR,Rect(raspberry_position[0],raspberry_position[1],20,20)) #更新显示 pygame.display.flip() #判断是否喵 ifsnake_position[0]>620orsnake_position[0]<0orsnake_position[1]>460orsnake_position[1]<0: game_over(play_surface) forsnake_bodyinsnake_segments[1:]: ifsnake_position==snake_body: game_over(play_surface) #控制游戏速度 fps_clock.tick(10)#增加游戏速度 if__name__=="__main__": main()
2024-08-24T19:11:14 点赞:0
在 【Python作品分享】贪吃蛇【作品秀】 中回复
importpygame importsys importtime importrandom frompygame.localsimport* #定义颜色变量 BLUE_COLOR=pygame.Color(0,0,255) BLACK_COLOR=pygame.Color(0,0,0) WHITE_COLOR=pygame.Color(255,255,255) GREY_COLOR=pygame.Color(150,150,150) #定义游戏结束函数 defgame_over(play_surface): game_over_font=pygame.font.Font('arial.ttf',72) game_over_surf=game_over_font.render('GameOver',True,GREY_COLOR) game_over_rect=game_over_surf.get_rect() game_over_rect.midtop=(320,10) play_surface.blit(game_over_surf,game_over_rect) pygame.display.flip() time.sleep(3)#等待3秒后结束游戏 pygame.quit() sys.exit() #定义主函数 defmain(): #初始化pygame pygame.init() fps_clock=pygame.time.Clock() #创建pygame显示层 play_surface=pygame.display.set_mode((喵0,480)) pygame.display.set_caption('RaspberrySnake') #初始化变量 snake_position=[100,100] snake_segments=[[100,100],[80,100],[60,100]] raspberry_position=[300,300] raspberry_spawned=True direction='RIGHT' score=0 whileTrue: #检测pygame事件 foreventinpygame.event.get(): ifevent.type==QUIT: pygame.quit() sys.exit() elifevent.type==KEYDOWN: #判断键盘事件 ifevent.keyin[K_RIGHT,ord('d')]anddirection!='LEFT': direction='RIGHT' elifevent.keyin[K_LEFT,ord('a')]anddirection!='RIGHT': direction='LEFT' elifevent.keyin[K_UP,ord('w')]anddirection!='DOWN': direction='UP' elifevent.keyin[K_DOWN,ord('s')]anddirection!='UP': direction='DOWN' elifevent.key==K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT)) #根据方向移动蛇头的坐标 ifdirection=='RIGHT': snake_position[0]+=20 elifdirection=='LEFT': snake_position[0]-=20 elifdirection=='UP': snake_position[1]-=20 elifdirection=='DOWN': snake_position[1]+=20 #增加蛇的长度 snake_segments.insert(0,list(snake_position)) #判断是否吃掉了树莓 ifsnake_position==raspberry_position: score+=1#增加得分 raspberry_spawned=False else: snake_segments.pop()#移除蛇尾 #重新生成树莓 ifnotraspberry_spawned: raspberry_position=[random.randrange(1,32)*20,random.randrange(1,24)*20] raspberry_spawned=True #绘制pygame显示层 play_surface.fill(BLACK_COLOR) forindex,positioninenumerate(snake_segments): pygame.draw.rect(play_surface,WHITE_COLORifindex==0elseBLUE_COLOR,Rect(position[0],position[1],20,20)) pygame.draw.rect(play_surface,GREY_COLOR,Rect(raspberry_position[0],raspberry_position[1],20,20)) #更新显示 pygame.display.flip() #判断是否喵 ifsnake_position[0]>620orsnake_position[0]<0orsnake_position[1]>460orsnake_position[1]<0: game_over(play_surface) forsnake_bodyinsnake_segments[1:]: ifsnake_position==snake_body: game_over(play_surface) #控制游戏速度 fps_clock.tick(10)#增加游戏速度 if__name__=="__main__": main()
2024-08-24T19:11:38 点赞:0
在 3D喵盲盒 中回复
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
# 定义立方体的顶点和边
vertices = [
(1, -1, -1),
(1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, -1, 1),
(-1, 1, 1)
]
edges = [
(0, 1),
(1, 2),
(2, 3),
(3, 0),
(4, 5),
(5, 6),
(6, 7),
(7, 4),
(0, 4),
(1, 5),
(2, 7),
(3, 6)
]
def draw_cube():
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(vertices[vertex])
glEnd()
def main():
# 初始化Pygame
pygame.init()
# 设置窗口尺寸
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
# 设置视角
gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)
glTranslatef(0.0, 0.0, -5)
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
# 清屏
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# 旋转立方体
glRotatef(1, 1, 1, 0)
draw_cube()
# 更新显示
pygame.display.flip()
pygame.time.wait(10)
if __name__ == "__main__":
main() 注意事项
PyOpenGL和Pygame创建3D图形的性能相对较低,这种简单的实现适合学习和实验。如果要创建更复杂的3D模型和动画,建议使用更专业的3D图形引擎如Panda3D或Blender的Python API。2024-08-25T14:00:04 点赞:0
在 【Python作品分享】我的世界python3D版【作品秀】 中回复
def move_picture(player_picture_path, bj_picture_path, window_length, window_wide, window_name, player_x, player_y, player_speed_x, player_speed_y):
import pygame as pg
import sys
pg.init()
# 设置窗口
windows = pg.display.set_mode((window_length, window_wide))
pg.display.set_caption(window_name)
# 加载背景图片
bj = pg.image.load(bj_picture_path)
# 玩家类
class Player:
def __init__(self):
self.px = player_x
self.py = player_y
self.player_image = pg.image.load(player_picture_path)
self.player_rect = self.player_image.get_rect()
self.player_rect.topleft = (self.px, self.py)
def move(self):
pressed_keys = pg.key.get_pressed()
if pressed_keys[pg.K_UP]:
self.py -= player_speed_y # 修改为上下移动的速度
if pressed_keys[pg.K_DOWN]:
self.py += player_speed_y
if pressed_keys[pg.K_LEFT]:
self.px -= player_speed_x # 修改为左右移动的速度
if pressed_keys[pg.K_RIGHT]:
self.px += player_speed_x
# 确保玩家不会移出窗口边界
self.px = max(0, min(self.px, window_length - self.player_rect.width))
self.py = max(0, min(self.py, window_wide - self.player_rect.height))
def res_p(self):
# 在新位置绘制玩家
windows.blit(self.player_image, (self.px, self.py))
player = Player()
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
# 绘制背景
windows.blit(bj, (0, 0))
# 更新玩家位置并绘制
player.move()
player.res_p()
# 更新显示
pg.display.update()
# 示例调用(确保路径正确)
# move_picture('player.png', 'background.jpg', 800, 600, 'Game Window', 100, 100, 5, 5) 代码说明
player_speed_y和player_speed_x,确保移动方向与速度相对应。self.px和self.py的边界检查,以确保玩家不会移出窗口范围。2024-08-25T14:07:48 点赞:0
在 【Python作品分享】PY关机程序 中回复
from tkinter import *
from tkinter import messagebox
import os
def shutdown():
response = messagebox.askokcancel("关闭计算机", "你确定要关闭计算机?")
if response:
os.system("shutdown /s /t 1")
def restart():
response = messagebox.askokcancel("重启计算机", "你确定要重启计算机?")
if response:
os.system("shutdown /r /t 1")
def logout():
response = messagebox.askokcancel("注销计算机", "你确定要注销计算机?")
if response:
os.system("shutdown /l")
master = Tk()
master.title('系统工具')
master.geometry('400x200+600+300') # 增大窗口尺寸
master.configure(bg='light grey')
# 增加标题标签
title_label = Label(master, text="请选择操作", font=("Arial", 14), bg='light grey')
title_label.pack(pady=10)
# 使用Frame来组织按钮
button_frame = Frame(master, bg='light grey')
button_frame.pack(pady=20)
bt1 = Button(button_frame, text="关闭计算机", width=15, command=shutdown)
bt1.grid(row=0, column=0, padx=10)
bt2 = Button(button_frame, text="重启计算机", width=15, command=restart)
bt2.grid(row=0, column=1, padx=10)
bt3 = Button(button_frame, text="注销计算机", width=15, command=logout)
bt3.grid(row=0, column=2, padx=10)
mainloop()
修改点说明:
Frame 来组织按钮,使布局更加整洁。2024-08-25T14:15:34 点赞:0
在 ### Python递归函数教程 中回复
def factorial(n):
if n == 0 or n == 1: # 基本情况
return 1
else:
return n * factorial(n - 1) # 递归调用
# 测试
num = 5
print(f"{num}! = {factorial(num)}")2024-08-25T14:17:15 点赞:0
在 ### Python递归函数教程 中回复
def fibonacci(n):
if n <= 0: # 基本情况
return 0
elif n == 1: # 基本情况
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) # 递归调用
# 测试
num = 6
print(f"Fibonacci number at position {num} is {fibonacci(num)}")2024-08-25T14:17:35 点赞:0
在 ### Python递归函数教程 中回复
def sum_list(lst):
if not lst: # 基本情况,空列表的总和为 0
return 0
else:
return lst[0] + sum_list(lst[1:]) # 递归调用
# 测试
numbers = [1, 2, 3, 4, 5]
print(f"Sum of {numbers} is {sum_list(numbers)}")2024-08-25T14:17:59 点赞:0
在 ### Python递归函数教程 中回复
def reverse_string(s):
if len(s) == 0: # 基本情况,空字符串
return s
else:
return s[-1] + reverse_string(s[:-1]) # 递归调用
# 测试
text = "hello"
print(f"Reversed string of '{text}' is '{reverse_string(text)}'")2024-08-25T14:18:17 点赞:0
在 【Python作品分享】666【求助帖】 中回复
import random
def 喵():
# 随机选择一个惩罚
punishments = [
'做5个深蹲',
'大喊一声我是喵',
'对左边的人说喵你~~',
'如果你是张子晨,请下楼',
'对右边的人说喵你~~',
'你很幸运,没有惩罚'
]
punishment = random.choice(punishments)
print(f'请接受惩罚: {punishment}')
def guess_number_game(num_players):
lower_bound = 1
upper_bound = 100
target_number = random.randint(lower_bound, upper_bound)
print(f'我已经在 {lower_bound} — {upper_bound} 随机选择了一个数,开始游戏!!!')
current_player = 1
while True:
print(f'请 {current_player} 号玩家说数')
# 获取玩家输入
while True:
try:
guess = int(input())
if guess < lower_bound or guess > upper_bound:
print(f'请输入一个在 {lower_bound} 和 {upper_bound} 之间的数字!')
else:
break
except ValueError:
print('无效输入,请输入一个数字!')
# 判断猜测结果
if guess == target_number:
print('恭喜你,猜对了!')
break
else:
print('猜错了!')
if guess < target_number:
lower_bound = guess + 1
print(f'范围调整为: {lower_bound} - {upper_bound}')
else:
upper_bound = guess - 1
print(f'范围调整为: {lower_bound} - {upper_bound}')
print('请接受惩罚')
喵()
# 切换到下一个玩家
current_player += 1
if current_player > num_players:
current_player = 1
if __name__ == '__main__':
print('欢迎来到数字猜谜游戏!')
while True:
try:
num_players = int(input('请输入人数: '))
if num_players < 1:
print('人数必须至少为1!')
else:
break
except ValueError:
print('无效输入,请输入一个数字!')
guess_number_game(num_players) 改进说明:
guess_number_game 函数中,使主程序更简洁。2024-08-25T14:20:47 点赞:0
在 【Python作品分享】python调研【作品秀】 中回复
importtime defloading_animation(duration=1,dots=6): """显示加载动画""" print('加载中',end='',flush=True) for_inrange(dots): time.sleep(duration) print('.',end='',flush=True) print()#换行 defprint_user_info(name,age,hobby,goal): """打印用户信息""" print('你的名字:',name) print('你的年龄:',age) print('你的爱好:',hobby) print('未来目标:',goal) defmain(): print('你好,欢迎来到Python,请先完成以下调查问卷') name=input('你的名字:') age=input('你的年龄:') hobby=input('你的爱好:') goal=input('未来目标:') loading_animation()#显示加载动画 #模拟打印信息 print('打印中',end='',flush=True) loading_animation() #打印用户信息 print_user_info(name,age,hobby,goal) print("已发送至Python中心!") print('恭喜你完成问卷调查,问卷结果将在10分钟后送达您的电脑!') print('(如果没有,请检查您的网络连接。)') if__name__=='__main__': main()改进说明: loading_animation 函数:这个函数处理加载动画的逻辑,减少了代码重复。 print_user_info 函数:专门用于打印用户的调查信息,使主程序更清晰。 主函数:所有的逻辑都放在 main() 函数内,方便管理和调用。 这种结构使得代码更加模块化,便于未来的扩展和维护。你可以根据需要进一步修改和添加功能。
2024-08-25T14:22:10 点赞:0
在 【Python作品分享】python调研【作品秀】 中回复
importtime defloading_animation(duration=1,dots=6): """显示加载动画""" print('加载中',end='',flush=True) for_inrange(dots): time.sleep(duration) print('.',end='',flush=True) print()#换行 defprint_user_info(name,age,hobby,goal): """打印用户信息""" print('你的名字:',name) print('你的年龄:',age) print('你的爱好:',hobby) print('未来目标:',goal) defmain(): print('你好,欢迎来到Python,请先完成以下调查问卷') name=input('你的名字:') age=input('你的年龄:') hobby=input('你的爱好:') goal=input('未来目标:') loading_animation()#显示加载动画 #模拟打印信息 print('打印中',end='',flush=True) loading_animation() #打印用户信息 print_user_info(name,age,hobby,goal) print("已发送至Python中心!") print('恭喜你完成问卷调查,问卷结果将在10分钟后送达您的电脑!') print('(如果没有,请检查您的网络连接。)') if__name__=='__main__': main()
2024-08-25T14:22:45 点赞:0
在 【Python作品分享】深渊历险记【作品秀】 中回复
import pgzrun
import random
WIDTH = 500
HEIGHT = 700
dudu = Actor('嘟嘟')
score = 0
music.play('背景音乐')
direction = 3
bricks = []
for i in range(5):
n = random.randint(1, 4)
b = Actor('踏板' + str(n))
min_x = b.width // 2
max_x = WIDTH - b.width // 2
b.x = random.randint(min_x, max_x)
b.y = 140 * (i + 1)
bricks.append(b)
if i == 2:
dudu.x = b.x
dudu.bottom = b.top
b.image = '踏板1'
def draw():
global score
screen.blit('背景', [0, 0])
dudu.draw()
for brick in bricks:
brick.draw()
screen.draw.text(f'Score: {score}', (20, 10))
if dudu.image == '嘟嘟哭':
screen.draw.text('Game Over! Press SPACE to restart.', (WIDTH // 2 - 120, HEIGHT // 2), color='red')
def update():
global score, direction
if dudu.image == '嘟嘟':
score += 1
on_brick = 0
for b in bricks:
b.y -= 3
if b.image == '踏板2':
b.x += direction
if b.right >= WIDTH:
direction = -3
elif b.left <= 0:
direction = 3
if b.y < 0:
n = random.randint(1, 4)
b.image = '踏板' + str(n)
b.y = HEIGHT
min_x = b.width // 2
max_x = WIDTH - b.width // 2
b.x = random.randint(min_x, max_x)
for b in bricks:
if dudu.colliderect(b) and dudu.bottom < b.bottom:
dudu.bottom = b.top
on_brick = 1
if b.image == '踏板4':
dudu.image = '嘟嘟哭'
if b.image == '踏板2':
dudu.x += direction
if dudu.right >= WIDTH:
direction = -3
elif dudu.left <= 0:
direction = 3
if on_brick == 0:
dudu.y += 8
if dudu.bottom > HEIGHT:
dudu.image = '嘟嘟哭'
if keyboard.left and dudu.left > 0:
dudu.x -= 5
if keyboard.right and dudu.right < WIDTH:
dudu.x += 5
if dudu.image == '嘟嘟哭':
music.stop()
def on_key_down(key):
if key == keys.SPACE and dudu.image == '嘟嘟哭':
restart_game()
def restart_game():
global score, bricks
music.play('背景音乐')
dudu.image = '嘟嘟'
dudu.y = HEIGHT // 2
score = 0
bricks.clear()
for i in range(5):
n = random.randint(1, 4)
b = Actor('踏板' + str(n))
min_x = b.width // 2
max_x = WIDTH - b.width // 2
b.x = random.randint(min_x, max_x)
b.y = 140 * (i + 1)
bricks.append(b)
if i == 2:
dudu.x = b.x
dudu.bottom = b.top
b.image = '踏板1'
pgzrun.go() 修改内容:
2024-08-25T14:27:57 点赞:0
在 玩具熊午夜后宫-姐妹地点Python代码(全部自编) 中回复
扩展游戏循环:
创建检查事件(如退出游戏)、更新游戏状态和渲染游戏图形的主循环。例如:扩展游戏循环:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game state
mouse.update()
room.update()
button.update()
door.update()
# Render everything
screen.fill((0, 0, 0)) # Clear the screen
room.update()
mouse.update()
button.update()
door.update()
pygame.display.flip() # Update the full display surface to the screen2024-08-25T14:33:54 点赞:0
在 【Python作品分享】魔鬼.猜数字【作品秀】 中回复
from random import randint
from time import sleep
def main():
print('Hi,菜鸟!我是作者。')
sleep(1)
print('欢迎来到《魔鬼.猜数字》')
sleep(1)
print('来挑战你的直觉吧!')
sleep(1)
# 难度选择
print('选择难度:1. 简单 2. 一般 3. 中等 4. 魔鬼')
difficulty = input('请输入难度(1-4),或输入q退出:')
if difficulty.lower() == 'q':
print('谢谢参与!再见!')
return
try:
b = int(difficulty)
if b < 1 or b > 4:
raise ValueError("输入无效,难度必须在1到4之间。")
except ValueError:
print("输入无效,请输入数字1到4或q退出。")
return
# 设置随机数范围
if b == 1:
number_range = 10000
print('切,还以为你多厉害呢!')
elif b == 2:
number_range = 10000000
print('原来你这么没实力!')
elif b == 3:
number_range = 1000000000
print('再练十年吧!')
else:
number_range = 喵0
print('你行不行啊菜鸟?')
the_number = randint(1, number_range)
attempts = 0
while True:
guess = input(f'请猜一个1到{number_range}之间的秘密数字(输入q退出):')
if guess.lower() == 'q':
print('谢谢参与!再见!')
break
try:
guess = int(guess)
except ValueError:
print("请输入一个有效的数字!")
continue
attempts += 1
if guess > the_number:
print(f'{guess} 猜大了,请再来一次!')
elif guess < the_number:
print(f'{guess} 猜小了,请再来一次!')
else:
print(f'{guess} 就是秘密数字!恭喜你菜鸟!')
print(f'你猜了 {attempts} 次, 太逊了!')
break
# 给出提示
if attempts in [10, 20, 30, 40]:
hints = {
10: '放弃吧!都猜十次了。',
20: '别试了,你不行的!',
30: '菜就多练!',
40: '认命吧!不陪你玩了,自己玩吧。'
}
print(hints[attempts])
sleep(1)
if __name__ == "__main__":
main()
主要改进点
try-except 来处理用户输入,确保玩家输入有效的数字。main() 函数中,使得代码更整洁。q 退出游戏,提升用户体验。通过这些改进,你的游戏将更加完善、易用和有趣。希望你喜欢这个修改版本!
2024-08-25T14:35:35 点赞:1
在 【Python作品分享】“贱”谍过家家【作品秀】 中回复
import random
import time
# 词汇列表
word_list = [
"案板", "澳币", "癌病", "埃博拉", "阿波罗", "爱车", "艾喵", "鹌鹑", "哀辞", "鹌鹑蛋",
"昂刺鱼", "矮凳", "矮冬瓜", "爱德华", "暗电流", "爱妃", "暗房", "案犯", "氨酚", "阿凡达", "矮柜",
"暗号", "阿华田", "案件", "暗礁", "安康鱼", "奥利奥", "喵膏", "安眠曲", "安慕希", "喵",
"按钮", "暗器"
]
# 加载动画
def loading_animation():
for _ in range(3):
for dots in range(7):
print("正在加载中" + "." * dots)
time.sleep(0.3)
print("\033c", end="") # 清屏
print("加载成功")
# 主游戏逻辑
def game():
loading_animation()
word = random.choice(word_list)
n = int(input("人数:"))
rad = random.randint(1, n)
for i in range(1, n + 1):
if i == rad:
io = input(f"是{rad}号吗:(输入yes/no) ")
if io.lower() == "yes":
print(f"{i}: 无")
io = input("看好了吗:(输入yes/no) ")
if io.lower() == "yes":
print("\033c", end="")
else:
io = input(f"是{i}号吗:(输入yes/no) ")
if io.lower() == "yes":
print(f"{i}: {word}")
io = input("看好了吗:(输入yes/no) ")
if io.lower() == "yes":
print("\033c", end="")
print("开始询问!")
input("询问好了吗:(输入yes/no) ")
print("开始投票!")
maxtou = 0
idx = 0
for i in range(1, n + 1):
tou = int(input(f"投{i}的人:"))
if tou > maxtou:
maxtou = tou
idx = i
print("开始询问!")
input("询问好了吗:(输入yes/no) ")
if maxtou == n - 1 and idx == rad:
print("卧底失败")
else:
print("卧底胜利")
# 启动游戏
if __name__ == "__main__":
game() 修改说明
功能模块化:将加载动画部分提取为 loading_animation 函数,提高了代码的结构清晰度。
循环的简化:用 for dots in range(7) 来控制加载动画的点数,减少了重复代码。
输入大小写处理:使用 io.lower() 来处理用户输入,这样用户可以输入任意大小写的 yes 或 no。
代码格式:改进了代码格式和可读性,保持一致的缩进和空行。
主程序保护:使用 if __name__ == "__main__": 来保护主程序,使其仅在直接运行时执行,不会在作为模块导入时执行。
通过这些修改,代码变得更加简洁和易于维护,同时保留了原有的功能。如果您有其他特定需求或进一步的问题,请随时告诉我!
2024-08-25T14:38:32 点赞:0
在 【Python作品分享】喵原格子(走格子小游戏) 中回复
import turtle
import copy
# -----------------------------------------------------------------
# 1.基本信息区,放置游戏相关的一些信息
size = 70
'''
0-空 1-墙壁 2-通道 3-目标 4-箱子
'''
level_n = 1
levels = [
[[0, 0, 1, 1, 1, 0],
[0, 0, 1, 3, 1, 1],
[1, 1, 1, 2, 2, 1],
[1, 3, 2, 2, 2, 1],
[1, 1, 2, 2, 2, 1],
[0, 1, 1, 1, 1, 1]],
[[0, 1, 1, 1, 1, 1],
[0, 1, 2, 2, 3, 1],
[1, 1, 2, 2, 3, 1],
[1, 2, 2, 2, 1, 1],
[1, 1, 2, 2, 1, 0],
[0, 1, 1, 1, 1, 0]],
# Add other levels as needed
]
grid = copy.deepcopy(levels[level_n - 1])
width = len(grid[0])
height = len(grid)
origin_x = -(width - 1) / 2 * size
origin_y = (height - 1) / 2 * size
# 角色初始位置
players = [[1, 3], [4, 1]]
player_x = players[level_n - 1][0]
player_y = players[level_n - 1][1]
result = 2
# ------------------------------------------------------------
# 2.功能模块区,主要放置函数
def draw(pen, img, x, y):
'''使用画笔pen,前往坐标(x,y),绘制外观img'''
global origin_x, origin_y, size
pen.goto(origin_x + x * size, origin_y - y * size)
pen.shape(img)
pen.stamp()
def move_up():
'''角色上移'''
global player_x, player_y, grid
if result != 2:
return
player_y -= 1
# 移动范围
if player_y < 0:
player_y += 1
return
elif grid[player_y][player_x] == 1:
player_y += 1
return
# 改变地形,更新地图信息
change_grid()
def move_down():
'''角色下移'''
global player_x, player_y, grid
if result != 2:
return
player_y += 1
# 移动范围
if player_y >= height:
player_y -= 1
return
elif grid[player_y][player_x] == 1:
player_y -= 1
return
# 改变地形,更新地图信息
change_grid()
def move_left():
'''角色左移'''
global player_x, player_y, grid
if result != 2:
return
player_x -= 1
# 移动范围
if player_x < 0:
player_x += 1
return
elif grid[player_y][player_x] == 1:
player_x += 1
return
# 改变地形,更新地图信息
change_grid()
def move_right():
'''角色右移'''
global player_x, player_y, grid
if result != 2:
return
player_x += 1
# 移动范围
if player_x >= width:
player_x -= 1
return
elif grid[player_y][player_x] == 1:
player_x -= 1
return
# 改变地形,更新地图信息
change_grid()
def show_result():
global result, grid, player_x, player_y
if grid[player_y][player_x] == 4:
result = 0
else:
for i in grid:
if 2 in i:
result = 2
break
else:
result = 1
def change_grid():
'''改变地形,更新地图信息'''
global grid, player_x, player_y
if grid[player_y][player_x] == 2:
grid[player_y][player_x] = 3
elif grid[player_y][player_x] == 3:
grid[player_y][player_x] = 4
blink1()
show_result()
def next_level():
global result, level_n, grid, player_x, player_y, width, height, origin_x, origin_y, size
if result == 1:
level_n += 1
result = 2
grid = copy.deepcopy(levels[level_n - 1])
width = len(grid[0])
height = len(grid)
origin_x = -(width - 1) / 2 * size
origin_y = (height - 1) / 2 * size
player_x = players[level_n - 1][0]
player_y = players[level_n - 1][1]
def blink1():
global grid, player_x, player_y
if player_x == 1 and player_y == 5:
if level_n == 4:
player_x = 3
player_y = 2
elif player_x == 3 and player_y == 1:
if level_n == 5:
player_x = 5
player_y = 1
# ------------------------------------------------------------
# 3.操作事件区,放置键鼠操作相关的内容
turtle.onkey(move_up, 'Up')
turtle.onkey(move_down, 'Down')
turtle.onkey(move_left, 'Left')
turtle.onkey(move_right, 'Right')
turtle.onkey(next_level, 'n')
def draw_grid():
'''绘制网格和物体'''
turtle.clear()
for y in range(height):
for x in range(width):
if grid[y][x] == 0:
draw(turtle, "blank", x, y) # 空地
elif grid[y][x] == 1:
draw(turtle, "喵", x, y) # 墙
elif grid[y][x] == 2:
draw(turtle, "circle", x, y) # 通道
elif grid[y][x] == 3:
draw(turtle, "triangle", x, y) # 目标
elif grid[y][x] == 4:
draw(turtle, "circle", x, y) # 箱子(目标)
elif grid[y][x] == 5:
draw(turtle, "turtle", x, y) # 玩家
# 初始化 Turtle
turtle.speed(0)
turtle.hideturtle()
turtle.tracer(0)
turtle.listen()
# 主循环
while True:
draw_grid()
turtle.update()
turtle.done()2024-08-25T14:41:18 点赞:0
在 【Python作品分享】新的作品【求助帖】 中回复
你提供的代码片段是将字母 a-z 和空格转换为特定的数字编码。然后,再进一步将这些数字编码转换为另一组数字编码。代码可以通过使用字典来简化,减少冗余,同时提高可读性和效率。以下是修改后的版本:
n = input("请输入字符串: ")
# 首先,我们定义两个字典来进行编码
char_to_num = {chr(i): str(i - 96).zfill(2) for i in range(97, 123)} # a-z
char_to_num[' '] = ' '
# 编码第一步
s1 = ''.join(char_to_num[i] for i in n if i in char_to_num)
print("第一步编码结果:", s1)
# 第二步编码的字典
num_to_num = {str(i): str(i + 27) for i in range(10)} # 0-9
num_to_num[' '] = '00' # 处理空格
# 编码第二步
s2 = ''.join(num_to_num[i] for i in s1 if i in num_to_num)
print("第二步编码结果:", s2)
2024-08-25T14:46:22 点赞:0
在 【Python作品分享】弹球游戏【作品秀】 中回复
# 弹球游戏(壁球)
from tkinter import *
import random
import winsound
# 制作窗口
win = Tk()
cv = Canvas(win, width=喵0, height=480)
cv.pack()
# 初始化游戏
def init_game():
global is_gameover, ball_weizhi_x, ball_weizhi_y
global ball_yidong_x, ball_yidong_y, ball_size
global racket_weizhi_x, racket_size, point, speed
is_gameover = False
ball_weizhi_x = 320 # 初始位置在窗口中央
ball_weizhi_y = 250
ball_yidong_x = 15
ball_yidong_y = -15
ball_size = 10
racket_weizhi_x = 270 # 挡板初始位置
racket_size = 100
point = 0
speed = 50
win.title("弹球游戏:开始!")
# 绘制画面
def draw_screen():
cv.delete('all') # 清空画面
cv.create_rectangle(0, 0, 喵0, 480, fill="white", width=0)
def draw_ball():
cv.create_oval(ball_weizhi_x - ball_size, ball_weizhi_y - ball_size,
ball_weizhi_x + ball_size, ball_weizhi_y + ball_size, fill="red")
def draw_racket():
cv.create_rectangle(racket_weizhi_x, 470,
racket_weizhi_x + racket_size, 480, fill="yellow")
# 移动小球
def move_ball():
global is_gameover, point, ball_weizhi_x, ball_weizhi_y, ball_yidong_x, ball_yidong_y
if is_gameover: return
# 判断是否撞到了左右的墙壁
if ball_weizhi_x + ball_yidong_x < ball_size or ball_weizhi_x + ball_yidong_x > 喵0 - ball_size:
ball_yidong_x *= -1
winsound.Beep(1320, 50)
# 判断是否撞到了顶部
if ball_weizhi_y + ball_yidong_y < ball_size:
ball_yidong_y *= -1
winsound.Beep(1320, 50)
# 判断是否撞到了挡板
if ball_weizhi_y + ball_yidong_y > 470 and (
racket_weizhi_x <= (ball_weizhi_x + ball_yidong_x) <= (racket_weizhi_x + racket_size)):
ball_yidong_y *= -1
if random.choice([True, False]):
ball_yidong_x *= -1
winsound.Beep(2000, 50)
messages = ["不错!", "真棒!", "干得好!", "真厉害!", "完美!"]
message = random.choice(messages)
point += 10
win.title(f"{message} 得分={point}")
# 更新小球位置
ball_weizhi_x += ball_yidong_x
ball_weizhi_y += ball_yidong_y
# 失误时的判定
if ball_weizhi_y > 480:
messages = ["太弱啦!", "失误了哦!", "啊,惨不忍睹!"]
message = random.choice(messages)
win.title(f"{message} 得分={point}")
winsound.Beep(600, 50)
global is_gameover
is_gameover = True
# 处理鼠标动作
def motion(event):
global racket_weizhi_x
racket_weizhi_x = max(0, min(event.x - racket_size // 2, 喵0 - racket_size)) # 保持挡板在窗口内
def click(event):
if event.num == 1 and is_gameover:
init_game()
# 确认鼠标的动作和点击
win.bind('<Motion>', motion) # 绑定鼠标移动事件
win.bind('<Button-1>', click) # 绑定鼠标左键点击事件
# 使游戏循环进行
def game_loop():
draw_screen()
draw_ball()
draw_racket()
move_ball()
win.after(speed, game_loop)
# 游戏的主处理
init_game()
game_loop()
win.mainloop() 主要修改点总结:
2024-08-25T14:50:36 点赞:0
在 【Python作品分享】新的作品【作业帖】 中回复
# 查找水仙花数
for number in range(100, 1000): # 遍历100到999之间的所有数
# 将数字转换为字符串,以便逐位处理
number_str = str(number)
# 计算每位数字的立方和
zongji = sum(int(digit) ** 3 for digit in number_str)
# 判断是否为水仙花数
if zongji == number:
print(number, "是水仙花数")2024-08-25T14:51:44 点赞:0
在 自制有tkinter(UI)的爬虫 中回复
importrequests importwebbrowserasweb frombs4importBeautifulSoup importtkinterastk fromtkinterimportfiledialog fromtkinterimportttk importpyperclipasclip importjson importcodecs defshow_text(): text=entry.get() label.config(text=f"url={text}",fg="green") try: url=text headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win喵;x喵)AppleWebKit/537.36(KH喵L,likeGecko)Chrome/94.0.4606.81Safari/537.36Edg/94.0.992.47'} resp=requests.get(url,headers=headers) txt.delete('1.0','end') txt.insert('1.0',resp.text) resp.close() soup=BeautifulSoup(resp.text,'html.parser') title=soup.title.stringifsoup.titleelse"无标题" show.configure(state="normal") show.delete('1.0',"end") show.insert('1.0',f'其他信息:标题:{title}') show.configure(state="disabled") ifopen_web.get()=='爬取后自动打开网页:开': web.open(url) exceptrequests.exceptions.RequestException: label.config(text=f"url错误或你无权限访问",fg="red") exceptException: label.config(text=f"未连接网络",fg="red") defpaste_text(): entry.insert('0',clip.paste()) defcopy_text(): clip.copy(txt.get('1.0','end')) definput_text(): path=filedialog.askdirectory(title='请选择文件夹') ifpath: inputname=name.get() inputcode=txt.get('1.0','end') input_undername=com.get() file_path=f"{path}/{inputname}.{input_undername}" withopen(file_path,'w',encoding='utf-8')asfile: file.write("//欢迎使用web爬取\n") file.write(inputcode) input_get.config(text=f"选择路径为:{path},下载成功",fg="black") defon_index(): index1=com.current() index2=0ifopen_web.get()=="爬取后自动打开网页:开"else1 root_x=root.winfo_x() root_y=root.winfo_y() withopen('./index.txt','w')asfile: file.write(f"{index1}\n{index2}\n{root_x}\n{root_y}") defback(): root.destroy() #设置主窗口 root=tk.Tk() root.geometry("1000x800+0+0") root.resizable(False,False) root.title("WEB代码爬取") root.iconphoto(False,tk.PhotoImage(file='./logo.png')) #URL输入框 entry=tk.Entry(root,width=100) entry.pack(pady=20) #按钮 start=tk.Button(root,text="开始",command=show_text,width=10,height=1) start.pack() paste=tk.Button(root,text="粘贴url",command=paste_text,width=10,height=1) paste.pack(pady=5) copy=tk.Button(root,text="复制代码",command=copy_text,width=10,height=1) copy.pack() input_btn=tk.Button(root,text="下载",command=input_text,width=10,height=1) input_btn.pack(pady=5) on=tk.Button(root,text="保存配置",command=on_index,width=10,height=1) on.pack() back_btn=tk.Button(root,text="返回",command=back,width=10,height=1) back_btn.pack(pady=5) #标签 label=tk.Label(root,text="输入url",fg="black") label.pack(pady=10) #滚动文本框 scrollbar=tk.Scrollbar(root) scrollbar.pack(side=tk.RIGHT,fill=tk.Y) txt=tk.Text(root,height=10,width=80,yscrollcommand=scrollbar.set) txt.pack(side=tk.LEFT,fill=tk.BOTH,expand=True) scrollbar.config(command=txt.yview) show=tk.Text(root,height=10,width=80) show.pack(pady=10) show.configure(state="disabled") #文件名输入框 name=tk.Entry(root,width=100) name.pack(pady=5) input_get=tk.Label(root,text="选择路径为:",fg="black") input_get.pack(pady=10) #文件类型选择 com=ttk.Combobox(root,values=("html","css","js","txt")) com.pack(pady=5) com.current(0) #自动打开网页选择 open_web=ttk.Combobox(root,values=("爬取后自动打开网页:开","爬取后自动打开网页:关")) open_web.pack(pady=5) open_web.current(0) #保持窗口在最上方 root.wm_attributes('-topmost',True) #启动主循环 root.mainloop()
2024-08-25T14:55:19 点赞:0
在 自制有tkinter(UI)的爬虫 中回复
importrequests importwebbrowserasweb frombs4importBeautifulSoup importtkinterastk fromtkinterimportfiledialog fromtkinterimportttk importpyperclipasclip importjson importcodecs defshow_text(): text=entry.get() label.config(text=f"url={text}",fg="green") try: url=text headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win喵;x喵)AppleWebKit/537.36(KH喵L,likeGecko)Chrome/94.0.4606.81Safari/537.36Edg/94.0.992.47'} resp=requests.get(url,headers=headers) txt.delete('1.0','end') txt.insert('1.0',resp.text) resp.close() soup=BeautifulSoup(resp.text,'html.parser') title=soup.title.stringifsoup.titleelse"无标题" show.configure(state="normal") show.delete('1.0',"end") show.insert('1.0',f'其他信息:标题:{title}') show.configure(state="disabled") ifopen_web.get()=='爬取后自动打开网页:开': web.open(url) exceptrequests.exceptions.RequestException: label.config(text=f"url错误或你无权限访问",fg="red") exceptException: label.config(text=f"未连接网络",fg="red") defpaste_text(): entry.insert('0',clip.paste()) defcopy_text(): clip.copy(txt.get('1.0','end')) definput_text(): path=filedialog.askdirectory(title='请选择文件夹') ifpath: inputname=name.get() inputcode=txt.get('1.0','end') input_undername=com.get() file_path=f"{path}/{inputname}.{input_undername}" withopen(file_path,'w',encoding='utf-8')asfile: file.write("//欢迎使用web爬取\n") file.write(inputcode) input_get.config(text=f"选择路径为:{path},下载成功",fg="black") defon_index(): index1=com.current() index2=0ifopen_web.get()=="爬取后自动打开网页:开"else1 root_x=root.winfo_x() root_y=root.winfo_y() withopen('./index.txt','w')asfile: file.write(f"{index1}\n{index2}\n{root_x}\n{root_y}") defback(): root.destroy() #设置主窗口 root=tk.Tk() root.geometry("1000x800+0+0") root.resizable(False,False) root.title("WEB代码爬取") root.iconphoto(False,tk.PhotoImage(file='./logo.png')) #URL输入框 entry=tk.Entry(root,width=100) entry.pack(pady=20) #按钮 start=tk.Button(root,text="开始",command=show_text,width=10,height=1) start.pack() paste=tk.Button(root,text="粘贴url",command=paste_text,width=10,height=1) paste.pack(pady=5) copy=tk.Button(root,text="复制代码",command=copy_text,width=10,height=1) copy.pack() input_btn=tk.Button(root,text="下载",command=input_text,width=10,height=1) input_btn.pack(pady=5) on=tk.Button(root,text="保存配置",command=on_index,width=10,height=1) on.pack() back_btn=tk.Button(root,text="返回",command=back,width=10,height=1) back_btn.pack(pady=5) #标签 label=tk.Label(root,text="输入url",fg="black") label.pack(pady=10) #滚动文本框 scrollbar=tk.Scrollbar(root) scrollbar.pack(side=tk.RIGHT,fill=tk.Y) txt=tk.Text(root,height=10,width=80,yscrollcommand=scrollbar.set) txt.pack(side=tk.LEFT,fill=tk.BOTH,expand=True) scrollbar.config(command=txt.yview) show=tk.Text(root,height=10,width=80) show.pack(pady=10) show.configure(state="disabled") #文件名输入框 name=tk.Entry(root,width=100) name.pack(pady=5) input_get=tk.Label(root,text="选择路径为:",fg="black") input_get.pack(pady=10) #文件类型选择 com=ttk.Combobox(root,values=("html","css","js","txt")) com.pack(pady=5) com.current(0) #自动打开网页选择 open_web=ttk.Combobox(root,values=("爬取后自动打开网页:开","爬取后自动打开网页:关")) open_web.pack(pady=5) open_web.current(0) #保持窗口在最上方 root.wm_attributes('-topmost',True) #启动主循环 root.mainloop()
2024-08-25T14:55:49 点赞:0
在 通过下面的程序猜出该程序复刻的游戏以及使用的编程语言 中回复
python改法: importrequests importwebbrowserasweb frombs4importBeautifulSoup importtkinterastk fromtkinterimportfiledialog fromtkinterimportttk importpyperclipasclip defshow_text(): text=entry.get() label.config(text=f"url={text}",fg="green") try: headers={ 'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win喵;x喵)AppleWebKit/537.36(KH喵L,likeGecko)Chrome/94.0.4606.81Safari/537.36Edg/94.0.992.47' } response=requests.get(text,headers=headers) response.raise_for_status()#RaiseanHTTPErrorforbadresponses txt.delete('1.0','end') txt.insert('1.0',response.text) soup=BeautifulSoup(response.text,'html.parser') title=soup.title.stringifsoup.titleelse"无标题" show.configure(state="normal") show.delete(1.0,"end") show.insert('1.0',f'其他信息:标题:{title}') show.configure(state="disabled") ifopen_web.get()=='爬取后自动打开网页:开': web.open(text) exceptrequests.exceptions.RequestException: label.config(text=f"url错误或你无权限访问",fg="red") exceptExceptionase: label.config(text=f"发生错误:{str(e)}",fg="red") defpaste_text(): entry.delete(0,'end') entry.insert(0,clip.paste()) defcopy_text(): clip.copy(txt.get('1.0','end')) definput_text(): path=filedialog.askdirectory(title='请选择文件夹') ifnotpath: return#如果没有选择文件夹,则退出该函数 inputname=name.get() inputcode=txt.get('1.0','end') input_undername=com.get() file_path=f"{path}/{inputname}.{input_undername}" withopen(file_path,'w',encoding='utf-8')asfile: file.write("//欢迎使用web爬取\n") file.write(inputcode) input_get.config(text=f"选择路径为:{path},下载成功",fg="black") defon_index(): index1=com.current() index2=0ifopen_web.get()=="爬取后自动打开网页:开"else1 root_x=root.winfo_x() root_y=root.winfo_y() withopen('./index.txt','w')asfile: file.write(f"{index1}\n{index2}\n{root_x}\n{root_y}") defback(): root.destroy() root=tk.Tk() root.geometry("1000x800+0+0") root.resizable(False,False) root.title("WEB代码爬取") root.iconphoto(False,tk.PhotoImage(file='./logo.png')) entry=tk.Entry(root) entry.pack(pady=10,padx=10,fill=tk.X) start=tk.Button(root,text="开始",command=show_text) start.pack(pady=5) input_button=tk.Button(root,text="下载",command=input_text) input_button.pack(pady=5) paste=tk.Button(root,text="粘贴url",command=paste_text) paste.pack(pady=5) copy=tk.Button(root,text="复制代码",command=copy_text) copy.pack(pady=5) label=tk.Label(root,text="输入url",fg="black") label.pack(pady=5) scrollbar=tk.Scrollbar(root) scrollbar.pack(side=tk.RIGHT,fill=tk.Y) txt=tk.Text(root,height=10,width=80,yscrollcommand=scrollbar.set) txt.pack(side=tk.LEFT,fill=tk.BOTH,expand=True) scrollbar.config(command=txt.yview) show=tk.Text(root,height=10,width=80) show.pack() show.configure(state="disabled") name=tk.Entry(root) name.pack(pady=5) input_get=tk.Label(root,text="选择路径为:",fg="black") input_get.pack(pady=5) com=ttk.Combobox(root,values=("html","css","js","txt")) com.pack(pady=5) com.current(0)#默认选择第一个选项 open_web=ttk.Combobox(root,values=("爬取后自动打开网页:开","爬取后自动打开网页:关")) open_web.pack(pady=5) open_web.current(0)#默认选择第一个选项 on=tk.Button(root,text="保存配置",command=on_index) on.pack(pady=5) back_button=tk.Button(root,text="返回",command=back) back_button.pack(pady=5) root.wm_attributes('-topmost',True) root.mainloop()
2024-08-25T14:57:58 点赞:0
在 通过下面的程序猜出该程序复刻的游戏以及使用的编程语言 中回复
#include <easy2d/easy2d.h>
#include <windows.h>
#include <mmsystem.h>
#include <dsound.h>
#include <thread>
#include <iostream>
#pragma comment(lib, "WINMM.LIB")
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") // Disable console window
using namespace easy2d;
#define TIME 60
bool gameOver = false;
static void playBGM(void) {
if (PlaySound(TEXT("happyChicken_bgm.mp3"), NULL, SND_FILENAME | SND_ASYNC) == 0) {
printf("playsound false\n");
}
}
void playChickenCrowing() {
std::thread([] {
mciSendString(TEXT("open resources/chickenCrowing.wma alias chickenCrowing"), NULL, 0, nullptr);
mciSendString(TEXT("play chickenCrowing"), NULL, 0, nullptr);
std::this_thread::sleep_for(std::chrono::seconds(3));
mciSendString(TEXT("close chickenCrowing"), NULL, 0, nullptr);
}).detach();
}
class Chicken : public Sprite {
private:
bool isDown = false;
public:
Chicken() {
this->open("resources/happyChicken.png");
this->setAnchor(0.5, 0.5);
this->setSize(100, 100);
this->setPos(Window::getWidth() / 2, Window::getHeight() / 2);
}
void onUpdate() override {
if (gameOver) return;
if (Input::isDown(KeyCode::Space) && !isDown) {
float X = Random::range(50, Window::getWidth() - 50);
float Y = Random::range(50, Window::getHeight() - 50);
this->setPos(Point(X, Y));
isDown = true;
} else if (!Input::isDown(KeyCode::Space) && isDown) {
isDown = false;
}
}
};
class Egg : public Sprite {
public:
Egg(int x, int y) {
this->open("resources/egg.png");
this->setAnchor(0.5, 0.5);
this->setPos(x, y);
this->setScale(0.75, 0.6);
}
};
class ScoreText : public Text {
private:
bool isDown = false;
public:
unsigned int score = 0;
ScoreText() {
this->setText("Score: 0");
this->setAnchor(0.5, 0.5);
this->setPos(Window::getWidth() * (1.0 / 10.0), Window::getHeight() * (1.0 / 15.0));
}
void onUpdate() override {
if (gameOver) return;
if (Input::isDown(KeyCode::Space) && !isDown) {
this->score++;
this->setText("Score: " + std::to_string(this->score));
isDown = true;
} else if (!Input::isDown(KeyCode::Space) && isDown) {
isDown = false;
}
}
};
class Settlement_ScoreText : public Text {
private:
int score = 0;
int targetScore;
float timer = 0;
public:
Settlement_ScoreText(int _s) : targetScore(_s) {
this->setText("Score: 0");
this->setFont(Font("Arial", 20));
this->setAnchor(0.5, 0.5);
this->setPos(Window::getWidth() * (1.0 / 2.0), Window::getHeight() * (3.0 / 5.0));
}
void onUpdate() override {
if (this->score < targetScore && (timer += Time::getDeltaTime()) > 0.0025) {
timer = 0;
this->score++;
this->setText("Score: " + std::to_string(this->score));
}
}
};
class TimeText : public Text {
private:
int timeRemaining = TIME;
ScoreText* scoreText;
public:
TimeText(ScoreText* _scoreText) : scoreText(_scoreText) {
this->setText(std::to_string(timeRemaining));
this->setAnchor(0.5, 0.5);
this->setPos(Window::getWidth() * (9.0 / 10.0), Window::getHeight() * (1.0 / 15.0));
}
void onUpdate() override {
if (timeRemaining > 0) {
timeRemaining--;
this->setText(std::to_string(timeRemaining));
if (timeRemaining > 30) {
this->setFillColor(Color::White);
} else if (timeRemaining > 15) {
this->setFillColor(Color::Orange);
} else {
this->setFillColor(Color::Red);
}
} else {
this->setText("Time's up!");
this->setPos(Window::getWidth() * (1.0 / 2.0), Window::getHeight() * (1.0 / 2.0));
auto* settlementScoreText = new Settlement_ScoreText(scoreText->score);
this->addChild(settlementScoreText, 3);
gameOver = true;
}
}
};
class GameScene : public Scene {
private:
bool spacePressed = false;
float timer = 0;
Chicken* chicken;
ScoreText* scoreText;
TimeText* timeText;
Egg* newEgg;
public:
GameScene() {
mciSendString(TEXT("open resources/backgroundMusic.wma alias mysong"), NULL, 0, NULL);
mciSendString(TEXT("play mysong repeat"), NULL, 0, NULL);
Window::setTitle("Happy Chicken");
Window::setSize(1000, 1000);
Renderer::setBackgroundColor(Color::LightBlue);
SceneManager::enter(this);
chicken = new Chicken();
this->addChild(chicken, 2);
scoreText = new ScoreText();
this->addChild(scoreText, 2);
timeText = new TimeText(scoreText);
this->addChild(timeText, 2);
}
void onUpdate() override {
if (Input::isDown(KeyCode::Space) && !spacePressed) {
playChickenCrowing();
eggLaying();
spacePressed = true;
} else if (!Input::isDown(KeyCode::Space) && spacePressed) {
spacePressed = false;
}
timer += Time::getDeltaTime();
if (timer > 1) {
timeText->onUpdate(); // Update time and check game over
timer = 0.0f;
}
}
private:
void eggLaying() {
newEgg = new Egg(chicken->getPosX(), chicken->getPosY());
this->addChild(newEgg, 1);
}
};
int main() {
if (Game::init()) {
auto scene = new GameScene();
Game::start();
delete scene; // Clean up after game
}
Game::destroy();
return 0;
}
2024-08-25T15:00:44 点赞:0
在 通过下面的程序猜出该程序复刻的游戏以及使用的编程语言 中回复
import pygame
import random
import threading
import time
# Initialize Pygame
pygame.init()
# Constants
TIME = 60
WIDTH, HEIGHT = 1000, 1000
WHITE = (255, 255, 255)
LIGHT_BLUE = (173, 216, 230)
ORANGE = (255, 165, 0)
RED = (255, 0, 0)
# Load sounds
def play_bgm():
pygame.mixer.music.load("resources/backgroundMusic.wav")
pygame.mixer.music.play(-1)
def play_chicken_crowing():
threading.Thread(target=lambda: [
pygame.mixer.Sound("resources/chickenCrowing.wav").play(),
time.sleep(3),
]).start()
# Chicken class
class Chicken(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("resources/happyChicken.png")
self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2))
self.is_down = False
def update(self):
if pygame.key.get_pressed()[pygame.K_SPACE] and not self.is_down:
self.rect.x = random.randint(50, WIDTH - 50)
self.rect.y = random.randint(50, HEIGHT - 50)
self.is_down = True
elif not pygame.key.get_pressed()[pygame.K_SPACE] and self.is_down:
self.is_down = False
# Egg class
class Egg(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.image.load("resources/egg.png")
self.rect = self.image.get_rect(center=(x, y))
self.scale = (0.75, 0.6)
# ScoreText class
class ScoreText(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.score = 0
self.font = pygame.font.SysFont('Arial', 20)
self.render_text()
def render_text(self):
self.image = self.font.render(f"Score: {self.score}", True, WHITE)
self.rect = self.image.get_rect(topleft=(WIDTH // 10, HEIGHT // 15))
def update(self):
if pygame.key.get_pressed()[pygame.K_SPACE]:
self.score += 1
self.render_text()
# TimeText class
class TimeText(pygame.sprite.Sprite):
def __init__(self, score_text):
super().__init__()
self.time = TIME
self.score_text = score_text
self.font = pygame.font.SysFont('Arial', 20)
self.render_text()
def render_text(self):
self.image = self.font.render(str(self.time), True, WHITE)
self.rect = self.image.get_rect(topleft=(WIDTH * 0.9, HEIGHT // 15))
def update(self):
self.time -= 1 / 60 # assuming 60 FPS
self.render_text()
if self.time <= 0:
self.time = 0
self.image = self.font.render("Time's up!", True, WHITE)
self.rect.center = (WIDTH // 2, HEIGHT // 2)
# Game loop
def main():
global game_over
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Happy Chicken")
clock = pygame.time.Clock()
play_bgm()
chicken = Chicken()
score_text = ScoreText()
time_text = TimeText(score_text)
all_sprites = pygame.sprite.Group()
all_sprites.add(chicken, score_text, time_text)
game_over = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
all_sprites.update()
if not game_over:
if pygame.key.get_pressed()[pygame.K_SPACE]:
play_chicken_crowing()
egg = Egg(chicken.rect.centerx, chicken.rect.centery)
all_sprites.add(egg)
if time_text.time <= 0 and not game_over:
game_over = True
screen.fill(LIGHT_BLUE)
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
2024-08-25T15:03:59 点赞:0
在 熊猫烧香源代码 中回复
防止熊猫烧香代码
import os
import time
import logging
# 设置日志记录
logging.basicConfig(filename='file_monitor.log', level=logging.INFO)
# 要监控的目录
WATCHED_DIR = 'C:/watched_directory' # 替换为要监控的实际目录
# 记录已处理的文件
processed_files = set()
def monitor_directory():
while True:
for root, dirs, files in os.walk(WATCHED_DIR):
for filename in files:
file_path = os.path.join(root, filename)
# 检查文件是否已经处理过
if file_path not in processed_files:
try:
# 检查文件类型(这里假设只关注txt文件)
if filename.endswith('.txt'):
# 记录文件创建或修改
logging.info(f'File detected: {file_path}')
processed_files.add(file_path)
# 读取文件内容并检查可疑内容(示例中只是简单检查)
with open(file_path, 'r') as f:
content = f.read()
if "WARNING: Potential malware detected" in content:
logging.warning(f'Suspicious content found in: {file_path}')
print(f'Suspicious content found in: {file_path}')
except Exception as e:
logging.error(f'Error processing file {file_path}: {e}')
# 每10秒检查一次
time.sleep(10)
if __name__ == "__main__":
print("Starting file monitoring...")
monitor_directory()
2024-08-25T15:07:36 点赞:0
在 【Python作品分享】走格子(待更新)【作品秀】 中回复
importturtle importpygame importcopy pygame.mixer.init() pygame.mixer.music.load('奇妙探险.mp3') pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play() #BasicGameInfor喵 size=70 level_n=1 #LevelsDefine levels=[ [[0,0,0,0,0,0], [1,1,1,1,0,0], [1,3,2,1,0,0], [1,1,1,1,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0]], #Addlevelshere ] #InitialPlayerPosition players=[[1,2],[2,4],[1,4]] player_x=players[level_n-1][0] player_y=players[level_n-1][1] #GameState result=2 #FunctionDefinitions defdraw(pen,img,x,y): globalorigin_x,origin_y,size pen.goto(origin_x+x*size,origin_y-y*size) pen.shape(img) pen.stamp() defmove_up(): move(0,-1) defmove_down(): move(0,1) defmove_left(): move(-1,0) defmove_right(): move(1,0) defmove(dx,dy): globalplayer_x,player_y,grid ifresult!=2: return new_x=player_x+dx new_y=player_y+dy ifnot(0<=new_x<widthand0<=new_y<height): return ifgrid[new_y][new_x]==1: return player_x,player_y=new_x,new_y change_grid() defchange_grid(): globalgrid,player_x,player_y #Changeterrainlogic ifgrid[player_y][player_x]==2: grid[player_y][player_x]=3 elifgrid[player_y][player_x]==3: grid[player_y][player_x]=4 show_result() defshow_result(): globalresult ifgrid[player_y][player_x]==4: result=0 else: result=2ifany(2inrowforrowingrid)else1 defnext_level(): globalresult,level_n ifresult==1: level_n+=1 reset_level() defreset_level(): globalresult,grid,player_x,player_y result=2 grid=copy.deepcopy(levels[level_n-1]) player_x,player_y=players[level_n-1] defreset_current_level(): globalgrid,player_x,player_y,result result=2 player_x,player_y=players[level_n-1] grid=copy.deepcopy(levels[level_n-1]) #InputHandling turtle.onkey(move_up,'Up') turtle.onkey(move_down,'Down') turtle.onkey(move_left,'Left') turtle.onkey(move_right,'Right') turtle.onkey(next_level,'Return') turtle.onkey(reset_current_level,'r')#Resetcurrentlevel turtle.listen() #GraphicsSetup tile_shapes=['空.gif','墙壁2.gif','雪地.gif','冰.gif','破碎的冰.gif'] forshapeintile_shapes: turtle.addshape(shape) turtle.addshape('角色26.gif') turtle.addshape('遮罩.gif') result_shapes=['失败.gif','成功.gif','空.gif'] forshapeinresult_shapes: turtle.addshape(shape) #GameLoop p=turtle.Pen() turtle.bgpic('雪地背景.gif') p.penup() p.hideturtle() turtle.tracer(False) whileTrue: p.clear() foriinrange(width): forjinrange(height): draw(p,tile_shapes[grid[j][i]],i,j) draw(p,'角色26.gif',player_x,player_y) draw(p,'遮罩.gif',player_x,player_y) draw(p,result_shapes[result],(width-1)/2,(height-1)/2) turtle.update() turtle.done()
2024-08-25T15:10:19 点赞:0