用户:
就在天边等待你查看:16 回复:13 评论:16 创建时间:2024-08-11T18:25:52
#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\"" ) // 禁用控制台窗口
using namespace easy2d;
#define TIME 60
bool gameOver = false;
static void playBGM(void)
{
if (0 == PlaySound(TEXT("happyChicken_bgm.mp3"), NULL, SND_FILENAME | SND_ASYNC))
{
printf("playsound false");
}
}
void playchickenCrowing(void)
{
std::thread thread1([] {
mciSendString(TEXT("open resources/chickenCrowing.wma alias chickenCrowing"), NULL, 0, NULL);
mciSendString(TEXT("play chickenCrowing"), NULL, 0, NULL);
std::this_thread::sleep_for(std::chrono::seconds(3));
mciSendString(TEXT("close chickenCrowing"), NULL, 0, NULL);
});
thread1.detach();
}
class Chicken : public Sprite
{
private:
bool isDown = false;
public:
Chicken()
{
this->open("resources/happyChicken.png");
this->setAnchor(0.5, 0.5);
this->setHeight(100);
this->setWidth(100);
this->setPos(Window::getWidth() / 2, Window::getHeight() / 2);
}
void onUpdate()
{
if (gameOver)
{
return;
}
if (Input::isDown(KeyCode::Space) && !(isDown)) // If space key is pressed, move the chicken
{
float X = Random::range(50, Window::getWidth() - 50);
float Y = Random::range(50, Window::getHeight() - 50); // Fixed Y coordinate calculation
this->setPos(Point(X, Y));
isDown = true;
}
else if (!(Input::isDown(KeyCode::Space)) && isDown) // Reset when space is released
{
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()
{
if (gameOver)
{
return;
}
if (Input::isDown(KeyCode::Space) && !(isDown)) // Increment score on space press
{
this->score++;
this->setText("Score: " + std::to_string(this->score));
isDown = true;
}
else if (!(Input::isDown(KeyCode::Space)) && isDown) // Reset when space is released
{
isDown = false;
}
}
int getScore()
{
return this->score;
}
};
class Settlement_ScoreText : public Text
{
private:
int score = 0;
int s;
float timer = 0;
public:
Settlement_ScoreText(int _s)
{
this->s = _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()
{
if (this->score < this->s && (timer += Time::getDeltaTime()) > 0.0025)
{
timer = 0;
this->score++;
this->setText("Score: " + std::to_string(this->score));
}
}
};
class TimeText : public Text
{
private:
int time = TIME;
int s;
ScoreText* st;
public:
TimeText(ScoreText* _st)
{
st = _st;
this->setText(std::to_string(time));
this->setAnchor(0.5, 0.5);
this->setPos(Window::getWidth() * (9.0 / 10.0), Window::getHeight() * (1.0 / 15.0));
}
void onUpdate()
{
this->s = st->score;
}
void timeReduction()
{
this->time--;
this->setText(std::to_string(time));
if (this->time > 30)
{
this->setFillColor(Color::White);
}
else if (this->time > 15)
{
this->setFillColor(Color::Orange);
}
else if (this->time > 0)
{
this->setFillColor(Color::Red);
}
else
{
this->setText("Time's up!");
this->setPos(Window::getWidth() * (1.0 / 2.0), Window::getHeight() * (1.0 / 2.0));
Settlement_ScoreText* sst = gcnew Settlement_ScoreText(s);
this->addChild(sst, 3);
}
}
};
class GameScene : public Scene
{
private:
bool isDown = false;
float timer = 0;
int time = TIME;
Egg* newEgg;
Chicken* chicken;
ScoreText* scoreText;
TimeText* timeText;
Settlement_ScoreText* sst;
public:
GameScene()
{
mciSendString(TEXT("open resources/backgroundMusic.wma alias mysong"), NULL, 0, NULL);
mciSendString(TEXT("play mysong repeat"), NULL, 0, NULL);
// Set window title, size, and color
Window::setTitle("Happy Chicken");
Window::setSize(1000, 1000);
Renderer::setBackgroundColor(Color::LightBlue);
this->setWidth(1000);
this->setHeight(1000);
SceneManager::enter(this);
// Create Chicken and add it to the scene
chicken = gcnew Chicken;
this->addChild(chicken, 2);
// Create ScoreText and add it to the scene
scoreText = gcnew ScoreText;
this->addChild(scoreText, 2);
// Create TimeText and add it to the scene
timeText = gcnew TimeText(scoreText);
this->addChild(timeText, 2);
}
void onUpdate()
{
if (Input::isDown(KeyCode::Space) && !(isDown)) // Increment score on space press
{
playchickenCrowing();
eggLaying();
isDown = true;
}
else if (!(Input::isDown(KeyCode::Space)) && isDown) // Reset when space is released
{
isDown = false;
}
timer += Time::getDeltaTime();
if (timer > 1)
{
timeText->timeReduction();
time--;
if (time <= 0 && !gameOver)
{
gameOver = true;
sst = gcnew Settlement_ScoreText(scoreText->score);
this->removeChild(scoreText);
this->addChild(sst, 3);
mciSendString(TEXT("close mysong"), NULL, 0, NULL);
}
timer = 0.0f;
}
}
private:
void eggLaying()
{
newEgg = gcnew Egg(chicken->getPosX(), chicken->getPosY());
this->addChild(newEgg, 1);
}
};
int main()
{
if (Game::init())
{
auto scene = gcnew GameScene;
Game::start();
}
Game::destroy();
return 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()
点赞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;
}
点赞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()
点赞0
评论